在上一篇文中我们详细介绍了强化学习背后的思想,并且还通过超级玛丽这个游戏从直观上对强化学习进行了说明。
但是,我们在学习强化学习的过程中如何有这样一个模拟环境来生成动作、状态和奖励这些东西呢?
在接下来的这篇文章中,我们将会介绍如何使用 OpenAI 开发的 Gymnasium 模拟器来搭建一个强化学习的模拟环境。
1 CartPole 任务#
如果你刚开始接触强化学习,那么最好的起点不是Q-learning、不是PPO、也不是DQN——而是那个所有教科书、论文、教程都提到的经典环境 CartPole(小车倒立摆)。
CartPole 是一个强化学习中的 控制任务(Control Task), 目标很简单——让一根竖立在小车上的杆子尽可能长时间地不倒。

这是不是和我们小时看到的街头杂耍一样,一个人将一根长长的竹竿立在手臂上,通过自身左右移动来保持竹竿平衡。
而在强化学习当中,这就是代理(Agent)需要学会的事情。
2 CartPole 环境组成#
在明白 CartPole 任务以后,我们再来看 CartPole 的环境组成元素,整体来看它就是在上一篇文章中我们介绍到的强化学习中的基本概念。
| 元素 | 含义 | CartPole 示例 |
|---|---|---|
| Agent(智能体) | 控制小车的算法 | 后续我们将会编写的策略网络 |
| Environment(环境) | 模拟小车和杆的物理系统 | 也就是此处的 CartPole 环境 |
| State(状态) | 当前系统的数值描述 | $s = [x, \dot{x}, \theta, \dot{\theta}]$ |
| Action(动作) | 向左推或向右推小车 | 0=左推,1=右推 |
| Reward(奖励) | 每保持一帧不倒 +1,否则 +0 | 越久越好 |
| Done(结束标志) | 杆倒或出界则结束 | 失败条件 |
在强化学习中,状态是智能体感知环境的全部信息。
不同的环境有不同的状态,环境越复杂状态也就越多。对于 CartPole 来说 $s = [x, \dot{x}, \theta, \dot{\theta}]$,其分别表示:
- $x$: 小车位置(-4.8 ~ +4.8),通常单位是米(m);
- $\dot{x}$: 小车速度,单位 m/s ;
- $\theta$: 杆的角度, 相对于竖直向上的偏离角度,单位是弧度(rad),0 表示杆完全竖直向;
- $\dot{\theta}$: 杆角速度, 杆角速度,单位 rad/s,表示杆旋转快慢和方向。
在 CartPole 环境中,小车每执行一步动作(左推 or 右推),如果杆子还没有倒,就获得 +1 奖励。 也就是说,**智能体的目标就是尽可能延长杆不倒的时间。**当杆倾斜超过 ±12度 或小车位置超出 ±2.4,就算“倒了”。
3 演示CartPole 环境交互#
在介绍完整个 CartPole 环境内容以后,我们再来看看如何铜鼓代码来运行。
3.1 Python 环境安装#
首先,我们需要安装使用到的Python环境。
下面这几个Python包就是我们在实验时安装的,其中 imageio 用来将整个过程保存为本地 git 图片,也就图1所示,如过不需要可以不用安装。
contourpy 1.3.1
cycler 0.12.1
gymnasium 1.2.1
imageio 2.37.0
matplotlib 3.10.7
numpy 1.23.5
pygame 2.6.13.2 CartPole 任务模拟#
下面我们来启动环境,并模拟整个过程。
需要说明的是,下面这段代码不做任何学习,只是演示环境的运行机制,它每一步都会:
执行动作(随机);
打印状态、动作、奖励;
可视化环境;
最后绘制小车位置与杆角度的变化曲线。
1 import gymnasium as gym
2 import time
3 import matplotlib.pyplot as plt
4 import numpy as np
5
6 def CarPole():
7 env = gym.make("CartPole-v1", render_mode="human")
8 state, _ = env.reset() # 初始化
9 print("初始状态 [x, x_dot, theta, theta_dot] =", state)
10 num_steps = 100 # 最大循环步数,避免无限循环。
11 total_reward = 0 # 累计奖励,用于衡量小车平衡效果。
12 x_list, theta_list = [], [] # 存储每一步的小车位置和杆角度,用于后续画图。
13 for t in range(num_steps):
14 action = env.action_space.sample()
15 next_state, reward, done, truncated, info = env.step(action)
16 x, x_dot, theta, theta_dot = next_state
17 total_reward += reward
18 x_list.append(x)
19 theta_list.append(theta)
20 print(f"Step {t + 1:03d}: Action={action} | x={x:+.3f}, x_dot={x_dot:+.3f}, "
21 f"theta={theta:+.3f}, theta_dot={theta_dot:+.3f}, Reward={reward}")
22 time.sleep(0.03)
23 if done or truncated: # 如果游戏结束(杆倒了或达到最大步数),退出循环
24 print(" Episode Ended!")
25 break
26 print(f"\n 总奖励: {total_reward:.2f}")
27 env.close()
28 return x_list, theta_list在上述代码中,第1行中 gymnasium 是强化学习环境库,这里用它创建 CartPole-v1 环境。第7行表示要在屏幕上渲染环境动画(你能看到小车和杆运动)。第14行表示随机选择动作,0 表示向左推力,1 表示向右推力。第15行是根据智能体执行的动作返回由环境生成的当前状态、奖励值、是否结束等信息。第23行为判断是否提前结束。
3.3 运行结果#
最后,可以通过如下代码来运行,并得到小车左右移动距离和杆角度的变化情况:
1 if __name__ == '__main__':
2 x_list, theta_list = CarPole()
3 plt.figure(figsize=(10, 4))
4 plt.subplot(1, 2, 1)
5 plt.plot(x_list)
6 plt.title("Cart Position (x)")
7 plt.xlabel("Step")
8 plt.ylabel("x")
9
10 plt.subplot(1, 2, 2)
11 plt.plot(np.degrees(theta_list))
12 plt.title("Pole Angle (theta, degrees)")
13 plt.xlabel("Step")
14 plt.ylabel("Angle (°)")
15 plt.tight_layout()
16 plt.show()上述代码运行时控制台将会输出类似如下信息:
初始状态 [x, x_dot, theta, theta_dot] = [-0.01429775 -0.01981201 0.01488416 -0.00709631]
Step 001: Action=1 | x=-0.015, x_dot=+0.175, theta=+0.015, theta_dot=-0.295, Reward=1.0
Step 002: Action=1 | x=-0.011, x_dot=+0.370, theta=+0.009, theta_dot=-0.583, Reward=1.0
Step 003: Action=1 | x=-0.004, x_dot=+0.565, theta=-0.003, theta_dot=-0.873, Reward=1.0
Step 004: Action=1 | x=+0.008, x_dot=+0.760, theta=-0.020, theta_dot=-1.166, Reward=1.0
Step 005: Action=0 | x=+0.023, x_dot=+0.565, theta=-0.044, theta_dot=-0.880, Reward=1.0
Step 006: Action=0 | x=+0.034, x_dot=+0.371, theta=-0.061, theta_dot=-0.602, Reward=1.0
Step 007: Action=1 | x=+0.041, x_dot=+0.567, theta=-0.073, theta_dot=-0.913, Reward=1.0
Step 008: Action=1 | x=+0.053, x_dot=+0.763, theta=-0.092, theta_dot=-1.228, Reward=1.0
Step 009: Action=0 | x=+0.068, x_dot=+0.569, theta=-0.116, theta_dot=-0.965, Reward=1.0
Step 010: Action=0 | x=+0.079, x_dot=+0.376, theta=-0.135, theta_dot=-0.711, Reward=1.0
Step 011: Action=0 | x=+0.087, x_dot=+0.183, theta=-0.150, theta_dot=-0.464, Reward=1.0
Step 012: Action=1 | x=+0.091, x_dot=+0.379, theta=-0.159, theta_dot=-0.800, Reward=1.0
Step 013: Action=1 | x=+0.098, x_dot=+0.576, theta=-0.175, theta_dot=-1.138, Reward=1.0
Step 014: Action=1 | x=+0.110, x_dot=+0.773, theta=-0.198, theta_dot=-1.480, Reward=1.0
Step 015: Action=0 | x=+0.125, x_dot=+0.581, theta=-0.227, theta_dot=-1.255, Reward=1.0
Episode Ended!
总奖励: 15.00同时最后会弹出一张图,左图显示小车位置随时间变化,右图显示杆角度变化(单位:度)。这样可以清楚看到杆在小车左右摆动的过程。

如果注释掉上面代码中的 if done or truncated: 条件,将会得到类似图3所示的结果。

4 总结#
通过 CartPole,我们可以理解强化学习的核心逻辑:“智能体在环境中不断试错,根据奖励信号调整策略,以实现长期回报最大化。”
在后续的文章中,我们将会训练一个策略网络,它会逐步学会:当杆向右倾时 → 推小车向右;当杆向左倾时 → 推小车向左;最终实现平衡杆子的目标。