强化学习经典算法笔记(二十一):gym-super-mario-bros游戏环境笔记

这篇笔记介绍了如何利用gym-super-mario-bros创建马里奥游戏环境进行强化学习实验。内容涵盖环境安装、演示、单独关卡设置、随机关卡选择以及奖励函数的解析。此外,还详细列举了游戏状态信息,包括生命、分数、关卡等关键数据。

gym-super-mario-bros游戏环境笔记

最近在学习Intrinsic Reward Model相关的paper,super-mario-bros可以说是算法性能测试的标配游戏环境了,可惜之前太多关注点都放在Atari上,特此开一篇笔记记录一下内容,以备后查。
在这里插入图片描述

简介

项目地址https://pypi.org/project/gym-super-mario-bros/

安装

pip install nes-py
pip install gym-super-mario-bros

需要在Ubuntu下安装,Windows不行。

Demo

游戏结束的条件应该有两个:3条命没了,或者超时了。具体实践时应该要设置一个最大探索长度。

Gym demo

from nes_py.wrappers import JoypadSpace
import gym_super_mario_bros
from gym_super_mario_bros.actions import SIMPLE_MOVEMENT
env = gym_super_mario_bros.make('SuperMarioBros-v0')
env = JoypadSpace(env, SIMPLE_MOVEMENT)

done = True
for step in range(5000):
    if done:
        state = env.reset()
    state, reward, done, info = env.step(env.action_space.sample())
    env.render()

env.close()

命令行demo

gym_super_mario_bros -e <the environment ID to play> -m <`human` or `random`>

-e默认选项是SuperMarioBros-v0-m默认选项是human
选择human时,键盘A D是左右移动,O是跳跃,长按O大跳。

环境

3条命玩32关。模拟器把无关画面全部剔除了,无关画面是指和agent操作无关的画面,比如过长画面。

EnvironmentGameROMScreenshot
SuperMarioBros-v0SMBstandard在这里插入图片描述
SuperMarioBros-v1SMBdownsample 降采样版本在这里插入图片描述
SuperMarioBros-v2SMBpixel在这里插入图片描述
SuperMarioBros-v3SMBrectangle在这里插入图片描述
SuperMarioBros2-v0SMB2standard在这里插入图片描述
SuperMarioBros2-v1SMB2downsample在这里插入图片描述

单独关卡

也可以单独训练一个关卡,Environment可以这样写:

SuperMarioBros-<world>-<stage>-v<version>
  • is a number in {1, 2, 3, 4, 5, 6, 7, 8} indicating the world
  • is a number in {1, 2, 3, 4} indicating the stage within a world
  • is a number in {0, 1, 2, 3} specifying the ROM mode to use
    • 0: standard ROM
    • 1: downsampled ROM
    • 2: pixel ROM
    • 3: rectangle ROM

For example, to play 4-2 on the downsampled ROM, you would use the environment id SuperMarioBros-4-2-v1.

随机选择关卡

随机选择一个关卡,并且只有一条命,死掉并reset之后会再随机选择一个关卡。此功能只对SMB有效,对SMB2无效。
示例代码:SuperMarioBrosRandomStages-v0
设置种子:env.seed(1),在调用reset前设置一下。

奖励函数

奖励功能假定游戏的目标是尽可能快地向右移动(增加Agent的x值)而不会死。为了建模这个游戏,奖励由三个独立的变量组成:

  1. v: the difference in agent x values between states
    • in this case this is instantaneous velocity for the given step
    • v = x1 - x0
      • x0 is the x position before the step
      • x1 is the x position after the step
    • moving right ⇔ v > 0
    • moving left ⇔ v < 0
    • not moving ⇔ v = 0
  2. c: the difference in the game clock between frames
    the penalty prevents the agent from standing still
    c = c0 - c1
    c0 is the clock reading before the step
    c1 is the clock reading after the step
    no clock tick ⇔ c = 0
    clock tick ⇔ c < 0
  3. d: a death penalty that penalizes the agent for dying in a state
    this penalty encourages the agent to avoid death
    alive ⇔ d = 0
    dead ⇔ d = -15

r = v + c + d
The reward is clipped into the range (-15, 15).

info内容解读

The info dictionary returned by the step method contains the following keys:

KeyTypeDescription
coinsintThe number of collected coins
flag_getboolTrue if Mario reached a flag or ax
lifeintThe number of lives left, i.e., {3, 2, 1}
scoreintThe cumulative in-game score
stageintThe current stage, i.e., {1, …, 4}
statusstrMario’s status, i.e., {‘small’, ‘tall’, ‘fireball’}
timeintThe time left on the clock
worldintThe current world, i.e., {1, …, 8}
x_posintMario’s x position in the stage (from the left)
y_posintMario’s y position in the stage (from the bottom)
### 使用PPO算法在gym-super-mario-bros环境中的实现 为了在 `gym-super-mario-bros` 游戏环境中应用近端策略优化 (Proximal Policy Optimization, PPO),可以按照以下方法构建模型并训练代理。以下是详细的说明: #### 安装依赖库 首先,确保安装必要的 Python 库来支持 `gym-super-mario-bros` 和强化学习框架 Stable Baselines3。 ```bash pip install nes-py gym-super-mario-bros stable-baselines3[extra] ``` 上述命令会安装 `nes-py`, `gym-super-mario-bros` 以及用于实现 PPO 的强化学习工具包 `Stable-Baselines3`[^1]。 --- #### 创建超级马里奥环境 通过导入 `SuperMarioBros-v0` 或其他变体创建游戏环境,并设置动作空间和观察空间。 ```python import gym_super_mario_bros from nes_py.wrappers import JoypadSpace from gym.spaces import Box from gym.wrappers import FrameStack from stable_baselines3.common.env_checker import check_env from stable_baselines3 import PPO # 初始化 Super Mario Bros 环境 env = gym_super_mario_bros.make('SuperMarioBros-v0') # 设置简化操作集 env = JoypadSpace(env, [['right'], ['right', 'A']]) # 将帧堆叠到一起以提供时间序列数据给神经网络 env = FrameStack(env, num_stack=4) # 验证环境是否兼容稳定基线的要求 check_env(env) ``` 此部分代码定义了一个简单的控制方案(右移或跳跃),并通过 `FrameStack` 提供连续四帧作为输入状态。 --- #### 训练PPO模型 使用 `stable-baselines3.PPO` 来初始化和训练代理。 ```python model = PPO( policy="CnnPolicy", env=env, verbose=1, tensorboard_log="./mario_ppo_tensorboard/" ) # 开始训练过程 model.learn(total_timesteps=int(1e6)) # 保存训练好的模型 model.save("ppo_mario") ``` 在此配置中: - **policy**: 使用卷积神经网络 (`CnnPolicy`) 处理图像型观测值。 - **total_timesteps**: 总共执行 $1 \times 10^6$ 时间步数进行训练。 - **tensorboard_log**: 可视化日志路径以便监控训练进展。 --- #### 测试已训练的模型 加载先前保存的模型并对环境运行推理测试。 ```python del model # 删除旧模型以防冲突 # 加载预训练模型 model = PPO.load("ppo_mario") state = env.reset() done = False while not done: action, _states = model.predict(state) state, reward, done, info = env.step(action) env.render() env.close() ``` 这段脚本展示了如何利用训练完成后的模型在游戏中做出决策。 --- ### 注意事项 1. 超参数调整对于性能至关重要。例如,更改学习率、批量大小或其他超参数可能显著影响收敛速度与最终效果。 2. 如果希望扩展功能,可考虑引入更复杂的奖励机制或者自定义环境封装器。 3. 对于更高难度级别(如世界 1-2 或以上),建议增加训练时间和样本数量。 ---
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值