Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Machine Learning – Reinforcement Learning Example

Machine Learning - Reinforcement Learning Example

Imagine you are teaching a puppy the command to sit. You do not directly tell it what the word "sit" means; instead, you guide it through rewards and punishments.

After many attempts, the puppy eventually understands the association between the "sit" command and getting a treat, and thus learns the skill.

Reinforcement Learning Reinforcement learning is a machine learning method in which a computer (or agent) learns, through trial and error, how to make optimal decisions by interacting with the environment in order to maximize cumulative reward.

Reinforcement LearningIt is fundamentally different from supervised learning (which has standard answers) and unsupervised learning (which finds inherent structures in data) that we studied earlier. The core of reinforcement learning is Agent The difference between Environment continuous interaction between the agent and the environment.


Core Concept Analysis

Before diving into the code, let us first understand a few key concepts. They are like the rules of a game, defining how the world of reinforcement learning works.

To understand more intuitively how these concepts work together, let us look at the basic interaction flow of reinforcement learning:

This loop continues until a terminal state is reached (such as winning or losing the game).


Classic problem: cliff walking

To put theory into practice, we will use a classic reinforcement learning example environment:CliffWalking-v0(CliffWalking). It comes from the gymnasium Gymnasium library (a maintained fork of the original OpenAI Gym).

Environment description

- Each step on an ordinary tile: -1 (encourages reaching the goal in fewer steps) - Falling off the cliff: -100, and sent back to the start - Reaching the goal: 0, and ends the current episode

Algorithm overview: Q-Learning

We will use Q-Learning Q-Learning algorithm to solve this problem. It is a model-free reinforcement learning algorithm, meaning the agent does not need to know the rules of the environment in advance (such as state transition probabilities); it learns through continuous trial and error.

At its core is a table called the Q-table .

The learning process of Q-Learning can be summarized in the following steps, which show how the agent updates its knowledge (the Q-table) through a single experience:

Core formula: the Bellman equation

The mathematical foundation of the Q-table update is the Bellman equation, whose update formula is as follows:

[ Q(S, A) \leftarrow Q(S, A) + \alpha [R + \gamma \max_{a} Q(S', a) - Q(S, A)] ]

Let's break down each part of this formula:

sign before positive numbers Meaning Analogy explanation
( Q(S, A) ) The original Q-value of action A in state S your previous old score for the decision to go straight at the intersection
(\alpha ) Learning Rate (0 < α ≤ 1) how much you trust this new experience. α=1 means completely overwriting old knowledge with the new experience; α=0.1 means the new experience only slightly adjusts the old knowledge
(R ) the immediate rewardobtained after executing action A after you go straight, you find the road clear and receive a small positive feedback (+1)
(\gamma ) Discount factor (0 ≤ γ < 1) how much you value future rewards. γ=0 means caring only about immediate rewards; γ=0.9 means placing great importance on long-term returns
(\max_{a} Q(S', a) ) the maximum Q-value among all possible actions in the new state S' after arriving at the new intersection, you evaluate which of turning left, turning right, or going straight has the highest future return
(R + \gamma \max_{a} Q(S', a)) Target Q-value, representing a new and better estimate of the current decision combining the immediate reward and the best future return to obtain a new score for the decision to go straight at the old intersection
(R + \gamma \max_{a} Q(S', a) - Q(S, A)) temporal difference error, the gap between new and old knowledge the difference between the new score and the old score; this difference drives learning

In short, this formula lets the agent use immediate reward + discount of the best future estimate to continuously revise its judgment of the value of the current decision.


Hands-on: writing a Q-Learning agent

Now, let us implement in code a Q-Learning agent that solves the cliff walking problem.

Step 1: Install and import libraries

First, make sure the necessary libraries are installed. Run in a terminal or command line:

Example

pip

install

gymnasium numpy

Then, import them in your Python file:

Example

import

gymnasium

as

gym

import

numpy

as

np

import

random

Step 2: Initialize the environment and Q-table

Example

1. Create the environment

env

=

gym.

make

(

"CliffWalking-v0"

,

render_mode

=

"human"

)

render_mode="human" is used for visualization

2. Get environment information

n_states

=

env.

observation_space

.

n

 

Total number of states (4*12=48)

n_actions

=

env.

action_space

.

n

     

Total number of actions (4 directions)

3. Initialize the Q-table with shape [number of states, number of actions], all initial values set to 0

Q_table

=

np.

zeros

(

(

n_states

,

n_actions

)

)

print

(

f

"Number of environment states: {n_states}, number of actions: {n_actions}"

)

print

(

f

"Q-table shape: {Q_table.shape}"

)

Step 3: Set hyperparameters

Hyperparameters are knobs that control the algorithm's behavior and need to be adjusted according to the problem.

Example

Define hyperparameters

alpha

=

0.1

 

Learning rate: the degree of influence of new information

gamma

=

0.99

 

Discount factor: the importance of future rewards

epsilon

=

0.1

Exploration rate: with what probability to explore randomly (rather than choosing the known best)

num_episodes

=

500

 

Number of training episodes (how many times the agent plays the game)

Step 4: Implement the ε-greedy policy

This is the core policy for the agent's decision-making; it balances Exploration and Use。

Example

def

choose_action

(

state

,

Q_table

,

epsilon

)

:

   

"""
    Select an action according to the ε-greedy policy.

    Parameters:
        state: current state
        Q_table: the Q-value table
        epsilon: exploration probability

    Returns:
        action: the selected action (0, 1, 2, 3)
    """

   

Generate a random number between 0 and 1

   

if

random

.

uniform

(

0

,

1

)

<

epsilon:

       

Exploration: randomly select an action

        action

=

env.

action_space

.

sample

(

)

   

else

:

       

Exploitation: select the action with the largest Q-value in the current state

       

np.argmax returns the index of the maximum value, i.e., the optimal action

        action

=

np.

argmax

(

Q_table

[

state

]

)

   

return

action

Step 5: Core training loop

This is the main process in which the algorithm learns.

Example

used to record the total reward of each episode in order to observe learning progress

reward_history

=

[

]

for

episode

in

range

(

num_episodes

)

:

   

Reset the environment and get the initial state

    state

,

_

=

env.

reset

(

)

    total_reward

=

0

 

Cumulative reward for this episode

    terminated

=

False

 

Whether a terminal state has been reached (goal/cliff)

    truncated

=

False

 

Whether it terminated due to exceeding the step limit (generally not in this environment)

   

The interaction loop for this episode, until the game ends

   

while

not

(

terminated

or

truncated

)

:

       

1. Select an action

        action

=

choose_action

(

state

,

Q_table

,

epsilon

)

       

2. Execute the action and get feedback from the environment

        next_state

,

reward

,

terminated

,

truncated

,

_

=

env.

step

(

action

)

       

3. Update the Q-table (core Q-Learning update formula)

       

Get the current Q-value

        current_q

=

Q_table

[

state

,

action

]

       

Compute the target Q-value: immediate reward + discount of the maximum future Q-value

       

Note: if the next state is a terminal state, there is no future Q-value

       

if

terminated:

            target_q

=

reward

       

else

:

            target_q

=

reward + gamma * np.

max

(

Q_table

[

next_state

]

)

       

Apply the Bellman equation to update the Q-value

        Q_table

[

state

,

action

]

=

current_q + alpha *

(

target_q - current_q

)

       

4. Transition to the next state and accumulate the reward

        state

=

next_state

        total_reward +

=

reward

   

Record the total reward for this episode

    reward_history.

append

(

total_reward

)

   

Print progress every 100 episodes

   

if

(

episode +

1

)

%

100

==

0

:

        avg_reward

=

np.

mean

(

reward_history

[

100

:

]

)

 

Average reward over the most recent 100 episodes

       

print

(

f

"Episode {episode + 1}, average reward over the last 100 episodes: {avg_reward:.2f}"

)

Training is over; close the environment

env.

close

(

)

Step 6: Test the trained agent

After training is complete, we turn off exploration and let the agent purely exploit the knowledge it learned (the Q-table) for one run, to see how it performs.

Example

print

(

"\n=== Start testing ==="

)

Create a new test environment (you can omit render_mode, or set it to "human" to watch)

test_env

=

gym.

make

(

"CliffWalking-v0"

,

render_mode

=

"human"

)

state

,

_

=

test_env.

reset

(

)

test_terminated

=

False

test_truncated

=

False

step_count

=

0

while

not

(

test_terminated

or

test_truncated

)

:

   

During testing, we set epsilon=0, meaning pure exploitation with no exploration

    action

=

choose_action

(

state

,

Q_table

,

epsilon

=

0

)

    state

,

reward

,

test_terminated

,

test_truncated

,

_

=

test_env.

step

(

action

)

    step_count +

=

1

   

print

(

f

"Step {step_count}: state {state}, action {action}, reward {reward}"

)

print

(

f

"Testing complete! Total steps: {step_count}, total reward: {reward} (reaching the goal gives a reward of 0)"

)

test_env.

close

(

)


Running results and analysis

Complete code:

Example

import

gymnasium

as

gym

import

numpy

as

np

import

random

=========================

1. Create the environment

=========================

env

=

gym.

make

(

"CliffWalking-v0"

,

render_mode

=

"human"

)

=========================

2. Get environment information

=========================

n_states

=

env.

observation_space

.

n

n_actions

=

env.

action_space

.

n

=========================

3. Initialize the Q-table

=========================

Q_table

=

np.

zeros

(

(

n_states

,

n_actions

)

)

print

(

f

"Number of environment states: {n_states}"

)

print

(

f

"Number of actions: {n_actions}"

)

print

(

f

"Q-table shape: {Q_table.shape}"

)

=========================

4. Set hyperparameters

=========================

alpha

=

0.1

gamma

=

0.99

epsilon

=

0.1

num_episodes

=

500

=========================

5. ε-greedy policy

=========================

def

choose_action

(

state

,

Q_table

,

epsilon

)

:

   

if

random

.

uniform

(

0

,

1

)

<

epsilon:

       

return

env.

action_space

.

sample

(

)

   

return

np.

argmax

(

Q_table

[

state

]

)

=========================

6. Training loop

=========================

reward_history

=

[

]

for

episode

in

range

(

num_episodes

)

:

    state

,

_

=

env.

reset

(

)

    total_reward

=

0

    terminated

=

False

    truncated

=

False

   

while

not

(

terminated

or

truncated

)

:

        action

=

choose_action

(

state

,

Q_table

,

epsilon

)

        next_state

,

reward

,

terminated

,

truncated

,

_

=

env.

step

(

action

)

        current_q

=

Q_table

[

state

,

action

]

       

if

terminated:

            target_q

=

reward

       

else

:

            target_q

=

reward + gamma * np.

max

(

Q_table

[

next_state

]

)

        Q_table

[

state

,

action

]

=

current_q + alpha *

(

target_q - current_q

)

        state

=

next_state

        total_reward +

=

reward

    reward_history.

append

(

total_reward

)

   

if

(

episode +

1

)

%

100

==

0

:

        avg_reward

=

np.

mean

(

reward_history

[

100

:

]

)

       

print

(

f

"Episode {episode + 1}, average reward over the last 100 episodes: {avg_reward:.2f}"

)

env.

close

(

)

=========================

7. Test the training results

=========================

print

(

"\n=== Start testing ==="

)

test_env

=

gym.

make

(

"CliffWalking-v0"

,

render_mode

=

"human"

)

state

,

_

=

test_env.

reset

(

)

terminated

=

False

truncated

=

False

step_count

=

0

total_reward

=

0

while

not

(

terminated

or

truncated

)

:

    action

=

choose_action

(

state

,

Q_table

,

epsilon

=

0

)

    state

,

reward

,

terminated

,

truncated

,

_

=

test_env.

step

(

action

)

    step_count +

=

1

    total_reward +

=

reward

   

print

(

f

"Step {step_count}: state {state}, action {action}, reward {reward}"

)

print

(

f

"Testing complete, total steps: {step_count}, total reward: {total_reward}"

)

test_env.

close

(

)

After running the complete code above, you will see two very intuitive phenomena: the change in reward during training, and the agent's actual action path during testing.

1. Training phase: rewards gradually increase

During training, the console outputs the average reward over the most recent 100 episodes every 100 episodes. For example:



轮次 100, 最近100轮平均奖励: -120.45

轮次 200, 最近100轮平均奖励: -65.32

轮次 300, 最近100轮平均奖励: -32.18

轮次 400, 最近100轮平均奖励: -18.06

轮次 500, 最近100轮平均奖励: -13.94

You will notice a clear trend:The average reward keeps rising (the absolute value of the negative value gets smaller)。

What does this indicate?

The improvement in reward essentially reflects an improvement in policy quality.

2. Testing phase: the agent's behavior

During the testing phase, we set epsilon epsilon to 0, which means:

If you enable render_mode="human"render_mode, you will see a very typical behavior:

This is precisely considered in the CliffWalking environment to be theoptimal policy:

This reflects a core characteristic of reinforcement learning:it pursues long-term cumulative return rather than short-term optimality。

3. Why does it learn to detour instead of taking the risky direct route?

This is a very important and also very classic question.

From human intuition, walking along the cliff is the shortest path, but for the agent:

Under the cumulative effect of the Bellman equation:

steady small losses < occasional major disasters

Therefore, Q-Learning naturally converges to a more conservative policy with a higher overall expected return.


Common questions and parameter effects

1. What happens if the learning rate α is too large or too small?

In this example,0.1 is a relatively safe choice.

2. Intuitive meaning of the discount factor γ

In the CliffWalking problem, a larger γ helps the agent realize that taking one more step now is to avoid greater losses in the future.

3. The essence of ε's role

ε determines the agent's personality:

In real projects, one typically uses an ε decay strategy:


Limitations of this example and directions for extension

Although Q-Learning is very classic, it also has obvious limitations:

This is why, in more complex problems, we introduce:

They replace the Q-table with neural networks, enabling reinforcement learning to be applied to real scenarios such as games, robot control, and autonomous driving.


Summary

Through this complete reinforcement learning example, you have:

  1. understood the fundamental difference between reinforcement learning and supervised / unsupervised learning
  2. mastered the complete loop of agent, environment, state, action, reward, and policy
  3. implemented a runnable, observable, and convergent Q-Learning agent by yourself
  4. understood the core idea of reinforcement learning: maximizing long-term return