State → Neural Network → Q-values → Choose action → Get reward → Update network
1. Import Gymnasium
Gymnasium provides environments for Reinforcement Learning (RL).
Here we use:
2. Import PyTorch
- 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
5. Create CartPole environment
6. Create the Q-network
First layer
7. ReLU activation
8. Output layer
9. Create optimizer
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
11. Reset the environment
12. Start reward counter
13. Run up to 500 steps
14. Convert state to PyTorch tensor
float32 means the numbers are stored as 32-bit floating-point values.
15. Predict Q-values
16. Choose the best action
argmax() finds the position of the largest value.
If:
Always choose the action with the highest predicted Q-value.
17. Perform the action
“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:
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
19. Don’t calculate gradients
Calculate this without tracking gradients.
20. Calculate the next Q-value
“According to the current model, what is the best possible future Q-value?“
21. Calculate target Q-value
22. Why 0.99?
“Don’t just think about what happens now. Think about future rewards too.”
23. Why this part?
24. Get current Q-value
The model’s current prediction for the action it actually took.
25. Calculate loss
26. Clear previous gradients
27. Backpropagation
“Which weights caused my prediction to be wrong, and in what direction should they change?“
28. Update the model
29. Move to next state
30. Add reward
31. Stop if episode is finished
32. Print episode reward
33. Close the environment
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