Fundamental Framework of Reinforcement Learning
Imagine you are teaching a puppy the "sit" command. You wouldn't directly tell it how to move every muscle for the sitting action; instead, you would do this:
- You give the "sit" command.
- The puppy tries to make some movement (it might sit, lie down, or spin around).
- If it sits, you immediately give it a treat as a reward.
- If it does something wrong, you give no reward, or give a slight "wrong" signal.
- After many attempts, the puppy gradually understands: after hearing "sit", making the sitting action earns a treat. Thus it has learned the command.
Reinforcement Learning It means letting a computer (or agent), like this puppy, learn how to make a series of decisions through interaction with the environment and based on the rewards or penalties received, in order to achieve a long-term goal.
It is fundamentally different from the familiarSupervised Learning(the "teacher" with standard answers) andUnsupervised learning(seeking the inherent structure of data). Reinforcement learning islearning from experience, whose core istrial and errorThe difference betweendelayed reward。
Core Elements of Reinforcement Learning
To formally describe this learning process, we introduce several core concepts that together form the basic framework of reinforcement learning.
Agent and Environment
This is the most basic pair of interacting entities in reinforcement learning.
- Agent: is the subject of learning, the entity that makes decisions. In the example above, the puppy is the agent. In a computer, it can be an algorithm, a program, or a robot.
- Environment: is the external world in which the agent lives and with which it interacts. For the puppy, the environment is you, the treats, the floor, and everything else external. The environment receives the agent's actions and gives new states and rewards.

Their relationship is a continuous cycle:The agent observes the environment -> takes an action -> the environment feeds back a new state and reward -> the agent observes again...

State, Action, and Reward
These are the three key pieces of information that describe each interaction.
- State: a complete description of the environment at a certain moment. For example, in the puppy-teaching case, the state might include: the puppy is standing, you are holding a treat, you just said "sit". The state is the basis for the agent's decision.
- Action: the choices the agent can make in a given state. For the puppy, the action set might be {sit, lie down, stand, spin...}.
- Reward: a scalar signal that the environment feeds back to the agent after it performs an action. It defineswhat is good and what is bad. Reward is the only compass for the agent's learning. Giving the puppy a treat is a positive reward (+1), while saying "wrong" can be seen as a slight negative reward (-0.1).
Strategy
Strategy The policy is the agent's brain or code of conduct. It defines which action the agent should take in any given state.
A policy can be a simple lookup table function or a complex deep neural network. The ultimate goal of reinforcement learning is to find anoptimal policythat enables the agent to obtain from the environment themaximization of long-term cumulative reward。
- Example: a simple policy might be: if the state is hearing the "sit" command, then choose the sit action with 90% probability and other actions with 10% probability.
Value Function
Reward tells the agentCurrentthe immediate goodness or badness of an action, but the agent needs to care more aboutthe long termreturns.Value Function The value function is the tool used to measure this long-term return.
The question it answers is: starting from the current state and following a certain policy all the way, Iexpectto obtain in total reward?
- State Value Function V(s): measures, in state
sthe long-term value of following the current policy. - Action Value Function Q(s, a): measures, in state
s, thenperforming a specific actionaand then following the current policy, the long-term value. It is more commonly used than the state value function because it can directly guide action selection.
Why do we need a value function? Imagine a chess game. Capturing an opponent's pawn gives an immediate small reward, but may lead to being "checkmated" ten moves later and receiving a huge negative reward. Through calculation and estimation, the value function helps the agent avoid such behavior of grasping small gains while losing the whole game.
Core Interaction Flow: Markov Decision Process
Reinforcement learning problems are usually modeled as a Markov Decision Process. This name sounds complex, but in fact it just organizes the elements we mentioned above in mathematical form, describing a standard framework for agent-environment interaction.
The core idea of MDP is:the next state and reward depend only on the current state and the current action taken, independent of previous history(i.e., the Markov property).
A complete MDP interaction cycle is as follows:

- At time
t, the environment is in stateS_t。 - The agent observes this state.
- The agent, according to its policy
π, selects an actionA_t。 - The environment receives this action.
- The environment, according to its internal dynamics, transitions to the next state
S_{t+1}and produces a scalar rewardR_{t+1}which is fed back to the agent. - The time step advances (
t = t+1), and a new cycle begins.

The agent's goal is to learn a policy by continuously going through this cycle π*so that, starting from any initial state, theexpected value of cumulative reward (i.e., return) is maximized。
A Simple Code Example: Grid World
Let's use a classic grid world example to make these concepts concrete. Suppose there is a 4x4 grid, and the agent starts from the starting point S and the goal is to reach the end point G. Stepping onto an obstacle # means failure, and each step carries a small penalty (to encourage reaching the goal as quickly as possible).
S . . .
. # . .
. . # .
. . . G
- State: the coordinates of each grid, such as (0,0), (0,1)... (3,3). There are 16 states in total.
- Action: {up, down, left, right}.
- Reward:
- Reaching
G: +10 - Hitting
#or going out of bounds: -5 - Other normal moves: -0.1 (encourage efficient paths)
- Strategy: we need to learn a table that records, in each state (cell), which direction to go.
Below is a highly simplified pseudocode demonstration of Q-learning (a classic reinforcement learning algorithm) for learning the optimal path in this grid world.
Example
import
numpy
as
np
import
random
from
typing
import
Dict
,
List
,
Tuple
====================== 1. Environment Simulation (Grid World) ======================
class
GridWorldEnv:
"""A simple grid world environment to demonstrate Q-Learning"""
def
init
(
self
,
grid_size: Tuple
[
int
,
int
]
=
(
5
,
5
)
,
start_pos: Tuple
[
int
,
int
]
=
(
0
,
0
)
,
goal_pos: Tuple
[
int
,
int
]
=
(
4
,
4
)
,
obstacle_pos: List
[
Tuple
[
int
,
int
]
]
=
[
(
1
,
1
)
,
(
2
,
2
)
,
(
3
,
1
)
]
)
:
self
.
grid_size
=
grid_size
self
.
start_pos
=
start_pos
self
.
goal_pos
=
goal_pos
self
.
obstacle_pos
=
obstacle_pos
self
.
current_pos
=
start_pos
Action definitions: 0-up, 1-down, 2-left, 3-right
self
.
actions
=
[
'up'
,
'down'
,
'left'
,
'right'
]
self
.
num_actions
=
len
(
self
.
actions
)
def
reset
(
self
)
int
:
"""Reset the environment and return the index of the initial state"""
self
.
current_pos
=
self
.
start_pos
return
self
.
pos_to_state
(
self
.
current_pos
)
def
pos_to_state
(
self
,
pos: Tuple
[
int
,
int
]
)
int
:
"""Convert a coordinate position to a state index"""
return
pos
[
0
]
self
.
grid_size
[
1
]
- pos
[
1
]
def
state_to_pos
(
self
,
state:
int
)
Tuple
[
int
,
int
]
:
"""Convert a state index to a coordinate position"""
return
(
state //
self
.
grid_size
[
1
]
,
state %
self
.
grid_size
[
1
]
)
def
random_action
(
self
)
int
:
"""Randomly select an action (exploration)"""
return
random
.
randint
(
0
,
self
.
num_actions
1
)
def
action_to_direction
(
self
,
action:
int
)
str
:
"""Convert an action index to a direction name"""
return
self
.
actions
[
action
]
def
step
(
self
,
action:
int
)
Tuple
[
int
,
float
,
bool
]
:
"""
Execute an action, return (next_state, reward, done)
Optimization: fix the bug where the obstacle reward could not be triggered, simplify the logic
"""
x
,
y
=
self
.
current_pos
Update the position according to the action
if
action
==
0
:
up
x
=
max
(
0
,
x -
1
)
elif
action
==
1
:
down
x
=
min
(
self
.
grid_size
[
0
]
1
,
x +
1
)
elif
action
==
2
:
Left
y
=
max
(
0
,
y -
1
)
elif
action
==
3
:
Right
y
=
min
(
self
.
grid_size
[
1
]
1
,
y +
1
)
Check whether an obstacle is hit (core fix: first record whether an obstacle was hit, then handle the position)
new_pos
=
(
x
,
y
)
hit_obstacle
=
False
Record whether an obstacle was hit
if
new_pos
in
self
.
obstacle_pos
:
hit_obstacle
=
True
Record the obstacle collision status
new_pos
=
self
.
current_pos
If an obstacle is hit, the position stays unchanged
self
.
current_pos
=
new_pos
next_state
=
self
.
pos_to_state
(
new_pos
)
Compute the reward (based on the pre-recorded hit_obstacle, fixing the original logical contradiction)
if
new_pos
==
self
.
goal_pos
:
reward
=
100.0
Reach the goal, large reward
done
=
True
elif
hit_obstacle:
Judge based on the flag, not the modified new_pos
reward
=
50.0
Hit an obstacle, penalty
done
=
False
else
:
reward
=
1.0
A small penalty for each step, encouraging reaching the goal as soon as possible
done
=
False
return
next_state
,
reward
,
done
====================== 2. Q-Learning Main Program ======================
if
name
==
"main"
:
Optimization 1: fix the random seed to ensure reproducible experimental results
random_seed
=
42
random
.
seed
(
random_seed
)
np.
random
.
seed
(
random_seed
)
Initialize the environment
env
=
GridWorldEnv
(
grid_size
=
(
5
,
5
)
,
5x5 grid
start_pos
=
(
0
,
0
)
,
Start point
goal_pos
=
(
4
,
4
)
,
Endpoint
obstacle_pos
=
[
(
1
,
1
)
,
(
2
,
2
)
,
(
3
,
1
)
]
Obstacle positions
)
Compute the number of states
num_states
=
env.
grid_size
[
0
]
- env.
grid_size
[
1
]
num_actions
=
env.
num_actions
Initialize the Q-table (action value function) with shape [number of states, number of actions]
Q_table
=
np.
zeros
(
[
num_states
,
num_actions
]
)
Define hyperparameters
learning_rate
=
0.1
Learning Rate
discount_factor
=
0.9
Discount factor
epsilon
=
0.1
Exploration rate
total_episodes
=
1000
Number of Training Epochs
Training process
for
episode
in
range
(
total_episodes
)
:
state
=
env.
reset
(
)
Reset the environment to the start, obtain the initial state S
done
=
False
Flag whether this episode is over
total_reward
=
0
Record the total reward for this episode
while
not
done:
1. ε-greedy policy selects an action
if
random
.
uniform
(
0
,
1
)
<
epsilon:
action
=
env.
random_action
(
)
Exploration: randomly select an action
else
:
Exploitation: select the action with the highest Q-value, handling ties
q_values
=
Q_table
[
state
]
max_q
=
np.
max
(
q_values
)
best_actions
=
np.
where
(
q_values
==
max_q
)
[
0
]
action
=
random
.
choice
(
best_actions
)
When tied, randomly select one
2. Execute an action and interact with the environment
next_state
,
reward
,
done
=
env.
step
(
action
)
total_reward +
=
reward
3. Update the Q-table (core: the Q-Learning formula)
Q(S, A) = Q(S, A) + α * [ R + γ * max(Q(S', a')) - Q(S, A) ]
old_value
=
Q_table
[
state
,
action
]
next_max
=
np.
max
(
Q_table
[
next_state
]
)
The maximum Q-value of the next state
Compute the target Q-value
target
=
reward + discount_factor * next_max
Update the Q-value
new_value
=
old_value + learning_rate *
(
target - old_value
)
Q_table
[
state
,
action
]
=
new_value
4. Move to the next state
state
=
next_state
Print the training progress every 100 episodes
if
(
episode +
1
)
%
100
==
0
:
(
f
"Episode {episode + 1}/{total_episodes}, Total Reward: {total_reward:.1f}"
)
====================== 3. Extract the Optimal Policy (Optimized Print Format, More Intuitive) ======================
policy: Dict
[
int
,
str
]
=
{
}
(
"\n=== Optimal Policy After Learning (Laid Out by Grid) ==="
)
Optimization 2: print according to the grid shape, intuitively showing the policy for the entire grid
grid_rows
,
grid_cols
=
env.
grid_size
for
row
in
range
(
grid_rows
)
:
row_str
=
[
]
for
col
in
range
(
grid_cols
)
:
pos
=
(
row
,
col
)
state
=
env.
pos_to_state
(
pos
)
if
pos
in
env.
obstacle_pos
:
row_str.
append
(
" Obstacle "
)
elif
pos
==
env.
goal_pos
:
row_str.
append
(
" Goal "
)
elif
pos
==
env.
start_pos
:
Also mark the starting point and its optimal action
best_action_idx
=
np.
argmax
(
Q_table
[
state
]
)
best_action
=
env.
action_to_direction
(
best_action_idx
)
row_str.
append
(
f
" Start({best_action}) "
)
else
:
best_action_idx
=
np.
argmax
(
Q_table
[
state
]
)
best_action
=
env.
action_to_direction
(
best_action_idx
)
policy
[
state
]
=
best_action
row_str.
append
(
f
" {best_action} "
)
(
"|"
.
join
(
row_str
)
)
====================== 4. Test the Optimal Policy ======================
(
"\n=== Test the Optimal Policy ==="
)
state
=
env.
reset
(
)
done
=
False
steps
=
0
path
=
[
env.
state_to_pos
(
state
)
]
while
not
done
and
steps
<
50
:
At most 50 steps to prevent an infinite loop
best_action_idx
=
np.
argmax
(
Q_table
[
state
]
)
next_state
,
reward
,
done
=
env.
step
(
best_action_idx
)
current_pos
=
env.
state_to_pos
(
next_state
)
path.
append
(
current_pos
)
state
=
next_state
steps +
=
1
(
f
"Path: {path}"
)
(
f
"Steps to reach the goal: {steps}"
)
(
f
"Reached the goal: {env.current_pos == env.goal_pos}"
)
Code Analysis:
Q_tableis the core action value function, with shape[状态数量,动作数量](in the example it is 25×4, corresponding to 25 states of the 5×5 grid and 4 actions: up, down, left, right).Q_table[s, a]It represents, in states(the index of the grid position), executing actiona(0-3 corresponds to up, down, left, right), the long-term value, initialized all to 0 and gradually updated through training.env.step(action)Simulates the core interaction logic of the Markov Decision Process (MDP): after inputting an action index, first update the agent's grid position (if an obstacle is hit, the position stays unchanged), then return the triple(next_state, reward, done)——next_stateis the index of the new state,rewardis the differentiated reward (goal +100, obstacle -50, each step -1),doneflags whether the goal has been reached (this episode ends).- The Core Update Formula of Q-Learning
Q(S,A) = Q(S,A) + α * [R + γ * max(Q(S', a')) - Q(S,A)]is implemented in the code by breaking it down: first obtain the current Q-valueold_valuethen compute the maximum Q-value of the next statenext_maxnext calculate the target valuetarget = 奖励 + 折扣因子 × 下一状态最大Q值finally, using the learning rateαto mix the old value with the target value, obtaining the updated Q-value and achieving iterative correction of the action value. epsilon(exploration rate) balances "exploitation" and "exploration" through the ε-greedy policy: withepsilonprobability randomly select an action (explore the unknown), with1-epsilonprobability select the action with the largest Q-value in the current state (exploit the known best); the code also optimizes the case of Q-value ties — if multiple actions have the same Q-value, randomly select one to avoid policy solidification caused by a single choice.- The code additionally implements bidirectional mapping between states and grid positions (
pos_to_state/state_to_pos), conversion between actions and direction names (action_to_direction), as well as policy extraction and testing after training: traverse all states, take the action with the largest Q-value in each state as the optimal policy, and verify the path and number of steps of this policy from start to goal.
Output:
Episode 100/1000, Total Reward: 93.0
Episode 200/1000, Total Reward: 90.0
Episode 300/1000, Total Reward: 92.0
Episode 400/1000, Total Reward: 90.0
Episode 500/1000, Total Reward: 93.0
Episode 600/1000, Total Reward: 93.0
Episode 700/1000, Total Reward: 91.0
Episode 800/1000, Total Reward: 93.0
Episode 900/1000, Total Reward: 93.0
Episode 1000/1000, Total Reward: 93.0
=== 学习完成后的最优策略 ===
位置 (0, 0): 最优动作 = right
位置 (0, 1): 最优动作 = right
位置 (0, 2): 最优动作 = down
位置 (0, 3): 最优动作 = down
位置 (0, 4): 最优动作 = down
位置 (1, 0): 最优动作 = up
位置 (1, 1): 最优动作 = 障碍物
位置 (1, 2): 最优动作 = right
位置 (1, 3): 最优动作 = down
位置 (1, 4): 最优动作 = left
位置 (2, 0): 最优动作 = down
位置 (2, 1): 最优动作 = down
位置 (2, 2): 最优动作 = 障碍物
位置 (2, 3): 最优动作 = down
位置 (2, 4): 最优动作 = down
位置 (3, 0): 最优动作 = down
位置 (3, 1): 最优动作 = 障碍物
位置 (3, 2): 最优动作 = right
位置 (3, 3): 最优动作 = right
位置 (3, 4): 最优动作 = down
位置 (4, 0): 最优动作 = right
位置 (4, 1): 最优动作 = right
位置 (4, 2): 最优动作 = right
位置 (4, 3): 最优动作 = right
位置 (4, 4): 最优动作 = 终点
=== 测试最优策略 ===
路径: [(0, 0), (0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (3, 3), (3, 4), (4, 4)]
到达终点步数: 8
是否到达终点: True
Summary and Practical Reflections
The basic framework of reinforcement learning can be summarized as follows:Through Markov Decision Process-style interactions with the environment, the agent continuously optimizes its policy (usually by learning and updating a value function) according to the reward signals received, with the ultimate goal of maximizing long-term cumulative reward.
| Concept | Analogy | Role in Reinforcement Learning |
|---|---|---|
| Agent | The learning puppy / the chess-playing AI | The decision-making subject, the algorithm performing learning |
| Environment | The trainer / the rules of the chessboard | The external system that provides state and reward feedback |
| State | The puppy's posture / the board position | The current information basis for the agent's decisions |
| Action | Sit / move a chess piece | The choices the agent can make |
| Reward | Treats / win-or-lose outcome | The immediate signal evaluating how good or bad an action is, the compass for learning |
| Strategy | The command response the puppy has learned | The mapping rule from state to action, the goal of learning |
| Value Function | Long-term judgment of the situation | Evaluate the long-term value of a state or action, the basis for policy optimization |