使用openai gym库的API mix问题

在使用训练好的模型对gym中的CartPole-v1时,写了下面的代码

obs = env.reset()
action,_ = model.predict(obs)

报了个大错,贼长,如下:

ValueError                                Traceback (most recent call last)
Cell In[43], line 1
----> 1 action,_ = model.predict(obs)

File c:\users\dell\appdata\local\programs\python\python39\lib\site-packages\stable_baselines3\common\base_class.py:556, in BaseAlgorithm.predict(self, observation, state, episode_start, deterministic)
    536 def predict(
    537     self,
    538     observation: Union[np.ndarray, Dict[str, np.ndarray]],
   (...)
    541     deterministic: bool = False,
    542 ) -> Tuple[np.ndarray, Optional[Tuple[np.ndarray, ...]]]:
    543     """
    544     Get the policy action from an observation (and optional hidden state).
    545     Includes sugar-coating to handle different observations (e.g. normalizing images).
   (...)
    554         (used in recurrent policies)
    555     """
--> 556     return self.policy.predict(observation, state, episode_start, deterministic)

File c:\users\dell\appdata\local\programs\python\python39\lib\site-packages\stable_baselines3\common\policies.py:357, in BasePolicy.predict(self, observation, state, episode_start, deterministic)
    354 # Check for common mistake that the user does not mix Gym/VecEnv API
    355 # Tuple obs are not supported by SB3, so we can safely do that check
    356 if isinstance(observation, tuple) and len(observation) == 2 and isinstance(observation[1], dict):
--> 357     raise ValueError(
    358         "You have passed a tuple to the predict() function instead of a Numpy array or a Dict. "
    359         "You are probably mixing Gym API with SB3 VecEnv API: `obs, info = env.reset()` (Gym) "
    360         "vs `obs = vec_env.reset()` (SB3 VecEnv). "
    361         "See related issue https://github.com/DLR-RM/stable-baselines3/issues/1694 "
    362         "and documentation for more information: https://stable-baselines3.readthedocs.io/en/master/guide/vec_envs.html#vecenv-api-vs-gym-api"
    363     )
    365 obs_tensor, vectorized_env = self.obs_to_tensor(observation)
    367 with th.no_grad():

ValueError: You have passed a tuple to the predict() function instead of a Numpy array or a Dict. You are probably mixing Gym API with SB3 VecEnv API: `obs, info = env.reset()` (Gym) vs `obs = vec_env.reset()` (SB3 VecEnv). See related issue https://github.com/DLR-RM/stable-baselines3/issues/1694 and documentation for more information: https://stable-baselines3.readthedocs.io/en/master/guide/vec_envs.html#vecenv-api-vs-gym-api

总结一下就是两个API混着用,需要输入列表结果输入的是元组,所以报错了。
找遍了全网没找到怎么改,问了gpt也没用。
改了好久突然发现obs, info = env.reset()这句代码,于是去看了下源文件中的定义(https://www.gymlibrary.dev/api/core/#gym.Env.reset)

observation (object)
 – Observation of the initial state. This will be an element of observation_space (typically a numpy array) and is analogous to the observation returned by step().

info (dictionary)
 – This dictionary contains auxiliary information complementing observation. It should be analogous to the info returned by step().

返回的还真不是列表,是由一个numpy array(obs)和一个dictionary(info)组成的元组。
这就好办了,用两个变量分别接收就好了,修改如下

obs,info = env.reset()
action, _ = model.predict(obs)

用type函数看看数据类型
在这里插入图片描述
诶对了,然后再放进去跑就行了

更新2024.5.10--------------------------------------------------------------------------------------
原来是之前

env = gym.make(environment_name, render_mode="human")
env = DummyVecEnv([lambda:env])
model = PPO('MlpPolicy', env, verbose = 1,tensorboard_log=log_path)

第二行代码没加,导致冲突了,加了第二行代码可以不用上述方法

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
OpenAI Gym是一个用于开发和比较强化学习算法的开源工具包。它提供了许多经典的强化学习环境,让研究者能够更轻松地实验和测试自己的算法。 OpenAI Gym包含了一系列模拟环境,可以在这些环境中训练强化学习算法。这些环境包括了各种各样的问题,例如棋盘游戏、控制机器人或车辆等场景。这些问题复杂多样,要求智能体在环境中进行观察、决策和行动。 OpenAI Gym的设计使得使用者能够方便地编写、测试和比较各种不同的强化学习算法。用户可以在该工具包中选择合适的环境,并使用内置的API进行训练和测试。此外,用户还可以通过插入自定义代码来扩展现有环境或创建全新的环境。 OpenAI Gym还提供了一种称为“gym spaces”的概念。这是一种用于描述观察空间和动作空间的通用接口。用户只需定义环境的观察空间和动作空间的特征,就可以使用这些通用接口来处理不同类型的环境。 通过使用OpenAI Gym,研究者可以在一个统一的框架下进行强化学习算法的开发和评估。这使得算法的比较更加公平和准确。同时,OpenAI Gym的开源性质也促进了算法共享和交流,推动了强化学习领域的发展。 总之,OpenAI Gym是一个强大的工具包,为研究者提供了广泛的强化学习环境和便利的开发、测试以及比较算法的功能。它的开源性质和通用接口设计使得研究者能够更加高效地进行算法的开发和创新。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WFForstar

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值