OpenAI Gym马里奥强化学习模型解包值数量异常问题求助
解决Gym Super Mario Bros环境中的返回值解包错误
问题背景
用OpenAI Gym构建《超级马里奥兄弟》强化学习模型时,跟随教程实操,运行约10分钟后出现两种解包错误:
too many values to unpack (expected 4)not enough values to unpack (expected 5, got 4)
错误出现在循环中env.step()的返回值解包环节,根源是环境实例化时的API版本兼容问题导致返回值格式不稳定。
错误原因
Gym新旧版本的API返回值格式不一致:
- 旧版Gym(v0):
env.step()返回4个值(state, reward, done, info);env.reset()返回1个值(state) - 新版Gym(v1+):
env.step()返回5个值(state, reward, terminated, truncated, info);env.reset()返回2个值(state, info)
代码中使用了apply_api_compatibility=True参数,该参数会尝试兼容新旧API,但运行过程中可能出现返回值格式切换,导致解包不匹配。
修复方案
统一适配新版Gym的API格式,明确处理所有返回值:
- 调整
env.reset()的赋值,接收返回的state和info - 调整
env.step()的解包,接收5个返回值,用terminated or truncated替代原有的done标识
修改后的完整代码
#!pip install gym_super_mario_bros==7.3.0 nes_py import gym_super_mario_bros from nes_py.wrappers import JoypadSpace from gym_super_mario_bros.actions import SIMPLE_MOVEMENT # 初始化游戏环境 env = gym_super_mario_bros.make('SuperMarioBros-v0', apply_api_compatibility=True, render_mode="human") env = JoypadSpace(env, SIMPLE_MOVEMENT) # 查看环境参数 print(env.action_space) print(env.observation_space.shape) print(env.observation_space) print(env.action_space.sample()) done = True for step in range(100000): if done: # 重置环境,接收新版API的两个返回值 state, info = env.reset() # 接收新版API的5个返回值 state, reward, terminated, truncated, info = env.step(env.action_space.sample()) # 合并terminated和truncated为done标识 done = terminated or truncated # 渲染游戏画面 env.render() # 关闭环境 env.close()
关键修改说明
env.reset()改为接收state, info,适配新版API的返回格式env.step()改为解包5个值,新增terminated(任务完成)和truncated(超时/截断)两个状态- 用
done = terminated or truncated保持原有逻辑的连续性,标识是否需要重置环境
内容的提问来源于stack exchange,提问作者Preston Menke
相关产品推荐
相关产品推荐

