Skip to main content

1. What is Reinforcement Learning?

Reinforcement Learning (RL) is a machine learning approach where an agent learns by interacting with an environment. The agent:
  1. Observes the current state.
  2. Selects an action.
  3. Receives a reward.
  4. Learns from the result.
  5. Repeats the process.

2. CartPole Environment

CartPole is a simple reinforcement learning environment. The goal is to keep a pole balanced on top of a moving cart.
The agent can perform two actions:
The longer the pole stays balanced, the higher the total reward.

3. OpenAI Gym / Gymnasium

Gym provides environments that can be used to test reinforcement learning algorithms. The modern package is Gymnasium. Install it:
Create the CartPole environment:

4. State

The state describes the current condition of the CartPole environment. CartPole has 4 state values:
The neural network receives these 4 values as input.

5. Action

CartPole has two possible actions:
The neural network produces two Q-values:
The action with the highest Q-value is selected.

6. Reward

A reward is feedback from the environment. For CartPole, the agent receives a reward for keeping the pole balanced. Example:
Total reward:
A higher reward means the agent kept the pole balanced for longer.

7. What is DQN?

DQN stands for: Deep Q-Network DQN combines:
Instead of storing Q-values in a table, a neural network predicts the Q-values.

8. Q-Values

A Q-value represents how useful an action is for the current state. Example:
Since:
the agent selects:

9. DQN Architecture

The simple model used in rl_demo.py is:
The code:
The final 2 represents the two possible actions.

10. Choosing an Action

The model predicts Q-values:
Example:
The highest value is selected:
Therefore:

11. Learning Process

The simplified DQN follows this process:
This process repeats for many episodes.

12. Code

rl_demo.py

Output

13. Install Dependencies

Run:
Example output:
The exact output can vary because reinforcement learning involves randomness.

14. Understanding the Important Code

Create environment

Creates the CartPole environment.

Get state

Starts a new episode and returns the initial state.

Predict Q-values

The neural network predicts the value of each action.

Select action

Selects the action with the highest Q-value.

Perform action

The environment returns:

Calculate loss

Measures the difference between the predicted Q-value and the target Q-value.

Update model

Updates the neural network so that future Q-value predictions become better.

15. Complete Learning Flow

Or simply:

16. Main Learning

The main concepts covered are:

Key takeaway

DQN uses a neural network to estimate Q-values and choose actions that can maximize future rewards.