Skip to main content
This code is implementing a simple Q-learning agent using a neural network to learn how to play the CartPole game. The easiest way to understand it is:
State → Neural Network → Q-values → Choose action → Get reward → Update network

1. Import Gymnasium

Gymnasium provides environments for Reinforcement Learning (RL). Here we use:
CartPole is a simple game where the agent tries to keep a pole balanced on a moving cart. The agent can take only two actions:

2. Import PyTorch

PyTorch is used to build and train the neural network. We need it for:
  • Tensors
  • Neural networks
  • Loss calculation
  • Backpropagation
  • Optimization

3. Import neural network module

torch.nn contains tools for creating neural networks. We use:

4. Import optimizer

The optimizer updates the neural network’s weights. We’ll use:
Adam is a popular optimization algorithm.

5. Create CartPole environment

This creates the game environment. The environment gives us a state. The CartPole state has 4 values:
For example:
These four numbers tell the agent what’s currently happening.

6. Create the Q-network

This is the brain of the agent. Let’s break it down.

First layer

Input:
Output:
So:

7. ReLU activation

ReLU is an activation function. Conceptually:
For example:
It allows the neural network to learn nonlinear relationships.

8. Output layer

The network produces 2 numbers. Why 2? Because CartPole has two possible actions:
The output represents the estimated Q-value for each action. For example:
The agent thinks:
because:
So the complete network is:

9. Create optimizer

Adam is responsible for changing the neural network’s weights.

model.parameters()

Means:
Give Adam all the weights and biases of the model.

lr=0.001

lr means learning rate. It controls how much the model changes during each update.

10. Train for 100 episodes

An episode means one complete game attempt. So the agent plays:

11. Reset the environment

At the beginning of every episode, we reset CartPole. The environment gives us the initial state. For example:

12. Start reward counter

We want to know how well the agent performed during the episode. So we start at:
Every successful timestep adds reward.

13. Run up to 500 steps

Each episode can have a maximum of 500 steps. Think:
The episode can end before 500 if the pole falls.

14. Convert state to PyTorch tensor

Gymnasium gives us normal numerical data. PyTorch needs tensors. So:
float32 means the numbers are stored as 32-bit floating-point values.

15. Predict Q-values

The current state goes into the neural network. For example:
Meaning:

16. Choose the best action

argmax() finds the position of the largest value. If:
then:
Its index is:
Therefore:
The agent chooses:
So this code is using a greedy policy:
Always choose the action with the highest predicted Q-value.

17. Perform the action

This is where the agent interacts with the environment. It says:
“CartPole, I’m choosing action 1.”
The environment responds with:

next_state

What the game looks like after the action.

reward

How much reward the agent received. Usually CartPole gives:
for each step the pole remains balanced.

terminated

Whether the episode ended because the task reached a terminal condition.

truncated

Whether the episode ended because of a time/step limit.

info

Additional environment information.

18. Convert next state to tensor

Same idea as before. We’re converting:
into a PyTorch tensor so the neural network can process it.

19. Don’t calculate gradients

We’re about to calculate the target Q-value. We don’t want this calculation itself to affect the neural network through gradients. So:
means:
Calculate this without tracking gradients.

20. Calculate the next Q-value

The model predicts Q-values for the next state. For example:
Then:
takes:
So:
This means:
“According to the current model, what is the best possible future Q-value?“

21. Calculate target Q-value

This is the heart of Q-learning. The basic Q-learning idea is:
In mathematical form: Qtarget=r+γmaxQ(s,a)Q_{target} = r + \gamma \max Q(s',a') Here:
So if:
then approximately:

22. Why 0.99?

is the discount factor, usually written as: γ\gamma It controls how much we care about future rewards.
So the agent learns:
“Don’t just think about what happens now. Think about future rewards too.”

23. Why this part?

Suppose the episode hasn’t ended:
Then:
So future reward is included. But if the episode ended:
then:
Therefore:
We don’t consider future rewards after the episode has ended.

24. Get current Q-value

Earlier we had:
and selected:
Therefore:
which is:
So:
means:
The model’s current prediction for the action it actually took.

25. Calculate loss

This measures how wrong the model’s prediction was. Suppose:
Then:
The bigger the difference:
the bigger the loss. The neural network then tries to reduce this error. This is essentially mean squared error for one Q-value.

26. Clear previous gradients

Before calculating new gradients, we clear old gradients. Think:

27. Backpropagation

This calculates how each neural-network parameter contributed to the error. In simple terms:
“Which weights caused my prediction to be wrong, and in what direction should they change?“

28. Update the model

Adam now changes the model’s weights based on the gradients. So:
This is how the model learns.

29. Move to next state

The current state becomes the next state. For example:
Then the process repeats.

30. Add reward

If the agent receives:
we add it to the total. For example:
If it survives 100 steps:
Higher reward generally means better performance.

31. Stop if episode is finished

If CartPole has ended, stop the current episode. For example:

32. Print episode reward

This shows how well the agent performed. Example:
If the agent is learning properly, generally hope to see rewards trend upward, although this particular implementation can be unstable.

33. Close the environment

When training is finished, close the CartPole environment and release its resources.

The Complete Learning Cycle

This is the most important thing to understand:

Note

This is a simplified demonstration of Deep Q-Learning, but it is not a proper DQN implementation. A production-quality DQN normally uses things such as:
  • Experience replay
  • Target network
  • Exploration, usually ε-greedy
  • Proper handling of terminal states
  • Batched training
current code always does:
So it always chooses the current best action. There is no exploration.