You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用OpenAI Gym的env.render()触发AssertionError问题求助

解决CarRacing-v2中env.render()触发AssertionError的问题

问题场景

使用OpenAI Gym的CarRacing-v2环境搭建自动驾驶强化学习模型时,调用env.render()触发AssertionError,报错核心指向car_racing.py中的assert mode in self.metadata["render_modes"]断言失败。已安装gym[box2d]和pyglet==1.3.2依赖。

问题原因

Gym 0.26及以上版本中,创建环境时默认不会指定render_mode参数,此时环境的render_mode为None,而CarRacing-v2支持的渲染模式仅包括"human"、"rgb_array"等,None不在合法列表中,触发断言错误。

解决方案

创建环境时显式指定render_mode参数,根据运行环境选择合适模式:

  • "human":弹出可视化窗口显示环境画面(适合本地桌面环境)
  • "rgb_array":返回环境的RGB图像数组(适合无桌面的服务器环境或需要处理图像的场景)

修改后的代码

import gym 
from stable_baselines3 import PPO
from stable_baselines3.common.vec_env import VecFrameStack
from stable_baselines3.common.evaluation import evaluate_policy
import os

environment_name = "CarRacing-v2"
# 显式指定render_mode为"human"
env = gym.make(environment_name, render_mode="human")

episodes = 5
for episode in range(1, episodes+1):
    state = env.reset()
    done = False
    score = 0 
    
    while not done:
        env.render()
        action = env.action_space.sample()
        # 适配Gym新版本step返回值格式
        n_state, reward, terminated, truncated, info = env.step(action)
        done = terminated or truncated
        score += reward
    print('Episode:{} Score:{}'.format(episode, score))
env.close()

补充:Gym新版本中step()方法返回(observation, reward, terminated, truncated, info),需将terminated和truncated合并为原逻辑中的done,避免解包错误。

内容的提问来源于stack exchange,提问作者Sam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 19:55:17