实用工具函数¶
Seeding (随机种子)¶
环境检查¶
- gymnasium.utils.env_checker.check_env(env: Env, warn: bool | None = None, skip_render_check: bool = False, skip_close_check: bool = False)[源代码]¶
检查环境是否遵循 Gymnasium 的 API。
为了确保环境“正确”实现,
check_env
检查observation_space
和action_space
是否正确。此外,该函数将使用各种值调用reset()
、step()
和render()
函数。我们强烈建议用户在构建环境后以及在项目的持续集成中调用此函数,以保持环境与 Gymnasium 的 API 同步更新。
- 参数:
env – 将要检查的 Gym 环境
warn – 已忽略,先前用于静默特定警告
skip_render_check – 是否跳过 render 方法的检查。默认为 False(对 CI 有用)
skip_close_check – 是否跳过 close 方法的检查。默认为 False
可视化¶
- gymnasium.utils.play.play(env: Env, transpose: bool | None = True, fps: int | None = None, zoom: float | None = None, callback: Callable | None = None, keys_to_action: dict[tuple[str | int, ...] | str | int, ActType] | None = None, seed: int | None = None, noop: ActType = 0, wait_on_player: bool = False)[源代码]¶
允许用户使用键盘来玩环境。
如果在回合制环境中玩,请将 wait_on_player 设置为 True。
- 参数:
env – 用于玩耍的环境。
transpose – 如果为
True
,则转置观测的输出。默认为True
。fps – 每秒执行环境的最大步数。如果为
None
(默认值),则使用env.metadata["render_fps""]
(如果环境未指定 “render_fps”,则使用 30)。zoom – 放大观测,
zoom
量,应为正浮点数callback –
如果提供了回调,则将在每一步之后执行。它接受以下输入
obs_t: 执行动作前的观测
obs_tp1: 执行动作后的观测
action: 执行的动作
rew: 收到的奖励
terminated: 环境是否终止
truncated: 环境是否截断
info: 调试信息
keys_to_action –
从按下的键到执行的动作的映射。支持不同的格式:按键组合可以表示为键的 Unicode 代码点元组、字符元组或字符串,其中字符串的每个字符代表一个键。例如,如果同时按下 ‘w’ 和空格应该触发动作编号 2,则
key_to_action
字典可能如下所示>>> key_to_action = { ... # ... ... (ord('w'), ord(' ')): 2 ... # ... ... }
或像这样
>>> key_to_action = { ... # ... ... ("w", " "): 2 ... # ... ... }
或像这样
>>> key_to_action = { ... # ... ... "w ": 2 ... # ... ... }
如果为
None
,则使用该环境的默认key_to_action
映射(如果提供)。seed – 重置环境时使用的随机种子。如果为 None,则不使用种子。
noop – 当没有输入任何键输入或输入的键组合未知时使用的动作。
wait_on_player – 游戏应等待用户操作
示例
>>> import gymnasium as gym >>> import numpy as np >>> from gymnasium.utils.play import play >>> play(gym.make("CarRacing-v3", render_mode="rgb_array"), ... keys_to_action={ ... "w": np.array([0, 0.7, 0], dtype=np.float32), ... "a": np.array([-1, 0, 0], dtype=np.float32), ... "s": np.array([0, 0, 1], dtype=np.float32), ... "d": np.array([1, 0, 0], dtype=np.float32), ... "wa": np.array([-1, 0.7, 0], dtype=np.float32), ... "dw": np.array([1, 0.7, 0], dtype=np.float32), ... "ds": np.array([1, 0, 1], dtype=np.float32), ... "as": np.array([-1, 0, 1], dtype=np.float32), ... }, ... noop=np.array([0, 0, 0], dtype=np.float32) ... )
如果环境被封装,上面的代码也有效,因此它对于验证帧级预处理是否不会使游戏变得无法玩非常有用。
如果您希望在玩游戏时绘制实时统计数据,可以使用
PlayPlot
。这是一个绘制最近 150 步奖励的示例代码。>>> from gymnasium.utils.play import PlayPlot, play >>> def callback(obs_t, obs_tp1, action, rew, terminated, truncated, info): ... return [rew,] >>> plotter = PlayPlot(callback, 150, ["reward"]) >>> play(gym.make("CartPole-v1"), callback=plotter.callback)
- class gymnasium.utils.play.PlayPlot(callback: Callable, horizon_timesteps: int, plot_names: list[str])[源代码]¶
提供一个回调,以便在使用
play()
时创建任意指标的实时图。- 此类使用一个函数实例化,该函数接受有关单个环境转换的信息
obs_t: 执行动作前的观测
obs_tp1: 执行动作后的观测
action: 执行的动作
rew: 收到的奖励
terminated: 环境是否终止
truncated: 环境是否截断
info: 调试信息
它应该返回从此数据计算出的一系列指标。例如,该函数可能如下所示
>>> def compute_metrics(obs_t, obs_tp, action, reward, terminated, truncated, info): ... return [reward, info["cumulative_reward"], np.linalg.norm(action)]
PlayPlot
提供了方法callback()
,它将将其参数传递给该函数,并使用返回的值来更新指标的实时图。通常,此
callback()
将与play()
结合使用,以查看指标在您玩游戏时如何演变>>> plotter = PlayPlot(compute_metrics, horizon_timesteps=200, ... plot_names=["Immediate Rew.", "Cumulative Rew.", "Action Magnitude"]) >>> play(your_env, callback=plotter.callback)
- 参数:
callback – 从环境转换计算指标的函数
horizon_timesteps – 用于实时图的时间范围
plot_names – 图表标题列表
- 引发:
DependencyNotInstalled – 如果未安装 matplotlib
环境 pickle 化¶
- class gymnasium.utils.ezpickle.EzPickle(*args: Any, **kwargs: Any)[源代码]¶
通过其构造函数参数进行 pickle 和 unpickle 的对象。
示例
>>> class Animal: pass >>> class Dog(Animal, EzPickle): ... def __init__(self, furcolor, tailkind="bushy"): ... Animal.__init__(self) ... EzPickle.__init__(self, furcolor, tailkind)
当此对象被 unpickle 时,将通过将提供的 furcolor 和 tailkind 传递到构造函数中来构造一个新的
Dog
。但是,哲学家仍然不确定它是否还是同一条狗。这通常仅对于封装 C/C++ 代码的环境(例如 MuJoCo 和 Atari)是必需的。
使用对象构造函数中的
args
和kwargs
进行 pickle 化。
保存渲染视频¶
- gymnasium.utils.save_video.save_video(frames: list, video_folder: str, episode_trigger: Callable[[int], bool] = None, step_trigger: Callable[[int], bool] = None, video_length: int | None = None, name_prefix: str = 'rl-video', episode_index: int = 0, step_starting_index: int = 0, save_logger: str | None = None, **kwargs)[源代码]¶
从渲染帧保存视频。
此函数从渲染帧片段列表中提取视频。
- 参数:
frames (List[RenderFrame]) – 用于构成视频的帧列表。
video_folder (str) – 录像将存储在其中的文件夹
episode_trigger – 接受整数并返回
True
的函数,表示应在此 episode 开始录制step_trigger – 接受整数并返回
True
的函数,表示应在此 step 开始录制video_length (int) – 录制 episode 的长度。如果未指定,则录制整个 episode。否则,将捕获指定长度的片段。
name_prefix (str) – 将添加到录制文件名的前缀。
episode_index (int) – 当前 episode 的索引。
step_starting_index (int) – 第一帧的 step 索引。
save_logger – 是否记录视频保存进度,对于需要一段时间的长视频很有帮助,使用 “bar” 启用。
**kwargs – 将传递给 moviepy 的 ImageSequenceClip 的 kwargs。您需要指定 fps 或 duration。
示例
>>> import gymnasium as gym >>> from gymnasium.utils.save_video import save_video >>> env = gym.make("FrozenLake-v1", render_mode="rgb_array_list") >>> _ = env.reset() >>> step_starting_index = 0 >>> episode_index = 0 >>> for step_index in range(199): ... action = env.action_space.sample() ... _, _, terminated, truncated, _ = env.step(action) ... ... if terminated or truncated: ... save_video( ... frames=env.render(), ... video_folder="videos", ... fps=env.metadata["render_fps"], ... step_starting_index=step_starting_index, ... episode_index=episode_index ... ) ... step_starting_index = step_index + 1 ... episode_index += 1 ... env.reset() >>> env.close()
新旧 Step API 兼容性¶
- gymnasium.utils.step_api_compatibility.step_api_compatibility(step_returns: TerminatedTruncatedStepType | DoneStepType, output_truncation_bool: bool = True, is_vector_env: bool = False) TerminatedTruncatedStepType | DoneStepType [源代码]¶
用于将 step 返回值转换为
output_truncation_bool
指定的 API 的函数。Done (旧) step API 指的是
step()
方法返回(observation, reward, done, info)
。Terminated Truncated (新) step API 指的是step()
方法返回(observation, reward, terminated, truncated, info)
(有关 API 更改的详细信息,请参阅文档)- 参数:
step_returns (tuple) –
step()
返回的项。可以是(obs, rew, done, info)
或(obs, rew, terminated, truncated, info)
output_truncation_bool (bool) – 输出是否应返回两个布尔值(新 API)或一个(旧)(默认为
True
)is_vector_env (bool) –
step_returns
是否来自向量环境
- 返回:
step_returns (tuple) – 依赖于
output_truncation_bool
,它可以返回(obs, rew, done, info)
或(obs, rew, terminated, truncated, info)
示例
此函数可以用于确保在使用冲突 API 的 step 接口中的兼容性。例如,如果 env 使用旧 API 编写,wrapper 使用新 API 编写,并且最终的 step 输出需要使用旧 API。
>>> import gymnasium as gym >>> env = gym.make("CartPole-v0") >>> _, _ = env.reset() >>> obs, reward, done, info = step_api_compatibility(env.step(0), output_truncation_bool=False) >>> obs, reward, terminated, truncated, info = step_api_compatibility(env.step(0), output_truncation_bool=True)
>>> vec_env = gym.make_vec("CartPole-v0", vectorization_mode="sync") >>> _, _ = vec_env.reset() >>> obs, rewards, dones, infos = step_api_compatibility(vec_env.step([0]), is_vector_env=True, output_truncation_bool=False) >>> obs, rewards, terminations, truncations, infos = step_api_compatibility(vec_env.step([0]), is_vector_env=True, output_truncation_bool=True)
- gymnasium.utils.step_api_compatibility.convert_to_terminated_truncated_step_api(step_returns: DoneStepType | TerminatedTruncatedStepType, is_vector_env=False) TerminatedTruncatedStepType [source]¶
此函数用于将 step 返回值转换为新的 step API,而无需考虑输入 API。
- 参数:
step_returns (tuple) –
step()
返回的项。可以是(obs, rew, done, info)
或(obs, rew, terminated, truncated, info)
is_vector_env (bool) –
step_returns
是否来自向量环境
- gymnasium.utils.step_api_compatibility.convert_to_done_step_api(step_returns: TerminatedTruncatedStepType | DoneStepType, is_vector_env: bool = False) DoneStepType [source]¶
此函数用于将 step 返回值转换为旧的 step API,而无需考虑输入 API。
- 参数:
step_returns (tuple) –
step()
返回的项。可以是(obs, rew, done, info)
或(obs, rew, terminated, truncated, info)
is_vector_env (bool) –
step_returns
是否来自向量环境
运行时性能基准测试¶
有时需要测量您的环境的运行时性能,并确保不会发生性能衰退。这些测试需要手动检查其输出
- gymnasium.utils.performance.benchmark_step(env: Env, target_duration: int = 5, seed=None) float [source]¶
用于测量环境 step 运行时性能的基准测试。
- 使用示例
`py env_old = ... old_throughput = benchmark_step(env_old) env_new = ... new_throughput = benchmark_step(env_old) slowdown = old_throughput / new_throughput `
- 参数:
env – 要进行基准测试的环境。
target_duration – 基准测试的持续时间,以秒为单位(注意:会略微超过)。
seed – 为环境和采样的动作设定种子。
返回: 每秒平均步数。