强化学习基础
1.什么是强化学习?
强化学习(reinforcement learning,RL)讨论的问题是智能体(agent)怎么在复杂、不确定的环境(environment)中最大化它能获得的奖励(reward)。

强化学习由两部分组成:智能体和环境。在强化学习过程中,智能体(agent)与环境(environment)一直在交互。智能体在环境中获取某个状态(state,St)后,它会利用该状态输出一个动作(action,At)。然后这个动作会在环境中被执行,环境会根据智能体采取的动作,输出下一个状态(St+1)以及当前这个动作带来的奖励(reward,Rt)。智能体的目的就是尽可能多地从环境中获取奖励。

2. 环境
OpenAI Gym 是一个用于开发强化学习算法的工具包。它提供了一系列的环境(cartpole, pendulum, mountain-car, mujoco, atari, and more),供用户在这些环境中训练和测试他们的算法。Gym 的设计目标是简化强化学习的研究,使得研究者和开发者能够专注于算法的实现,而不必担心环境的细节。
2.1 查看提供的所有环境
import gymnasium as gym
# To see all environments you can create
gym.pprint_registry()

2.2 倒立摆环境的简单代码示例
# Run `pip install "gymnasium[classic-control]"` for this example.
import gymnasium as gym
from gymnasium.utils.save_video import save_video
# Create our training environment - a cart with a pole that needs balancing
# "render_mode" parameter that specifies how the environment should be visualized.
# See Env.render() for details on different render modes.
# The render mode determines whether you see a visual window (“human”),
# get image arrays (“rgb_array”), or run without visuals (None - fastest for training).
env = gym.make("CartPole-v1", render_mode="rgb_array_list")
# Reset environment to start a new episode
# For initializing the environment with a particular random seed or options (see the
# environment documentation for possible values) use the seed or options parameters with reset().
observation, info = env.reset()
# observation: what the agent can "see" - cart position, velocity, pole angle, etc.
# info: extra debugging information (usually not needed for basic learning)
print(f"Starting observation: {observation}")
# Example output: [ 0.01234567 -0.00987654 0.02345678 0.01456789]
# [cart_position, cart_velocity, pole_angle, pole_angular_velocity]
episode_over = False
total_reward = 0
# One such action-observation exchange is called a timestep.
while not episode_over:
# Choose an action: 0 = push cart left, 1 = push cart right
action = env.action_space.sample() # Random action for now - real agents will be smarter!
# Take the action and see what happens
observation, reward, terminated, truncated, info = env.step(action)
# reward: +1 for each step the pole stays upright
# terminated: True if pole falls too far (agent failed)
# truncated: True if we hit the time limit (500 steps)
total_reward += reward
episode_over = terminated or truncated
# 直接使用 env.render() 获取整个episode的帧列表
save_video(
frames=env.render(), # 获取帧列表
video_folder="videos",
fps=env.metadata["render_fps"], # 从环境元数据中获取FPS,若报错可手动指定,如 fps=30[reference:3]
name_prefix="manual_save",
)
print(f"Episode finished! Total reward: {total_reward}")
env.close()


2.3 倒立摆环境查看动作空间(Action Space)和状态空间(Observation Space)
import gymnasium as gym
# Discrete action space (button presses)
env = gym.make("CartPole-v1")
print(f"Action space: {env.action_space}") # Discrete(2) - left or right
print(f"Sample action: {env.action_space.sample()}") # 0 or 1
# Box observation space (continuous values)
print(f"Observation space: {env.observation_space}") # Box with 4 values
# Box([-4.8, -inf, -0.418, -inf], [4.8, inf, 0.418, inf])
print(f"Sample observation: {env.observation_space.sample()}") # Random valid observation
Box: describes bounded space with upper and lower limits of any n-dimensional shape (like continuous control or image pixels).
Discrete: describes a discrete space where {0, 1, ..., n-1} are the possible values (like button presses or menu choices).
2.4 倒立摆环境详解
在这个环境中,智能体是推车。动作空间是推车的两个动作,向左推和向右推。状态空间是推车的位置,推车的速度,木杆的角度和木杆的角速度。奖励是推车采取向左推或者向右推的动作之后,只要木杆不倒下,奖励就加1。游戏的结束条件是推车将杆子推出了屏幕,杆子倒下和timestep超过500步。
3. 策略和轨迹
推车应该采取什么样的策略(policy),才能让杆子不倒下,获得不停的奖励。推车要采取的策略是一个函数。要采取的动作一般来说是一个概率分布。
要采取的动作的概率分布=策略函数(环境的状态)

策略的数学符号是π。如果π函数是一个神经网络,那么这就是深度学习 + 强化学习 = 深度强化学习。

所以玩倒立摆游戏的一个回合(episode)就是环境的状态为 𝑆0,推车采取动作 𝐴0,然后获得奖励 𝑅0,然后环境的状态转移到了 𝑆1,推车接着采取动作 𝐴1,然后获得奖励 𝑅1,…。下标是时刻,或者时间步。把它们写到一起,就是一个轨迹(trajectory)。轨迹用数学符号 𝜏 表示。
𝜏=(𝑆0,𝐴0,𝑅0,𝑆1,𝐴1,𝑅1,𝑆2,𝐴2,𝑅2,⋯)
4. 马尔科夫决策过程(MDP,Markov Decision Process)
4.1 状态转移
假设智能体现在处于状态 𝑠 并执行了行动 𝑎 ,那么转移到下一个状态 𝑠′ 的概率 𝑝(𝑠′|𝑠, 𝑎) ,状态转移不需要过去的信息。这个特性被称马尔科夫性质。
4.2 奖励函数
当智能体处于状态 𝑠 ,执行行动 𝑎,下一个状态是 𝑠′ 时,得到的奖励由函数 𝑟(𝑠,𝑎,𝑠′) 定义。
4.3 策略
智能体的行动是由随机性策略决定的,𝜋(𝑎|𝑠)
4.4 收益
当位于时刻 𝑡 时,环境此时处于状态 𝑆𝑡 ,然后根据策略函数开始采取动作,采取的动作是 𝐴𝑡 ,获取的奖励是 𝑅𝑡 ,然后环境的状态从 𝑆𝑡 转移到了 𝑆𝑡+1 ,然后采取动作 𝐴𝑡+1 ,然后获得奖励 𝑅𝑡+1 ,然后环境的状态从 𝑆𝑡+1 转移到了 𝑆𝑡+2 ,然后环境会奖励 𝑅𝑡+2 ,……。但是未来的奖励不如现在的奖励有吸引力,所以需要打折,𝛾 叫做折扣因子(discount rate),其被设定为 0.0 和 1.0 之间的实数。那么,从 𝑡 时刻起,未来一共获得的奖励叫做回报(或者收益,Return)。
𝐺𝑡=𝑅𝑡+𝛾𝑅𝑡+1+𝛾2𝑅𝑡+2+⋯
由上面的式子可以推导出如下递推公式:
𝐺𝑡=𝑅𝑡+𝛾𝐺𝑡+1
4.6 状态价值函数
根据策略函数,每条轨迹都有一个产生的概率。评估在环境处于状态 𝑆𝑡 时,一直采取策略 𝜋 的预期回报(回报的期望值),这就是状态价值函数(State Value Function)。

或者
(贝尔曼期望方程)

4.7 MDP的目标
最优策略的状态价值函数叫作最优状态价值函数(optimal state-value function)。可以使用 𝑣∗ 来表示最优状态价值函数。这是MDP的目标。
5. 期望的定义和相关性质
5.1 期望的定义

5.2 函数的期望公式

5.3 全期望公式

5.4 条件期望的迭代公式

5.5 期望的线性性质

- 点赞
- 收藏
- 关注作者
评论(0)