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

Fundamental Framework of Reinforcement Learning

Fundamental Framework of Reinforcement Learning

Imagine you are teaching a puppy the "sit" command. You wouldn't directly tell it how to move every muscle for the sitting action; instead, you would do this:

  1. You give the "sit" command.
  2. The puppy tries to make some movement (it might sit, lie down, or spin around).
  3. If it sits, you immediately give it a treat as a reward.
  4. If it does something wrong, you give no reward, or give a slight "wrong" signal.
  5. After many attempts, the puppy gradually understands: after hearing "sit", making the sitting action earns a treat. Thus it has learned the command.

Reinforcement Learning It means letting a computer (or agent), like this puppy, learn how to make a series of decisions through interaction with the environment and based on the rewards or penalties received, in order to achieve a long-term goal.

It is fundamentally different from the familiarSupervised Learning(the "teacher" with standard answers) andUnsupervised learning(seeking the inherent structure of data). Reinforcement learning islearning from experience, whose core istrial and errorThe difference betweendelayed reward。


Core Elements of Reinforcement Learning

To formally describe this learning process, we introduce several core concepts that together form the basic framework of reinforcement learning.

Agent and Environment

This is the most basic pair of interacting entities in reinforcement learning.

Their relationship is a continuous cycle:The agent observes the environment -> takes an action -> the environment feeds back a new state and reward -> the agent observes again...

State, Action, and Reward

These are the three key pieces of information that describe each interaction.

Strategy

Strategy The policy is the agent's brain or code of conduct. It defines which action the agent should take in any given state.

A policy can be a simple lookup table function or a complex deep neural network. The ultimate goal of reinforcement learning is to find anoptimal policythat enables the agent to obtain from the environment themaximization of long-term cumulative reward。

Value Function

Reward tells the agentCurrentthe immediate goodness or badness of an action, but the agent needs to care more aboutthe long termreturns.Value Function The value function is the tool used to measure this long-term return.

The question it answers is: starting from the current state and following a certain policy all the way, Iexpectto obtain in total reward?

Why do we need a value function? Imagine a chess game. Capturing an opponent's pawn gives an immediate small reward, but may lead to being "checkmated" ten moves later and receiving a huge negative reward. Through calculation and estimation, the value function helps the agent avoid such behavior of grasping small gains while losing the whole game.


Core Interaction Flow: Markov Decision Process

Reinforcement learning problems are usually modeled as a Markov Decision Process. This name sounds complex, but in fact it just organizes the elements we mentioned above in mathematical form, describing a standard framework for agent-environment interaction.

The core idea of MDP is:the next state and reward depend only on the current state and the current action taken, independent of previous history(i.e., the Markov property).

A complete MDP interaction cycle is as follows:

  1. At time t, the environment is in state S_t。
  2. The agent observes this state.
  3. The agent, according to its policy π, selects an action A_t。
  4. The environment receives this action.
  5. The environment, according to its internal dynamics, transitions to the next state S_{t+1}and produces a scalar reward R_{t+1}which is fed back to the agent.
  6. The time step advances (t = t+1), and a new cycle begins.

The agent's goal is to learn a policy by continuously going through this cycle π*so that, starting from any initial state, theexpected value of cumulative reward (i.e., return) is maximized。


A Simple Code Example: Grid World

Let's use a classic grid world example to make these concepts concrete. Suppose there is a 4x4 grid, and the agent starts from the starting point S and the goal is to reach the end point G. Stepping onto an obstacle # means failure, and each step carries a small penalty (to encourage reaching the goal as quickly as possible).

S . . .

. # . .

. . # .

. . . G

- Reaching `G`: +10 - Hitting `#` or going out of bounds: -5 - Other normal moves: -0.1 (encourage efficient paths)

Below is a highly simplified pseudocode demonstration of Q-learning (a classic reinforcement learning algorithm) for learning the optimal path in this grid world.

Example

import

numpy

as

np

import

random

from

typing

import

Dict

,

List

,

Tuple

====================== 1. Environment Simulation (Grid World) ======================

class

GridWorldEnv:

   

"""A simple grid world environment to demonstrate Q-Learning"""

   

def

init

(

self

,

grid_size: Tuple

[

int

,

int

]

=

(

5

,

5

)

,

                 start_pos: Tuple

[

int

,

int

]

=

(

0

,

0

)

,

                 goal_pos: Tuple

[

int

,

int

]

=

(

4

,

4

)

,

                 obstacle_pos: List

[

Tuple

[

int

,

int

]

]

=

[

(

1

,

1

)

,

(

2

,

2

)

,

(

3

,

1

)

]

)

:

       

self

.

grid_size

=

grid_size

       

self

.

start_pos

=

start_pos

       

self

.

goal_pos

=

goal_pos

       

self

.

obstacle_pos

=

obstacle_pos

       

self

.

current_pos

=

start_pos

       

       

Action definitions: 0-up, 1-down, 2-left, 3-right

       

self

.

actions

=

[

'up'

,

'down'

,

'left'

,

'right'

]

       

self

.

num_actions

=

len

(

self

.

actions

)

       

   

def

reset

(

self

)

int

:

       

"""Reset the environment and return the index of the initial state"""

       

self

.

current_pos

=

self

.

start_pos

       

return

self

.

pos_to_state

(

self

.

current_pos

)

   

   

def

pos_to_state

(

self

,

pos: Tuple

[

int

,

int

]

)

int

:

       

"""Convert a coordinate position to a state index"""

       

return

pos

[

0

]

self

.

grid_size

[

1

]

[

1

]

   

   

def

state_to_pos

(

self

,

state:

int

)

Tuple

[

int

,

int

]

:

       

"""Convert a state index to a coordinate position"""

       

return

(

state //

self

.

grid_size

[

1

]

,

state %

self

.

grid_size

[

1

]

)

   

   

def

random_action

(

self

)

int

:

       

"""Randomly select an action (exploration)"""

       

return

random

.

randint

(

0

,

self

.

num_actions

1

)

   

   

def

action_to_direction

(

self

,

action:

int

)

str

:

       

"""Convert an action index to a direction name"""

       

return

self

.

actions

[

action

]

   

   

def

step

(

self

,

action:

int

)

Tuple

[

int

,

float

,

bool

]

:

       

"""
        Execute an action, return (next_state, reward, done)
        Optimization: fix the bug where the obstacle reward could not be triggered, simplify the logic
        """

        x

,

y

=

self

.

current_pos

       

       

Update the position according to the action

       

if

action

==

0

:  

up

            x

=

max

(

0

,

x -

1

)

       

elif

action

==

1

:  

down

            x

=

min

(

self

.

grid_size

[

0

]

1

,

x +

1

)

       

elif

action

==

2

:  

Left

            y

=

max

(

0

,

y -

1

)

       

elif

action

==

3

:  

Right

            y

=

min

(

self

.

grid_size

[

1

]

1

,

y +

1

)

       

       

Check whether an obstacle is hit (core fix: first record whether an obstacle was hit, then handle the position)

        new_pos

=

(

x

,

y

)

        hit_obstacle

=

False

 

Record whether an obstacle was hit

       

if

new_pos

in

self

.

obstacle_pos

:

            hit_obstacle

=

True

 

Record the obstacle collision status

            new_pos

=

self

.

current_pos

 

If an obstacle is hit, the position stays unchanged

       

       

self

.

current_pos

=

new_pos

        next_state

=

self

.

pos_to_state

(

new_pos

)

       

       

Compute the reward (based on the pre-recorded hit_obstacle, fixing the original logical contradiction)

       

if

new_pos

==

self

.

goal_pos

:

            reward

=

100.0

 

Reach the goal, large reward

            done

=

True

       

elif

hit_obstacle:  

Judge based on the flag, not the modified new_pos

            reward

=

50.0

 

Hit an obstacle, penalty

            done

=

False

       

else

:

            reward

=

1.0

 

A small penalty for each step, encouraging reaching the goal as soon as possible

            done

=

False

       

       

return

next_state

,

reward

,

done

====================== 2. Q-Learning Main Program ======================

if

name

==

"main"

:

   

Optimization 1: fix the random seed to ensure reproducible experimental results

    random_seed

=

42

   

random

.

seed

(

random_seed

)

    np.

random

.

seed

(

random_seed

)

   

   

Initialize the environment

    env

=

GridWorldEnv

(

        grid_size

=

(

5

,

5

)

,

         

5x5 grid

        start_pos

=

(

0

,

0

)

,

         

Start point

        goal_pos

=

(

4

,

4

)

,

         

Endpoint

        obstacle_pos

=

[

(

1

,

1

)

,

(

2

,

2

)

,

(

3

,

1

)

]

 

Obstacle positions

   

)

   

   

Compute the number of states

    num_states

=

env.

grid_size

[

0

]

grid_size

[

1

]

    num_actions

=

env.

num_actions

   

   

Initialize the Q-table (action value function) with shape [number of states, number of actions]

    Q_table

=

np.

zeros

(

[

num_states

,

num_actions

]

)

   

   

Define hyperparameters

    learning_rate

=

0.1

     

Learning Rate

    discount_factor

=

0.9

   

Discount factor

    epsilon

=

0.1

           

Exploration rate

    total_episodes

=

1000

   

Number of Training Epochs

   

   

Training process

   

for

episode

in

range

(

total_episodes

)

:

        state

=

env.

reset

(

)

   

Reset the environment to the start, obtain the initial state S

        done

=

False

         

Flag whether this episode is over

        total_reward

=

0

     

Record the total reward for this episode

       

       

while

not

done:

           

1. ε-greedy policy selects an action

           

if

random

.

uniform

(

0

,

1

)

<

epsilon:

                action

=

env.

random_action

(

)

 

Exploration: randomly select an action

           

else

:

               

Exploitation: select the action with the highest Q-value, handling ties

                q_values

=

Q_table

[

state

]

                max_q

=

np.

max

(

q_values

)

                best_actions

=

np.

where

(

q_values

==

max_q

)

[

0

]

                action

=

random

.

choice

(

best_actions

)

 

When tied, randomly select one

           

           

2. Execute an action and interact with the environment

            next_state

,

reward

,

done

=

env.

step

(

action

)

            total_reward +

=

reward

           

           

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

           

Q(S, A) = Q(S, A) + α * [ R + γ * max(Q(S', a')) - Q(S, A) ]

            old_value

=

Q_table

[

state

,

action

]

            next_max

=

np.

max

(

Q_table

[

next_state

]

)

 

The maximum Q-value of the next state

           

           

Compute the target Q-value

            target

=

reward + discount_factor * next_max

           

Update the Q-value

            new_value

=

old_value + learning_rate *

(

target - old_value

)

            Q_table

[

state

,

action

]

=

new_value

           

           

4. Move to the next state

            state

=

next_state

       

       

Print the training progress every 100 episodes

       

if

(

episode +

1

)

%

100

==

0

:

           

print

(

f

"Episode {episode + 1}/{total_episodes}, Total Reward: {total_reward:.1f}"

)

   

   

====================== 3. Extract the Optimal Policy (Optimized Print Format, More Intuitive) ======================

    policy: Dict

[

int

,

str

]

=

{

}

   

print

(

"\n=== Optimal Policy After Learning (Laid Out by Grid) ==="

)

   

   

Optimization 2: print according to the grid shape, intuitively showing the policy for the entire grid

    grid_rows

,

grid_cols

=

env.

grid_size

   

for

row

in

range

(

grid_rows

)

:

        row_str

=

[

]

       

for

col

in

range

(

grid_cols

)

:

            pos

=

(

row

,

col

)

            state

=

env.

pos_to_state

(

pos

)

           

if

pos

in

env.

obstacle_pos

:

                row_str.

append

(

" Obstacle "

)

           

elif

pos

==

env.

goal_pos

:

                row_str.

append

(

" Goal "

)

           

elif

pos

==

env.

start_pos

:

               

Also mark the starting point and its optimal action

                best_action_idx

=

np.

argmax

(

Q_table

[

state

]

)

                best_action

=

env.

action_to_direction

(

best_action_idx

)

                row_str.

append

(

f

" Start({best_action}) "

)

           

else

:

                best_action_idx

=

np.

argmax

(

Q_table

[

state

]

)

                best_action

=

env.

action_to_direction

(

best_action_idx

)

                policy

[

state

]

=

best_action

                row_str.

append

(

f

"   {best_action}   "

)

       

print

(

"|"

.

join

(

row_str

)

)

   

   

====================== 4. Test the Optimal Policy ======================

   

print

(

"\n=== Test the Optimal Policy ==="

)

    state

=

env.

reset

(

)

    done

=

False

    steps

=

0

    path

=

[

env.

state_to_pos

(

state

)

]

   

   

while

not

done

and

steps

<

50

:  

At most 50 steps to prevent an infinite loop

        best_action_idx

=

np.

argmax

(

Q_table

[

state

]

)

        next_state

,

reward

,

done

=

env.

step

(

best_action_idx

)

        current_pos

=

env.

state_to_pos

(

next_state

)

        path.

append

(

current_pos

)

        state

=

next_state

        steps +

=

1

   

   

print

(

f

"Path: {path}"

)

   

print

(

f

"Steps to reach the goal: {steps}"

)

   

print

(

f

"Reached the goal: {env.current_pos == env.goal_pos}"

)

Code Analysis:

Output:



Episode 100/1000, Total Reward: 93.0

Episode 200/1000, Total Reward: 90.0

Episode 300/1000, Total Reward: 92.0

Episode 400/1000, Total Reward: 90.0

Episode 500/1000, Total Reward: 93.0

Episode 600/1000, Total Reward: 93.0

Episode 700/1000, Total Reward: 91.0

Episode 800/1000, Total Reward: 93.0

Episode 900/1000, Total Reward: 93.0

Episode 1000/1000, Total Reward: 93.0



=== 学习完成后的最优策略 ===

位置 (0, 0): 最优动作 = right

位置 (0, 1): 最优动作 = right

位置 (0, 2): 最优动作 = down

位置 (0, 3): 最优动作 = down

位置 (0, 4): 最优动作 = down

位置 (1, 0): 最优动作 = up

位置 (1, 1): 最优动作 = 障碍物

位置 (1, 2): 最优动作 = right

位置 (1, 3): 最优动作 = down

位置 (1, 4): 最优动作 = left

位置 (2, 0): 最优动作 = down

位置 (2, 1): 最优动作 = down

位置 (2, 2): 最优动作 = 障碍物

位置 (2, 3): 最优动作 = down

位置 (2, 4): 最优动作 = down

位置 (3, 0): 最优动作 = down

位置 (3, 1): 最优动作 = 障碍物

位置 (3, 2): 最优动作 = right

位置 (3, 3): 最优动作 = right

位置 (3, 4): 最优动作 = down

位置 (4, 0): 最优动作 = right

位置 (4, 1): 最优动作 = right

位置 (4, 2): 最优动作 = right

位置 (4, 3): 最优动作 = right

位置 (4, 4): 最优动作 = 终点



=== 测试最优策略 ===

路径: [(0, 0), (0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (3, 3), (3, 4), (4, 4)]

到达终点步数: 8

是否到达终点: True


Summary and Practical Reflections

The basic framework of reinforcement learning can be summarized as follows:Through Markov Decision Process-style interactions with the environment, the agent continuously optimizes its policy (usually by learning and updating a value function) according to the reward signals received, with the ultimate goal of maximizing long-term cumulative reward.

Concept Analogy Role in Reinforcement Learning
Agent The learning puppy / the chess-playing AI The decision-making subject, the algorithm performing learning
Environment The trainer / the rules of the chessboard The external system that provides state and reward feedback
State The puppy's posture / the board position The current information basis for the agent's decisions
Action Sit / move a chess piece The choices the agent can make
Reward Treats / win-or-lose outcome The immediate signal evaluating how good or bad an action is, the compass for learning
Strategy The command response the puppy has learned The mapping rule from state to action, the goal of learning
Value Function Long-term judgment of the situation Evaluate the long-term value of a state or action, the basis for policy optimization