Machine Learning - Reinforcement Learning Example
Imagine you are teaching a puppy the command to sit. You do not directly tell it what the word "sit" means; instead, you guide it through rewards and punishments.
- When the puppy happens to sit, you immediately give it a treat (Reward)。
- when it does something wrong, you withhold the treat (punishment)。
After many attempts, the puppy eventually understands the association between the "sit" command and getting a treat, and thus learns the skill.
Reinforcement Learning Reinforcement learning is a machine learning method in which a computer (or agent) learns, through trial and error, how to make optimal decisions by interacting with the environment in order to maximize cumulative reward.
Reinforcement LearningIt is fundamentally different from supervised learning (which has standard answers) and unsupervised learning (which finds inherent structures in data) that we studied earlier. The core of reinforcement learning is Agent The difference between Environment continuous interaction between the agent and the environment.
Core Concept Analysis
Before diving into the code, let us first understand a few key concepts. They are like the rules of a game, defining how the world of reinforcement learning works.
-
Agent:The agent is our learner or decision-maker. In the analogy above, it is the puppy. In a program, it is an algorithm responsible for observing the environment, taking actions, and learning from the results.
-
Environment:The environment is the external world in which the agent resides. It receives the agent's actions and gives two kinds of feedback: a new environment state and the immediate reward brought by the action.
-
Status:The state is a description of the specific situation of the environment at a given moment. For example, in a maze game, the state is the agent's current position coordinates.
-
Action:An action is a choice the agent can make in a given state. For example, in a maze, actions can be up, down, left, and right.
-
Reward:A reward is a direct evaluation signal from the environment for the agent's action, usually a numerical value.Positive reward indicates encouragement,negative reward indicates punishment. The agent's ultimate goal is to maximize the total reward (cumulative reward)。
-
Policy:A policy is the agent's code of behavior; it defines which action should be chosen in each possible state. The learning process is essentially the process of optimizing this policy.
To understand more intuitively how these concepts work together, let us look at the basic interaction flow of reinforcement learning:

This loop continues until a terminal state is reached (such as winning or losing the game).
Classic problem: cliff walking
To put theory into practice, we will use a classic reinforcement learning example environment:CliffWalking-v0(CliffWalking). It comes from the gymnasium Gymnasium library (a maintained fork of the original OpenAI Gym).
Environment description
- Scenario: a 4x12 grid world.
- Start point: bottom-left corner (coordinates [3, 0]).
- Endpoint: bottom-right corner (coordinates [3, 11]).
- Cliff: all positions in the bottom row except the start and the goal ([3, 1] to [3, 10]); falling into the cliff gives a huge penalty and returns you to the start.
- Goals: the agent must travel safely from the start to the goal and avoid falling off the cliff.
- Action: up (0), right (1), down (2), left (3).
- Reward:
- Each step on an ordinary tile: -1 (encourages reaching the goal in fewer steps)
- Falling off the cliff: -100, and sent back to the start
- Reaching the goal: 0, and ends the current episode
Algorithm overview: Q-Learning
We will use Q-Learning Q-Learning algorithm to solve this problem. It is a model-free reinforcement learning algorithm, meaning the agent does not need to know the rules of the environment in advance (such as state transition probabilities); it learns through continuous trial and error.
At its core is a table called the Q-table .
- line represents all possible states.
- column represents all possible actions.
- The value of a cell (Q-value) represents the long-term expected return of taking a certain action in a certain state.
The learning process of Q-Learning can be summarized in the following steps, which show how the agent updates its knowledge (the Q-table) through a single experience:

Core formula: the Bellman equation
The mathematical foundation of the Q-table update is the Bellman equation, whose update formula is as follows:
[ Q(S, A) \leftarrow Q(S, A) + \alpha [R + \gamma \max_{a} Q(S', a) - Q(S, A)] ]
Let's break down each part of this formula:
| sign before positive numbers | Meaning | Analogy explanation |
|---|---|---|
| ( Q(S, A) ) | The original Q-value of action A in state S | your previous old score for the decision to go straight at the intersection |
| (\alpha ) | Learning Rate (0 < α ≤ 1) | how much you trust this new experience. α=1 means completely overwriting old knowledge with the new experience; α=0.1 means the new experience only slightly adjusts the old knowledge |
| (R ) | the immediate rewardobtained after executing action A | after you go straight, you find the road clear and receive a small positive feedback (+1) |
| (\gamma ) | Discount factor (0 ≤ γ < 1) | how much you value future rewards. γ=0 means caring only about immediate rewards; γ=0.9 means placing great importance on long-term returns |
| (\max_{a} Q(S', a) ) | the maximum Q-value among all possible actions in the new state S' | after arriving at the new intersection, you evaluate which of turning left, turning right, or going straight has the highest future return |
| (R + \gamma \max_{a} Q(S', a)) | Target Q-value, representing a new and better estimate of the current decision | combining the immediate reward and the best future return to obtain a new score for the decision to go straight at the old intersection |
| (R + \gamma \max_{a} Q(S', a) - Q(S, A)) | temporal difference error, the gap between new and old knowledge | the difference between the new score and the old score; this difference drives learning |
In short, this formula lets the agent use immediate reward + discount of the best future estimate to continuously revise its judgment of the value of the current decision.
Hands-on: writing a Q-Learning agent
Now, let us implement in code a Q-Learning agent that solves the cliff walking problem.
Step 1: Install and import libraries
First, make sure the necessary libraries are installed. Run in a terminal or command line:
Example
pip
install
gymnasium numpy
Then, import them in your Python file:
Example
import
gymnasium
as
gym
import
numpy
as
np
import
random
Step 2: Initialize the environment and Q-table
Example
1. Create the environment
env
=
gym.
make
(
"CliffWalking-v0"
,
render_mode
=
"human"
)
render_mode="human" is used for visualization
2. Get environment information
n_states
=
env.
observation_space
.
n
Total number of states (4*12=48)
n_actions
=
env.
action_space
.
n
Total number of actions (4 directions)
3. Initialize the Q-table with shape [number of states, number of actions], all initial values set to 0
Q_table
=
np.
zeros
(
(
n_states
,
n_actions
)
)
(
f
"Number of environment states: {n_states}, number of actions: {n_actions}"
)
(
f
"Q-table shape: {Q_table.shape}"
)
Step 3: Set hyperparameters
Hyperparameters are knobs that control the algorithm's behavior and need to be adjusted according to the problem.
Example
Define hyperparameters
alpha
=
0.1
Learning rate: the degree of influence of new information
gamma
=
0.99
Discount factor: the importance of future rewards
epsilon
=
0.1
Exploration rate: with what probability to explore randomly (rather than choosing the known best)
num_episodes
=
500
Number of training episodes (how many times the agent plays the game)
Step 4: Implement the ε-greedy policy
This is the core policy for the agent's decision-making; it balances Exploration and Use。
- ExplorationExploration: randomly select actions to discover potentially better policies.
- UseExploitation: select the action the current Q-table considers best to obtain the maximum return.
Example
def
choose_action
(
state
,
Q_table
,
epsilon
)
:
"""
Select an action according to the ε-greedy policy.
Parameters:
state: current state
Q_table: the Q-value table
epsilon: exploration probability
Returns:
action: the selected action (0, 1, 2, 3)
"""
Generate a random number between 0 and 1
if
random
.
uniform
(
0
,
1
)
<
epsilon:
Exploration: randomly select an action
action
=
env.
action_space
.
sample
(
)
else
:
Exploitation: select the action with the largest Q-value in the current state
np.argmax returns the index of the maximum value, i.e., the optimal action
action
=
np.
argmax
(
Q_table
[
state
]
)
return
action
Step 5: Core training loop
This is the main process in which the algorithm learns.
Example
used to record the total reward of each episode in order to observe learning progress
reward_history
=
[
]
for
episode
in
range
(
num_episodes
)
:
Reset the environment and get the initial state
state
,
_
=
env.
reset
(
)
total_reward
=
0
Cumulative reward for this episode
terminated
=
False
Whether a terminal state has been reached (goal/cliff)
truncated
=
False
Whether it terminated due to exceeding the step limit (generally not in this environment)
The interaction loop for this episode, until the game ends
while
not
(
terminated
or
truncated
)
:
1. Select an action
action
=
choose_action
(
state
,
Q_table
,
epsilon
)
2. Execute the action and get feedback from the environment
next_state
,
reward
,
terminated
,
truncated
,
_
=
env.
step
(
action
)
3. Update the Q-table (core Q-Learning update formula)
Get the current Q-value
current_q
=
Q_table
[
state
,
action
]
Compute the target Q-value: immediate reward + discount of the maximum future Q-value
Note: if the next state is a terminal state, there is no future Q-value
if
terminated:
target_q
=
reward
else
:
target_q
=
reward + gamma * np.
max
(
Q_table
[
next_state
]
)
Apply the Bellman equation to update the Q-value
Q_table
[
state
,
action
]
=
current_q + alpha *
(
target_q - current_q
)
4. Transition to the next state and accumulate the reward
state
=
next_state
total_reward +
=
reward
Record the total reward for this episode
reward_history.
append
(
total_reward
)
Print progress every 100 episodes
if
(
episode +
1
)
%
100
==
0
:
avg_reward
=
np.
mean
(
reward_history
[
100
:
]
)
Average reward over the most recent 100 episodes
(
f
"Episode {episode + 1}, average reward over the last 100 episodes: {avg_reward:.2f}"
)
Training is over; close the environment
env.
close
(
)
Step 6: Test the trained agent
After training is complete, we turn off exploration and let the agent purely exploit the knowledge it learned (the Q-table) for one run, to see how it performs.
Example
(
"\n=== Start testing ==="
)
Create a new test environment (you can omit render_mode, or set it to "human" to watch)
test_env
=
gym.
make
(
"CliffWalking-v0"
,
render_mode
=
"human"
)
state
,
_
=
test_env.
reset
(
)
test_terminated
=
False
test_truncated
=
False
step_count
=
0
while
not
(
test_terminated
or
test_truncated
)
:
During testing, we set epsilon=0, meaning pure exploitation with no exploration
action
=
choose_action
(
state
,
Q_table
,
epsilon
=
0
)
state
,
reward
,
test_terminated
,
test_truncated
,
_
=
test_env.
step
(
action
)
step_count +
=
1
(
f
"Step {step_count}: state {state}, action {action}, reward {reward}"
)
(
f
"Testing complete! Total steps: {step_count}, total reward: {reward} (reaching the goal gives a reward of 0)"
)
test_env.
close
(
)
Running results and analysis
Complete code:
Example
import
gymnasium
as
gym
import
numpy
as
np
import
random
=========================
1. Create the environment
=========================
env
=
gym.
make
(
"CliffWalking-v0"
,
render_mode
=
"human"
)
=========================
2. Get environment information
=========================
n_states
=
env.
observation_space
.
n
n_actions
=
env.
action_space
.
n
=========================
3. Initialize the Q-table
=========================
Q_table
=
np.
zeros
(
(
n_states
,
n_actions
)
)
(
f
"Number of environment states: {n_states}"
)
(
f
"Number of actions: {n_actions}"
)
(
f
"Q-table shape: {Q_table.shape}"
)
=========================
4. Set hyperparameters
=========================
alpha
=
0.1
gamma
=
0.99
epsilon
=
0.1
num_episodes
=
500
=========================
5. ε-greedy policy
=========================
def
choose_action
(
state
,
Q_table
,
epsilon
)
:
if
random
.
uniform
(
0
,
1
)
<
epsilon:
return
env.
action_space
.
sample
(
)
return
np.
argmax
(
Q_table
[
state
]
)
=========================
6. Training loop
=========================
reward_history
=
[
]
for
episode
in
range
(
num_episodes
)
:
state
,
_
=
env.
reset
(
)
total_reward
=
0
terminated
=
False
truncated
=
False
while
not
(
terminated
or
truncated
)
:
action
=
choose_action
(
state
,
Q_table
,
epsilon
)
next_state
,
reward
,
terminated
,
truncated
,
_
=
env.
step
(
action
)
current_q
=
Q_table
[
state
,
action
]
if
terminated:
target_q
=
reward
else
:
target_q
=
reward + gamma * np.
max
(
Q_table
[
next_state
]
)
Q_table
[
state
,
action
]
=
current_q + alpha *
(
target_q - current_q
)
state
=
next_state
total_reward +
=
reward
reward_history.
append
(
total_reward
)
if
(
episode +
1
)
%
100
==
0
:
avg_reward
=
np.
mean
(
reward_history
[
100
:
]
)
(
f
"Episode {episode + 1}, average reward over the last 100 episodes: {avg_reward:.2f}"
)
env.
close
(
)
=========================
7. Test the training results
=========================
(
"\n=== Start testing ==="
)
test_env
=
gym.
make
(
"CliffWalking-v0"
,
render_mode
=
"human"
)
state
,
_
=
test_env.
reset
(
)
terminated
=
False
truncated
=
False
step_count
=
0
total_reward
=
0
while
not
(
terminated
or
truncated
)
:
action
=
choose_action
(
state
,
Q_table
,
epsilon
=
0
)
state
,
reward
,
terminated
,
truncated
,
_
=
test_env.
step
(
action
)
step_count +
=
1
total_reward +
=
reward
(
f
"Step {step_count}: state {state}, action {action}, reward {reward}"
)
(
f
"Testing complete, total steps: {step_count}, total reward: {total_reward}"
)
test_env.
close
(
)
After running the complete code above, you will see two very intuitive phenomena: the change in reward during training, and the agent's actual action path during testing.
1. Training phase: rewards gradually increase
During training, the console outputs the average reward over the most recent 100 episodes every 100 episodes. For example:
轮次 100, 最近100轮平均奖励: -120.45
轮次 200, 最近100轮平均奖励: -65.32
轮次 300, 最近100轮平均奖励: -32.18
轮次 400, 最近100轮平均奖励: -18.06
轮次 500, 最近100轮平均奖励: -13.94
You will notice a clear trend:The average reward keeps rising (the absolute value of the negative value gets smaller)。
What does this indicate?
- In the early stage of training, the agent frequently falls off the cliff and receives a large number of
-100penalties. - As training progresses, the Q-table gradually learns "which paths are dangerous and which are safe".
- The agent begins to actively avoid the cliff, choosing a safer route that is longer but carries smaller penalties.
The improvement in reward essentially reflects an improvement in policy quality.
2. Testing phase: the agent's behavior
During the testing phase, we set epsilon epsilon to 0, which means:
- No more random exploration
- Act entirely according to the optimal policy learned in the Q-table
If you enable render_mode="human"render_mode, you will see a very typical behavior:
- The agent sets off from the start
- moves horizontally along the position one tile above the cliff
- then moves downward when near the goal, arriving safely at the goal
This is precisely considered in the CliffWalking environment to be theoptimal policy:
- not the shortest path (hugging the cliff), but the
- but insteadsmallest expected penaltypath.
This reflects a core characteristic of reinforcement learning:it pursues long-term cumulative return rather than short-term optimality。
3. Why does it learn to detour instead of taking the risky direct route?
This is a very important and also very classic question.
From human intuition, walking along the cliff is the shortest path, but for the agent:
- once it takes a wrong step, it immediately receives a
-100huge penalty - by contrast, taking a few more steps only adds a few more
-1
Under the cumulative effect of the Bellman equation:
steady small losses < occasional major disasters
Therefore, Q-Learning naturally converges to a more conservative policy with a higher overall expected return.
Common questions and parameter effects
1. What happens if the learning rate α is too large or too small?
- α too large: the learning process oscillates, the policy is unstable, and it tends to repeatedly overturn existing experience
- α too small: learning is very slow, requiring many epochs to converge
In this example,0.1 is a relatively safe choice.
2. Intuitive meaning of the discount factor γ
γ → 0: the agent only cares about immediate rewards and tends to be short-sightedγ → 1: the agent attaches great importance to long-term consequences, more like a far-sighted planner
In the CliffWalking problem, a larger γ helps the agent realize that taking one more step now is to avoid greater losses in the future.
3. The essence of ε's role
ε determines the agent's personality:
- Large ε → adventurous, more exploration
- Small ε → conservative, more exploitation of existing experience
In real projects, one typically uses an ε decay strategy:
- more exploration in the early stage
- gradually converging to a stable strategy later on
Limitations of this example and directions for extension
Although Q-Learning is very classic, it also has obvious limitations:
- Q-table size grows linearly with the state space
- cannot directly handle continuous states (such as the real physical world)
- slow convergence in complex environments
This is why, in more complex problems, we introduce:
- Deep Q-Network(DQN)
- Policy Gradient
- Actor-Critic
They replace the Q-table with neural networks, enabling reinforcement learning to be applied to real scenarios such as games, robot control, and autonomous driving.
Summary
Through this complete reinforcement learning example, you have:
- understood the fundamental difference between reinforcement learning and supervised / unsupervised learning
- mastered the complete loop of agent, environment, state, action, reward, and policy
- implemented a runnable, observable, and convergent Q-Learning agent by yourself
- understood the core idea of reinforcement learning: maximizing long-term return