Deep Reinforcement Learning
Deep reinforcement learning is an exciting interdisciplinary direction in the field of artificial intelligence; we can break it down into two parts to understand it:
Reinforcement Learning is the core idea; it simulates the process by which humans or animals learn through "trial and error." Imagine teaching a puppy a new command: when it does something right, you give it a treat as a reward; when it does something wrong, there is no reward and perhaps even a slight punishment. After many attempts, the puppy learns to make the correct action in a specific situation in order to obtain the reward. The agent in reinforcement learning is like this puppy: through interaction with the environment, it adjusts its own behavior policy according to the rewards it receives.
Deep learning is a powerful tool. When the environment faced by reinforcement learning is very complex (such as video game screens or robot sensor data), traditional mathematical methods struggle to directly extract useful features from it for decision-making. Deep learning, especially deep neural networks, excels at handling this kind of high-dimensional, complex raw data (such as images and sound), and can automatically learn hierarchical feature representations of the data.
Therefore,Deep reinforcement learning = the decision-making framework of reinforcement learning + the perception and representation capabilities of deep learning. It enables the agent to learn directly from complex raw inputs (such as pixels) how to take optimal actions in order to achieve long-term goals.

Core Concepts and Basic Framework
To understand deep reinforcement learning, one must first grasp several core roles in its basic framework and the relationships between them.
Basic Elements of Reinforcement Learning
-
Agent
-
Environment
-
State (s)
-
Action (a)
-
Reward (r)
-
Policy (π)
a = π(s)), or stochastic (a ~ π(a|s))。-
Value Function
s , the expected return that can be obtained by following the current policy.s , executing action a, and then following the current policy to obtain the expected return.Interaction Process
The interaction between the agent and the environment is a continuous cyclic process, which can be clearly represented by the following flowchart:

This cycle repeats continuously; the agent collects a large amount of interaction data (s, a, r, s') and uses this data to improve its own policy.
Main Algorithms of Deep Reinforcement Learning
The family of deep reinforcement learning algorithms is mainly divided into two major categories:Value-Based and Policy-Based, and one that combines the advantages of both: Actor-Critic method.
1. Value-Based Deep Q-Networks
The core of this type of algorithm is to learn the optimal Action Value Function Q(s, a). Once an accurate Q function has been learned, the optimal policy is simple: in each state s , choose the action that yields the Q(s, a) largest Q value a。
Deep Q-Network (DQN) is a landmark piece of work. It uses a deep neural network to approximate the complex Q function.
Key Technical Innovations of DQN:
- Experience Replay: The agent stores its interaction experiences
(s, a, r, s')in a memory buffer. During training, a batch of experiences is randomly sampled from the buffer for learning. This breaks the correlations between data points, making training more stable and efficient. - Target Network: Uses a "target network" with the same structure but more slowly updated parameters to compute the learning target (the Q target value), while another "online network" is used for action selection and real-time updates. This solves the problem of the target value constantly shifting during training, greatly improving stability.
A Simplified DQN Training Procedure:
- Initialize the online network
Qand the target networkQ_target(with identical parameters), and clear the experience replay buffer. - The agent, according to the current state
s, randomly with a certain probability or according to theQnetwork, selects an actiona。 - Executes the action; the environment returns the reward
rand the new states', and stores the experience(s, a, r, s')in the replay buffer. - Randomly sample a batch of experiences from the replay buffer.
- For each sample, compute the target Q value:
y = r + γ * max_a' Q_target(s', a'). Among them,γγ is the discount factor, used to balance immediate and future rewards. - Starts with
(y - Q(s, a))^2As the loss, update the online network via gradient descentQ's parameter. - Every certain number of steps, copy the parameters of the online network to the target network.
- Repeat steps 2-7.
Advantages and Limitations:
- Advantages: Relatively high sample efficiency and relatively stable training.
- Limitation: Naturally difficult to handle continuous action spaces (because it requires computing
max_a Q(s,a)), and usually can only learn deterministic policies.
2. Policy-Based Policy Gradient Methods
These methods directly parametrize the policy π(a|s; θ)(for example, represented by a neural network), and by optimizing the policy parameters θ to directly maximize the expected return.
Core idea: By computing the gradient of the expected return J(θ) with respect to the policy parameters θ (i.e., the policy gradient), and then updating the parameters along the gradient direction, making the policy better and better.
The REINFORCE Algorithm is a classic policy gradient algorithm. Its update formula is: θ ← θ + α * ∇_θ log π(a|s; θ) * G_t where G_t is the cumulative reward from the current moment to the end of the episode,α is the learning rate.
Advantages and Limitations:
- Advantages: Can directly learn stochastic policies and is naturally suited to continuous action spaces.
- Limitation: Updates are based on the entire episode, resulting in high variance, which leads to unstable training and low sample efficiency.
3. Actor-Critic Methods
The actor-critic framework cleverly combines value-based and policy-based methods, drawing on each other's strengths.
- Actor: A policy network responsible for generating actions based on the state. It is like an actor who, under the guidance of a critic, improves its own "acting skills" (the policy).
- Critic: A value network (usually a Q-network or a V-network) responsible for evaluating the value of the actions taken by the actor in a given state. It is like a critic who scores the actor's performance.
Workflow:
- The actor, according to the current state
sand its own policy, selects and executes an actiona。 - The environment feeds back the reward
rand the new states'。 - The critic, based on
(s, a, r, s'), computes the TD error (Temporal-Difference Error, a signal that measures the difference between predicted and actual value). - The critic uses this error to update its own value-evaluation network, making its scoring more accurate.
- The actor uses the "score" provided by the critic (such as the TD error or an advantage function) to update its own policy network, making itself more inclined to choose actions that receive high scores.
Advantage: Actor-critic methods generally have lower variance and are more stable than pure policy gradient methods (such as REINFORCE), while also being better at handling continuous actions and stochastic policies than pure value-based methods (such as DQN).A3C, A2C, PPO, SAC are all highly successful actor-critic algorithms.
Practice: Playing the CartPole Game with DQN
Let's use a classic control problem CartPole(pole balancing) to gain an intuitive feel for DQN. In this environment, the cart can move left and right, and the goal is to keep the pole on the cart upright without falling.
Environment setup
We use OpenAI Gym, a reinforcement learning toolkit.
Example
Install the necessary libraries (run in Jupyter Notebook or on the command line)
!pip install gym numpy torch
import
gym
import
numpy
as
np
import
random
import
torch
import
torch.
nn
as
nn
import
torch.
optim
as
optim
import
collections
Create environment
env
=
gym.
make
(
'CartPole-v1'
)
state_dim
=
env.
observation_space
.
shape
[
0
]
State dimensions: 4 (cart position, velocity, pole angle, angular velocity)
action_dim
=
env.
action_space
.
n
Action dimensions: 2 (left, right)
(
f
"State space dimension: {state_dim}, action space size: {action_dim}"
)
Define the Q-Network
This is a simple fully connected neural network whose input is the state and whose output is the Q value corresponding to each action.
Example
class
DQN
(
nn.
Module
)
:
def
init
(
self
,
state_dim
,
action_dim
)
:
super
(
DQN
,
self
)
.
init
(
)
self
.
fc1
=
nn.
Linear
(
state_dim
,
128
)
First fully connected layer
self
.
fc2
=
nn.
Linear
(
128
,
128
)
Second fully connected layer
self
.
fc3
=
nn.
Linear
(
128
,
action_dim
)
Output layer, one Q value per action
def
forward
(
self
,
x
)
:
x
=
torch.
relu
(
self
.
fc1
(
x
)
)
Use the ReLU activation function to introduce nonlinearity
x
=
torch.
relu
(
self
.
fc2
(
x
)
)
return
self
.
fc3
(
x
)
Output Q values without passing through an activation function
Define the Experience Replay Buffer
Used to store and sample past experiences.
Example
class
ReplayBuffer:
def
init
(
self
,
capacity
)
:
self
.
buffer
=
collections
.
deque
(
maxlen
=
capacity
)
A deque that automatically discards old experiences
def
add
(
self
,
state
,
action
,
reward
,
next_state
,
done
)
:
self
.
buffer
.
append
(
(
state
,
action
,
reward
,
next_state
,
done
)
)
def
sample
(
self
,
batch_size
)
:
transitions
=
random
.
sample
(
self
.
buffer
,
batch_size
)
Organize the data into a tensor stacked by columns for easy batch processing by the neural network
state
,
action
,
reward
,
next_state
,
done
=
zip
(
*transitions
)
return
(
np.
array
(
state
)
,
action
,
reward
,
np.
array
(
next_state
)
,
done
)
def
size
(
self
)
:
return
len
(
self
.
buffer
)
Define the DQN Agent
Integrates the network, experience replay, and training logic.
Example
class
DQNAgent:
def
init
(
self
,
state_dim
,
action_dim
,
lr
=
1e-3
,
gamma
=
0.98
,
epsilon
=
0.01
,
target_update_freq
=
10
,
buffer_size
=
10000
,
batch_size
=
64
)
:
self
.
action_dim
=
action_dim
self
.
q_net
=
DQN
(
state_dim
,
action_dim
)
Online network
self
.
target_q_net
=
DQN
(
state_dim
,
action_dim
)
Target network
self
.
target_q_net
.
load_state_dict
(
self
.
q_net
.
state_dict
(
)
)
Identical initial parameters
self
.
optimizer
=
optim.
Adam
(
self
.
q_net
.
parameters
(
)
,
lr
=
lr
)
Optimizer
self
.
gamma
=
gamma
Discount factor
self
.
epsilon
=
epsilon
Exploration rate (final)
self
.
target_update_freq
=
target_update_freq
Target network update frequency
self
.
batch_size
=
batch_size
self
.
buffer
=
ReplayBuffer
(
buffer_size
)
self
.
count
=
0
Record the update step count
def
take_action
(
self
,
state
,
epsilon
=
None
)
:
"""Select an action according to the epsilon-greedy policy"""
if
epsilon
is
None
:
epsilon
=
self
.
epsilon
if
np.
random
.
random
(
)
<
epsilon:
return
np.
random
.
randint
(
self
.
action_dim
)
Exploration: random selection
else
:
state
=
torch.
tensor
(
state
,
dtype
=
torch.
float
)
.
unsqueeze
(
0
)
Add a batch dimension
with
torch.
no_grad
(
)
:
q_values
=
self
.
q_net
(
state
)
return
q_values.
argmax
(
)
.
item
(
)
Exploitation: choose the action with the largest Q value
def
update
(
self
)
:
"""Sample from the experience replay buffer and update the network"""
if
self
.
buffer
.
size
(
)
<
self
.
batch_size
:
return
1. Sampling
states
,
actions
,
rewards
,
next_states
,
dones
=
self
.
buffer
.
sample
(
self
.
batch_size
)
Convert to a PyTorch tensor
states
=
torch.
tensor
(
states
,
dtype
=
torch.
float
)
actions
=
torch.
tensor
(
actions
)
.
unsqueeze
(
1
)
The shape becomes [batch_size, 1] for easy gather operations
rewards
=
torch.
tensor
(
rewards
,
dtype
=
torch.
float
)
.
unsqueeze
(
1
)
next_states
=
torch.
tensor
(
next_states
,
dtype
=
torch.
float
)
dones
=
torch.
tensor
(
dones
,
dtype
=
torch.
float
)
.
unsqueeze
(
1
)
2. Compute the current Q value (Q(s, a))
current_q_values
=
self
.
q_net
(
states
)
.
gather
(
1
,
actions
)
Extract only the Q value corresponding to the executed action a
3. Compute the target Q value (r + γ * max_a' Q_target(s', a'))
with
torch.
no_grad
(
)
:
next_q_values
=
self
.
target_q_net
(
next_states
)
.
max
(
1
)
[
0
]
.
unsqueeze
(
1
)
Take the maximum Q value of the next state
target_q_values
=
rewards +
self
.
gamma
- next_q_values *
(
1
- dones
)
If the episode ends (done=1), there is no future reward
4. Compute the loss (mean squared error)
loss
=
nn.
MSELoss
(
)
(
current_q_values
,
target_q_values
)
5. Update the online network via gradient descent
self
.
optimizer
.
zero_grad
(
)
loss.
backward
(
)
Optional: gradient clipping to prevent exploding gradients
torch.nn.utils.clip_grad_norm_(self.q_net.parameters(), max_norm=10)
self
.
optimizer
.
step
(
)
self
.
count
=
1
6. Periodically update the target network
if
self
.
count
%
self
.
target_update_freq
==
0
:
self
.
target_q_net
.
load_state_dict
(
self
.
q_net
.
state_dict
(
)
)
Training loop
Example
def
train_agent
(
env
,
agent
,
num_episodes
=
500
,
max_steps
=
500
,
initial_epsilon
=
0.9
,
epsilon_decay
=
0.995
)
:
"""Train the agent"""
return_list
=
[
]
Record the total reward for each episode
epsilon
=
initial_epsilon
for
i_episode
in
range
(
num_episodes
)
:
state
,
_
=
env.
reset
(
)
episode_return
=
0
done
=
False
for
step
in
range
(
max_steps
)
:
1. Select and execute an action
action
=
agent.
take_action
(
state
,
epsilon
)
Use the decayed exploration rate
next_state
,
reward
,
done
,
truncated
,
_
=
env.
step
(
action
)
2. Store the experience
agent.
buffer
.
add
(
state
,
action
,
reward
,
next_state
,
done
)
state
=
next_state
episode_return +
=
reward
3. Update the network
agent.
update
(
)
if
done
or
truncated:
break
Exploration rate decay
epsilon
=
max
(
agent.
epsilon
,
epsilon * epsilon_decay
)
return_list.
append
(
episode_return
)
if
(
i_episode +
1
)
%
50
==
0
:
(
f
"Episode: {i_episode+1}, average reward (last 50 episodes): {np.mean(return_list[-50:]):.1f}, exploration rate: {epsilon:.3f}"
)
(
"Training complete!"
)
return
return_list
Create the agent and start training
agent
=
DQNAgent
(
state_dim
,
action_dim
,
lr
=
1e-3
,
gamma
=
0.99
,
epsilon
=
0.01
)
returns
=
train_agent
(
env
,
agent
,
num_episodes
=
300
)
Test the trained agent
Example
def
test_agent
(
env
,
agent
,
num_episodes
=
5
,
render
=
True
)
:
"""Test the agent's performance"""
total_rewards
=
[
]
for
i
in
range
(
num_episodes
)
:
state
,
_
=
env.
reset
(
)
episode_return
=
0
done
=
False
while
not
done:
if
render:
env.
render
(
)
Visualize the environment; when running locally, you can see the cart balancing the pole
action
=
agent.
take_action
(
state
)
Use the minimum exploration rate during testing (i.e., pure exploitation)
next_state
,
reward
,
done
,
truncated
,
_
=
env.
step
(
action
)
state
=
next_state
episode_return +
=
reward
if
done
or
truncated:
break
total_rewards.
append
(
episode_return
)
(
f
"Test episode {i+1}: total reward = {episode_return}"
)
env.
close
(
)
(
f
"Average test reward: {np.mean(total_rewards):.1f}"
)
Test the agent
test_agent
(
env
,
agent
,
num_episodes
=
3
,
render
=
False
)
Set render=False in a GUI-less environment
Challenges and Future Directions of Deep Reinforcement Learning
Despite its great success, deep reinforcement learning still faces many challenges:
- Low Sample Efficiency: Typically requires far more interaction data than humans or traditional methods to learn a task.
- Unstable training: Very sensitive to hyperparameters (learning rate, network structure, etc.), and the training process is prone to divergence.
- Difficult Reward Design: Designing a reward function that correctly guides the agent toward the ultimate goal is itself a difficult problem.
- Safety and Interpretability: How to ensure the agent's behavior is safe, reliable, and as expected, and how to understand its decision-making process.
Future research is advancing in directions such as more efficient algorithms (e.g., model-based reinforcement learning), more powerful representation learning, multi-task and meta-learning, and safe alignment with the real world.
Summary and Exercises
Deep reinforcement learning combines the perceptual capabilities of deep learning with the decision-making framework of reinforcement learning, enabling machines to learn to accomplish advanced tasks in complex environments. You have learned its core concepts and main algorithm families, and gained hands-on experience through the DQN practice code.
Exercises and Reflection:
- Modify the code: Try adjusting the
DQNAgenthyperparameters in the code (such aslr,gamma,batch_size), and observe their impact on training speed and final performance. - Change the Environment: Try applying the code to other environments in Gym, such as
MountainCar-v0orLunarLander-v2. Pay attention to adjusting the dimensions of the state and action. - Algorithm Comparison: Read about and try to implement a simple policy gradient algorithm (such as REINFORCE) to solve the CartPole problem, and compare its differences from DQN in terms of training stability and sample efficiency.
- Further Exploration: Choose a modern advanced algorithm (such as PPO or SAC), read its paper or open-source implementation, and understand which problems in DQN or policy gradients it solves.