Observation Wrappers

class gymnasium.ObservationWrapper(env: Env[ObsType, ActType])[source]

使用 observation() 函数修改来自 Env.reset()Env.step() 的 observation。

如果你想仅在将 observation 传递给学习代码之前对其应用函数,你可以简单地从 ObservationWrapper 继承并覆盖方法 observation() 以实现该转换。在该方法中定义的转换必须通过 env observation space 反映出来。否则,你需要通过在你的 wrapper 的 __init__() 方法中设置 self.observation_space 来指定 wrapper 的新 observation space。

参数:

env – 要包装的环境。

observation(observation: ObsType) WrapperObsType[source]

返回修改后的 observation。

参数:

observationenv observation

返回:

修改后的 observation

已实现的 Wrappers

class gymnasium.wrappers.TransformObservation(env: gym.Env[ObsType, ActType], func: Callable[[ObsType], Any], observation_space: gym.Space[WrapperObsType] | None)[source]

将函数应用于从环境的 Env.reset()Env.step() 接收的 observation,该 observation 将传递回用户。

函数 func 将应用于所有 observation。如果来自 func 的 observation 超出 env 的 observation space 的范围,请提供更新后的 observation_space

wrapper 的向量版本存在 gymnasium.wrappers.vector.TransformObservation

示例

>>> import gymnasium as gym
>>> from gymnasium.wrappers import TransformObservation
>>> import numpy as np
>>> np.random.seed(0)
>>> env = gym.make("CartPole-v1")
>>> env.reset(seed=42)
(array([ 0.0273956 , -0.00611216,  0.03585979,  0.0197368 ], dtype=float32), {})
>>> env = gym.make("CartPole-v1")
>>> env = TransformObservation(env, lambda obs: obs + 0.1 * np.random.random(obs.shape), env.observation_space)
>>> env.reset(seed=42)
(array([0.08227695, 0.06540678, 0.09613613, 0.07422512]), {})
更新日志
  • v0.15.4 - 初始添加

  • v1.0.0 - 添加 observation_space 的要求

参数:
  • env – 要包装的环境

  • func – 将转换 observation 的函数。如果此转换后的 observation 超出 env.observation_space 的 observation space,则提供 observation_space

  • observation_space – wrapper 的 observation space,如果为 None,则假定与 env.observation_space 相同。

class gymnasium.wrappers.DelayObservation(env: Env[ObsType, ActType], delay: int)[source]

为从环境返回的 observation 添加延迟。

在达到 delay 步数之前,返回的 observation 是一个零数组,其形状与 observation space 相同。

wrapper 没有向量版本。

注意

这不支持随机延迟值,如果用户对此感兴趣,请提出 issue 或 pull request 以添加此功能。

示例

>>> import gymnasium as gym
>>> env = gym.make("CartPole-v1")
>>> env.reset(seed=123)
(array([ 0.01823519, -0.0446179 , -0.02796401, -0.03156282], dtype=float32), {})
>>> env = DelayObservation(env, delay=2)
>>> env.reset(seed=123)
(array([0., 0., 0., 0.], dtype=float32), {})
>>> env.step(env.action_space.sample())
(array([0., 0., 0., 0.], dtype=float32), 1.0, False, False, {})
>>> env.step(env.action_space.sample())
(array([ 0.01823519, -0.0446179 , -0.02796401, -0.03156282], dtype=float32), 1.0, False, False, {})
更新日志
  • v1.0.0 - 初始添加

参数:
  • env – 要包装的环境

  • delay – 延迟 observation 的步数

class gymnasium.wrappers.DtypeObservation(env: Env[ObsType, ActType], dtype: Any)[source]

将 observation 数组的 dtype 修改为指定的 dtype。

注意

这仅与 BoxDiscreteMultiDiscreteMultiBinary observation space 兼容

wrapper 的向量版本存在 gymnasium.wrappers.vector.DtypeObservation

更新日志
  • v1.0.0 - 初始添加

参数:
  • env – 要包装的环境

  • dtype – observation 的新 dtype

class gymnasium.wrappers.FilterObservation(env: gym.Env[ObsType, ActType], filter_keys: Sequence[str | int])[source]

通过一组键或索引过滤 Dict 或 Tuple observation space。

wrapper 的向量版本存在 gymnasium.wrappers.vector.FilterObservation

示例

>>> import gymnasium as gym
>>> from gymnasium.wrappers import FilterObservation
>>> env = gym.make("CartPole-v1")
>>> env = gym.wrappers.TimeAwareObservation(env, flatten=False)
>>> env.observation_space
Dict('obs': Box([-4.8               -inf -0.41887903        -inf], [4.8               inf 0.41887903        inf], (4,), float32), 'time': Box(0, 500, (1,), int32))
>>> env.reset(seed=42)
({'obs': array([ 0.0273956 , -0.00611216,  0.03585979,  0.0197368 ], dtype=float32), 'time': array([0], dtype=int32)}, {})
>>> env = FilterObservation(env, filter_keys=['time'])
>>> env.reset(seed=42)
({'time': array([0], dtype=int32)}, {})
>>> env.step(0)
({'time': array([1], dtype=int32)}, 1.0, False, False, {})
更新日志
  • v0.12.3 - 初始添加,最初称为 FilterObservationWrapper

  • v1.0.0 - 重命名为 FilterObservation 并添加对带有整数 filter_keys 的 tuple observation space 的支持

参数:
  • env – 要包装的环境

  • filter_keys – 要包含的子空间集,对 Dict 使用字符串列表,对 Tuple space 使用整数

class gymnasium.wrappers.FlattenObservation(env: Env[ObsType, ActType])[source]

展平环境的 observation space 以及来自 resetstep 函数的每个 observation。

wrapper 的向量版本存在 gymnasium.wrappers.vector.FlattenObservation

示例

>>> import gymnasium as gym
>>> from gymnasium.wrappers import FlattenObservation
>>> env = gym.make("CarRacing-v3")
>>> env.observation_space.shape
(96, 96, 3)
>>> env = FlattenObservation(env)
>>> env.observation_space.shape
(27648,)
>>> obs, _ = env.reset()
>>> obs.shape
(27648,)
更新日志
  • v0.15.0 - 初始添加

参数:

env – 要包装的环境

class gymnasium.wrappers.FrameStackObservation(env: gym.Env[ObsType, ActType], stack_size: int, *, padding_type: str | ObsType = 'reset')[source]

以滚动方式堆叠来自最后 N 个时间步的 observation。

例如,如果堆叠数为 4,则返回的 observation 包含最近的 4 个 observation。对于环境 ‘Pendulum-v1’,原始 observation 是形状为 [3] 的数组,因此如果我们堆叠 4 个 observation,则处理后的 observation 的形状为 [4, 3]。

用户可以选择使用的填充 observation

  • “reset”(默认)- 重复重置值

  • “zero” - observation space 的“零”类实例

  • custom - observation space 的实例

wrapper 没有向量版本。

示例

>>> import gymnasium as gym
>>> from gymnasium.wrappers import FrameStackObservation
>>> env = gym.make("CarRacing-v3")
>>> env = FrameStackObservation(env, stack_size=4)
>>> env.observation_space
Box(0, 255, (4, 96, 96, 3), uint8)
>>> obs, _ = env.reset()
>>> obs.shape
(4, 96, 96, 3)
具有不同填充 observation 的示例
>>> env = gym.make("CartPole-v1")
>>> env.reset(seed=123)
(array([ 0.01823519, -0.0446179 , -0.02796401, -0.03156282], dtype=float32), {})
>>> stacked_env = FrameStackObservation(env, 3)   # the default is padding_type="reset"
>>> stacked_env.reset(seed=123)
(array([[ 0.01823519, -0.0446179 , -0.02796401, -0.03156282],
       [ 0.01823519, -0.0446179 , -0.02796401, -0.03156282],
       [ 0.01823519, -0.0446179 , -0.02796401, -0.03156282]],
      dtype=float32), {})
>>> stacked_env = FrameStackObservation(env, 3, padding_type="zero")
>>> stacked_env.reset(seed=123)
(array([[ 0.        ,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.        ,  0.        ],
       [ 0.01823519, -0.0446179 , -0.02796401, -0.03156282]],
      dtype=float32), {})
>>> stacked_env = FrameStackObservation(env, 3, padding_type=np.array([1, -1, 0, 2], dtype=np.float32))
>>> stacked_env.reset(seed=123)
(array([[ 1.        , -1.        ,  0.        ,  2.        ],
       [ 1.        , -1.        ,  0.        ,  2.        ],
       [ 0.01823519, -0.0446179 , -0.02796401, -0.03156282]],
      dtype=float32), {})
更新日志
  • v0.15.0 - 最初添加为 FrameStack,支持 lz4

  • v1.0.0 - 重命名为 FrameStackObservation 并删除 lz4 和 LazyFrame 支持

    以及添加 padding_type 参数

参数:
  • env – 应用 wrapper 的环境

  • stack_size – 要堆叠的帧数。

  • padding_type – 堆叠 observation 时要使用的填充类型,选项:“reset”、“zero”、自定义 obs

class gymnasium.wrappers.GrayscaleObservation(env: Env[ObsType, ActType], keep_dim: bool = False)[source]

resetstep 计算的图像 observation 从 RGB 转换为灰度。

keep_dim 将保留通道维度。

wrapper 的向量版本存在 gymnasium.wrappers.vector.GrayscaleObservation

示例

>>> import gymnasium as gym
>>> from gymnasium.wrappers import GrayscaleObservation
>>> env = gym.make("CarRacing-v3")
>>> env.observation_space.shape
(96, 96, 3)
>>> grayscale_env = GrayscaleObservation(env)
>>> grayscale_env.observation_space.shape
(96, 96)
>>> grayscale_env = GrayscaleObservation(env, keep_dim=True)
>>> grayscale_env.observation_space.shape
(96, 96, 1)
更新日志
  • v0.15.0 - 初始添加,最初称为 GrayScaleObservation

  • v1.0.0 - 重命名为 GrayscaleObservation

参数:
  • env – 要包装的环境

  • keep_dim – 是否在 observation 中保留通道,如果 Trueobs.shape == 3 否则 obs.shape == 2

class gymnasium.wrappers.MaxAndSkipObservation(env: Env[ObsType, ActType], skip: int = 4)[source]

跳过第 N 帧(observation)并返回最后两个 observation 之间的最大值。

wrapper 没有向量版本。

示例

>>> import gymnasium as gym
>>> env = gym.make("CartPole-v1")
>>> obs0, *_ = env.reset(seed=123)
>>> obs1, *_ = env.step(1)
>>> obs2, *_ = env.step(1)
>>> obs3, *_ = env.step(1)
>>> obs4, *_ = env.step(1)
>>> skip_and_max_obs = np.max(np.stack([obs3, obs4], axis=0), axis=0)
>>> env = gym.make("CartPole-v1")
>>> wrapped_env = MaxAndSkipObservation(env)
>>> wrapped_obs0, *_ = wrapped_env.reset(seed=123)
>>> wrapped_obs1, *_ = wrapped_env.step(1)
>>> np.all(obs0 == wrapped_obs0)
np.True_
>>> np.all(wrapped_obs1 == skip_and_max_obs)
np.True_
更新日志
  • v1.0.0 - 初始添加

参数:
  • env (Env) – 应用 wrapper 的环境

  • skip – 要跳过的帧数

class gymnasium.wrappers.NormalizeObservation(env: Env[ObsType, ActType], epsilon: float = 1e-8)[source]

将 observation 归一化为以均值为中心且单位方差。

属性 update_running_mean 允许冻结/继续 observation 统计数据的运行均值计算。如果 True(默认),则每次调用 stepreset 时,RunningMeanStd 都会更新。如果 False,则使用计算的统计数据,但不再更新;这可能在评估期间使用。

wrapper 的向量版本存在 gymnasium.wrappers.vector.NormalizeObservation

注意

归一化取决于过去的轨迹,如果 wrapper 是新实例化的或策略最近更改,则 observation 将无法正确归一化。

示例

>>> import numpy as np
>>> import gymnasium as gym
>>> env = gym.make("CartPole-v1")
>>> obs, info = env.reset(seed=123)
>>> term, trunc = False, False
>>> while not (term or trunc):
...     obs, _, term, trunc, _ = env.step(1)
...
>>> obs
array([ 0.1511158 ,  1.7183299 , -0.25533703, -2.8914354 ], dtype=float32)
>>> env = gym.make("CartPole-v1")
>>> env = NormalizeObservation(env)
>>> obs, info = env.reset(seed=123)
>>> term, trunc = False, False
>>> while not (term or trunc):
...     obs, _, term, trunc, _ = env.step(1)
>>> obs
array([ 2.0059888,  1.5676788, -1.9944268, -1.6120394], dtype=float32)
更新日志
  • v0.21.0 - 初始添加

  • v1.0.0 - 添加 update_running_mean 属性以允许禁用更新运行均值/标准差,这在评估时间尤其有用。

    将所有 observation 转换为 np.float32,并将 observation space 设置为低/高 -np.infnp.inf,dtype 为 np.float32

参数:
  • env (Env) – 应用 wrapper 的环境

  • epsilon – 用于缩放 observation 的稳定性参数。

class gymnasium.wrappers.AddRenderObservation(env: Env[ObsType, ActType], render_only: bool = True, render_key: str = 'pixels', obs_key: str = 'state')[source]

在环境的 observation 中包含渲染的 observation。

注意

这以前称为 PixelObservationWrapper

wrapper 没有向量版本。

示例 - 将 observation 替换为渲染的图像
>>> env = gym.make("CartPole-v1", render_mode="rgb_array")
>>> env = AddRenderObservation(env, render_only=True)
>>> env.observation_space
Box(0, 255, (400, 600, 3), uint8)
>>> obs, _ = env.reset(seed=123)
>>> image = env.render()
>>> np.all(obs == image)
np.True_
>>> obs, *_ = env.step(env.action_space.sample())
>>> image = env.render()
>>> np.all(obs == image)
np.True_
示例 - 将渲染的图像添加到原始 observation 作为字典项
>>> env = gym.make("CartPole-v1", render_mode="rgb_array")
>>> env = AddRenderObservation(env, render_only=False)
>>> env.observation_space
Dict('pixels': Box(0, 255, (400, 600, 3), uint8), 'state': Box([-4.8               -inf -0.41887903        -inf], [4.8               inf 0.41887903        inf], (4,), float32))
>>> obs, info = env.reset(seed=123)
>>> obs.keys()
dict_keys(['state', 'pixels'])
>>> obs["state"]
array([ 0.01823519, -0.0446179 , -0.02796401, -0.03156282], dtype=float32)
>>> np.all(obs["pixels"] == env.render())
np.True_
>>> obs, reward, terminates, truncates, info = env.step(env.action_space.sample())
>>> image = env.render()
>>> np.all(obs["pixels"] == image)
np.True_
更新日志
  • v0.15.0 - 最初添加为 PixelObservationWrapper

  • v1.0.0 - 重命名为 AddRenderObservation

参数:
  • env – 要包装的环境。

  • render_only (bool) – 如果 True(默认),则会丢弃包装环境返回的原始 observation,并且字典 observation 将仅包含像素。如果 False,则 observation 字典将同时包含原始 observation 和像素 observation。

  • render_key – 可选的自定义字符串,用于指定像素键。默认为“pixels”

  • obs_key – 可选的自定义字符串,用于指定 obs 键。默认为“state”

class gymnasium.wrappers.ResizeObservation(env: Env[ObsType, ActType], shape: tuple[int, int])[source]

使用 OpenCV 将图像 observation 调整为指定的形状。

wrapper 的向量版本存在 gymnasium.wrappers.vector.ResizeObservation

示例

>>> import gymnasium as gym
>>> from gymnasium.wrappers import ResizeObservation
>>> env = gym.make("CarRacing-v3")
>>> env.observation_space.shape
(96, 96, 3)
>>> resized_env = ResizeObservation(env, (32, 32))
>>> resized_env.observation_space.shape
(32, 32, 3)
更新日志
  • v0.12.6 - 初始添加

  • v1.0.0 - 需要包含两个整数的 shape 元组

参数:
  • env – 要包装的环境

  • shape – 调整大小后的 observation 形状

class gymnasium.wrappers.ReshapeObservation(env: gym.Env[ObsType, ActType], shape: int | tuple[int, ...])[source]

重塑基于数组的观测空间为指定的形状。

存在一个向量版本的包装器 gymnasium.wrappers.vector.RescaleObservation

示例

>>> import gymnasium as gym
>>> from gymnasium.wrappers import ReshapeObservation
>>> env = gym.make("CarRacing-v3")
>>> env.observation_space.shape
(96, 96, 3)
>>> reshape_env = ReshapeObservation(env, (24, 4, 96, 1, 3))
>>> reshape_env.observation_space.shape
(24, 4, 96, 1, 3)
更新日志
  • v1.0.0 - 初始添加

参数:
  • env – 要包装的环境

  • shape – 重塑后的观测空间

class gymnasium.wrappers.RescaleObservation(env: gym.Env[ObsType, ActType], min_obs: np.floating | np.integer | np.ndarray, max_obs: np.floating | np.integer | np.ndarray)[source]

将环境的 Box 观测空间仿射(线性地)重新缩放到 [min_obs, max_obs] 的范围内。

对于原始观测空间中无界的组件,相应的目标边界也必须是无限的,反之亦然。

存在一个向量版本的包装器 gymnasium.wrappers.vector.RescaleObservation

示例

>>> import gymnasium as gym
>>> from gymnasium.wrappers import RescaleObservation
>>> env = gym.make("Pendulum-v1")
>>> env.observation_space
Box([-1. -1. -8.], [1. 1. 8.], (3,), float32)
>>> env = RescaleObservation(env, np.array([-2, -1, -10], dtype=np.float32), np.array([1, 0, 1], dtype=np.float32))
>>> env.observation_space
Box([ -2.  -1. -10.], [1. 0. 1.], (3,), float32)
更新日志
  • v1.0.0 - 初始添加

参数:
  • env – 要包装的环境

  • min_obs – 新的最小观测边界

  • max_obs – 新的最大观测边界

class gymnasium.wrappers.TimeAwareObservation(env: Env[ObsType, ActType], flatten: bool = True, normalize_time: bool = False, *, dict_time_key: str = 'time')[source]

使用 episode 内采取的时间步数来增强观测。

如果 normalize_timeTrue,则时间表示为 [0,1] 之间的归一化值;否则,如果 False,则当前时间步是一个整数。

对于具有 Dict 观测空间的环境,时间信息会自动添加到键 “time” 中(可以通过 dict_time_key 更改),对于具有 Tuple 观测空间的环境,时间信息将作为元组中的最后一个元素添加。否则,观测空间将转换为 Dict 观测空间,其中包含两个键,“obs” 用于基本环境的观测,“time” 用于时间信息。

要展平观测,请使用 flatten 参数,该参数将使用 gymnasium.spaces.utils.flatten() 函数。

wrapper 没有向量版本。

示例

>>> import gymnasium as gym
>>> from gymnasium.wrappers import TimeAwareObservation
>>> env = gym.make("CartPole-v1")
>>> env = TimeAwareObservation(env)
>>> env.observation_space
Box([-4.80000019        -inf -0.41887903        -inf  0.        ], [4.80000019e+00            inf 4.18879032e-01            inf
 5.00000000e+02], (5,), float64)
>>> env.reset(seed=42)[0]
array([ 0.0273956 , -0.00611216,  0.03585979,  0.0197368 ,  0.        ])
>>> _ = env.action_space.seed(42)
>>> env.step(env.action_space.sample())[0]
array([ 0.02727336, -0.20172954,  0.03625453,  0.32351476,  1.        ])
归一化时间观测空间示例
>>> env = gym.make('CartPole-v1')
>>> env = TimeAwareObservation(env, normalize_time=True)
>>> env.observation_space
Box([-4.8               -inf -0.41887903        -inf  0.        ], [4.8               inf 0.41887903        inf 1.        ], (5,), float32)
>>> env.reset(seed=42)[0]
array([ 0.0273956 , -0.00611216,  0.03585979,  0.0197368 ,  0.        ],
      dtype=float32)
>>> _ = env.action_space.seed(42)
>>> env.step(env.action_space.sample())[0]
array([ 0.02727336, -0.20172954,  0.03625453,  0.32351476,  0.002     ],
      dtype=float32)
展平观测空间示例
>>> env = gym.make("CartPole-v1")
>>> env = TimeAwareObservation(env, flatten=False)
>>> env.observation_space
Dict('obs': Box([-4.8               -inf -0.41887903        -inf], [4.8               inf 0.41887903        inf], (4,), float32), 'time': Box(0, 500, (1,), int32))
>>> env.reset(seed=42)[0]
{'obs': array([ 0.0273956 , -0.00611216,  0.03585979,  0.0197368 ], dtype=float32), 'time': array([0], dtype=int32)}
>>> _ = env.action_space.seed(42)
>>> env.step(env.action_space.sample())[0]
{'obs': array([ 0.02727336, -0.20172954,  0.03625453,  0.32351476], dtype=float32), 'time': array([1], dtype=int32)}
更新日志
  • v0.18.0 - 初始添加

  • v1.0.0 - 移除向量环境支持,添加 flattennormalize_time 参数

参数:
  • env – 应用 wrapper 的环境

  • flatten – 将观测展平为单维的 Box

  • normalize_time – 如果为 True,则返回 [0,1] 范围内的时间;否则,返回截断前的剩余时间步数

  • dict_time_key – 对于具有 Dict 观测空间的环境,时间空间的键。 默认为 “time”