导航 RL 框架

Python 中的 Gymnasium 强化学习

Fouad Trad

Machine Learning Engineer

RL 框架

图示智能体组件。

Python 中的 Gymnasium 强化学习

RL 框架

图示智能体与环境组件。

Python 中的 Gymnasium 强化学习

RL 框架

  • Agent(智能体): 学习者、决策者
  • Environment(环境): 待解决的挑战

图示所有 RL 组件:智能体、环境、状态、动作和回报。

Python 中的 Gymnasium 强化学习

RL 框架

  • Agent(智能体): 学习者、决策者
  • Environment(环境): 待解决的挑战
  • State(状态): 某时刻的环境快照

图示环境向智能体提供状态。

Python 中的 Gymnasium 强化学习

RL 框架

  • Agent(智能体): 学习者、决策者
  • Environment(环境): 待解决的挑战
  • State(状态): 某时刻的环境快照
  • Action(动作): 智能体对状态的响应选择

图示智能体根据环境状态执行动作。

Python 中的 Gymnasium 强化学习

RL 框架

  • Agent(智能体): 学习者、决策者
  • Environment(环境): 待解决的挑战
  • State(状态): 某时刻的环境快照
  • Action(动作): 智能体对状态的响应选择
  • Reward(回报): 对动作的反馈

图示智能体根据环境状态执行动作,并基于该动作从环境获得回报。

Python 中的 Gymnasium 强化学习

RL 交互循环

env = create_environment()
state = env.get_initial_state()

for i in range(n_iterations): action = choose_action(state)
state, reward = env.execute(action)
update_knowledge(state, action, reward)

图示智能体根据环境状态执行动作,并基于该动作从环境获得回报。

Python 中的 Gymnasium 强化学习

回合式 vs 连续式任务

回合式任务
  • 任务分为多个回合
  • 每个回合有起点与终点
  • 示例:智能体下棋

图示一只猫在下棋。

连续式任务
  • 持续交互
  • 无明确回合边界
  • 示例:调节红绿灯

图示一只青蛙骑车等待红绿灯变绿。

Python 中的 Gymnasium 强化学习

回报和(Return)

  • 动作具有长期影响
  • 目标:最大化累计回报
  • Return(回报和):所有期望回报之和

图示回报和是各回报 r_1 至 r_n 之和。

Python 中的 Gymnasium 强化学习

折扣回报

  • 立即回报比未来回报更有价值
  • 折扣回报: 更重视临近回报
  • 折扣因子 ($\gamma$):折减未来回报

图示折扣回报为各时刻回报乘以折扣因子幂的总和。

Python 中的 Gymnasium 强化学习

折扣因子

  • 取值在01之间
  • 平衡短期与长期回报
    • 较低取值 → 偏好眼前收益
    • 较高取值 → 重视长期收益

图示折扣因子极端取值的影响:0 仅看即时收益,1 不折扣未来收益。

Python 中的 Gymnasium 强化学习

数值示例

import numpy as np
expected_rewards = np.array([1, 6, 3])

discount_factor = 0.9
discounts = np.array([discount_factor ** i for i in range(len(expected_rewards))])
print(f"Discounts: {discounts}")
Discounts: [1.   0.9  0.81]
discounted_return = np.sum(expected_rewards * discounts)
print(f"The discounted return is {discounted_return}")
The discounted return is 8.83
Python 中的 Gymnasium 强化学习

Passons à la pratique !

Python 中的 Gymnasium 强化学习

Preparing Video For Download...