向量化

Gymnasium.vector.VectorEnv

class gymnasium.vector.VectorEnv[source]

向量化环境的基类,用于并行运行同一环境的多个独立副本。

向量环境可以通过同时采样多个子环境,在线性步数/秒的速度上提供加速。Gymnasium 包含两个通用的向量环境:AsyncVectorEnvSyncVectorEnv 以及几个自定义向量环境实现。对于每个子环境的 reset()step() 批次 observationsrewardsterminationstruncationsinfo,请参见以下示例。对于 rewardsterminationstruncations,数据被打包成形状为 (num_envs,) 的 NumPy 数组。对于 observations(和 actions),批处理过程取决于观测(和动作)空间的类型,并且通常针对神经网络输入/输出进行了优化。对于 info,数据保留为字典,以便键将给出所有子环境的数据。

为了创建环境,make_vec() 是向量环境,等效于 make(),用于轻松创建向量环境,其中包含用于修改环境质量、环境数量、向量化器类型、向量化器参数的多个独特参数。

为了避免在重置之前必须等待所有子环境终止,实现可以在剧集结束时自动重置子环境(terminated 或 truncated 为 True)。这对于使用向量环境正确实现训练算法至关重要。默认情况下,Gymnasium 的实现使用 next-step 自动重置,并使用 AutoresetMode 枚举作为选项。向量环境使用的模式应在 metadata[“autoreset_mode”] 中可用。警告,某些向量实现或训练算法将仅支持特定的自动重置模式。有关更多信息,请阅读 https://farama.org/Vector-Autoreset-Mode

注意

reset()step() 的 info 参数最初在 v0.25 之前实现为每个子环境的字典列表。但是,在 v0.25+ 中,它被修改为字典,每个键都有一个 NumPy 数组。要使用旧的 info 样式,请使用 DictInfoToList 封装器。

示例

>>> import gymnasium as gym
>>> envs = gym.make_vec("CartPole-v1", num_envs=3, vectorization_mode="sync", wrappers=(gym.wrappers.TimeAwareObservation,))
>>> envs = gym.wrappers.vector.ClipReward(envs, min_reward=0.2, max_reward=0.8)
>>> envs
<ClipReward, SyncVectorEnv(CartPole-v1, num_envs=3)>
>>> envs.num_envs
3
>>> envs.action_space
MultiDiscrete([2 2 2])
>>> envs.observation_space
Box([[-4.80000019        -inf -0.41887903        -inf  0.        ]
 [-4.80000019        -inf -0.41887903        -inf  0.        ]
 [-4.80000019        -inf -0.41887903        -inf  0.        ]], [[4.80000019e+00            inf 4.18879032e-01            inf
  5.00000000e+02]
 [4.80000019e+00            inf 4.18879032e-01            inf
  5.00000000e+02]
 [4.80000019e+00            inf 4.18879032e-01            inf
  5.00000000e+02]], (3, 5), float64)
>>> observations, infos = envs.reset(seed=123)
>>> observations
array([[ 0.01823519, -0.0446179 , -0.02796401, -0.03156282,  0.        ],
       [ 0.02852531,  0.02858594,  0.0469136 ,  0.02480598,  0.        ],
       [ 0.03517495, -0.000635  , -0.01098382, -0.03203924,  0.        ]])
>>> infos
{}
>>> _ = envs.action_space.seed(123)
>>> actions = envs.action_space.sample()
>>> observations, rewards, terminations, truncations, infos = envs.step(actions)
>>> observations
array([[ 0.01734283,  0.15089367, -0.02859527, -0.33293587,  1.        ],
       [ 0.02909703, -0.16717631,  0.04740972,  0.3319138 ,  1.        ],
       [ 0.03516225, -0.19559774, -0.01162461,  0.25715804,  1.        ]])
>>> rewards
array([0.8, 0.8, 0.8])
>>> terminations
array([False, False, False])
>>> truncations
array([False, False, False])
>>> infos
{}
>>> envs.close()

向量环境具有额外的属性,供用户理解实现

方法

VectorEnv.step(actions: ActType) tuple[ObsType, ArrayType, ArrayType, ArrayType, dict[str, Any]][source]

为每个并行环境采取一个动作。

参数:

actions – 具有 action_space 形状的动作批次。

返回值:

批量的 (观测, 奖励, 终止, 截断, 信息)

注意

由于向量环境为终止和截断的子环境自动重置,因此这将在 terminated 或 truncated 为 True 之后的下一步发生。

示例

>>> import gymnasium as gym
>>> import numpy as np
>>> envs = gym.make_vec("CartPole-v1", num_envs=3, vectorization_mode="sync")
>>> _ = envs.reset(seed=42)
>>> actions = np.array([1, 0, 1], dtype=np.int32)
>>> observations, rewards, terminations, truncations, infos = envs.step(actions)
>>> observations
array([[ 0.02727336,  0.18847767,  0.03625453, -0.26141977],
       [ 0.01431748, -0.24002443, -0.04731862,  0.3110827 ],
       [-0.03822722,  0.1710671 , -0.00848456, -0.2487226 ]],
      dtype=float32)
>>> rewards
array([1., 1., 1.])
>>> terminations
array([False, False, False])
>>> terminations
array([False, False, False])
>>> infos
{}
VectorEnv.reset(*, seed: int | None = None, options: dict[str, Any] | None = None) tuple[ObsType, dict[str, Any]][source]

重置所有并行环境,并返回初始观测和信息的批次。

参数:
  • seed – 环境重置种子

  • options – 是否返回选项

返回值:

来自向量化环境的观测和信息的批次。

示例

>>> import gymnasium as gym
>>> envs = gym.make_vec("CartPole-v1", num_envs=3, vectorization_mode="sync")
>>> observations, infos = envs.reset(seed=42)
>>> observations
array([[ 0.0273956 , -0.00611216,  0.03585979,  0.0197368 ],
       [ 0.01522993, -0.04562247, -0.04799704,  0.03392126],
       [-0.03774345, -0.02418869, -0.00942293,  0.0469184 ]],
      dtype=float32)
>>> infos
{}
VectorEnv.render() tuple[RenderFrame, ...] | None[source]

返回来自并行环境的渲染帧。

返回值:

来自并行环境的渲染帧的元组

VectorEnv.close(**kwargs: Any)[source]

关闭所有并行环境并释放资源。

它还会关闭所有现有的图像查看器,然后调用 close_extras() 并将 closed 设置为 True

警告

此函数本身不关闭环境,它应在 close_extras() 中处理。这对于同步和异步向量化环境都是通用的。

注意

当垃圾回收或程序退出时,将自动调用此函数。

参数:

**kwargs – 传递给 close_extras() 的关键字参数

属性

VectorEnv.num_envs: int

向量环境中子环境的数量。

VectorEnv.action_space: gym.Space

(批处理的)动作空间。step 的输入动作必须是 action_space 的有效元素。

VectorEnv.observation_space: gym.Space

(批处理的)观测空间。resetstep 返回的观测是 observation_space 的有效元素。

VectorEnv.single_action_space: gym.Space

子环境的动作空间。

VectorEnv.single_observation_space: gym.Space

子环境的观测空间。

VectorEnv.spec: EnvSpec | None = None

环境的 EnvSpec,通常在 gymnasium.make_vec() 期间设置

VectorEnv.metadata: dict[str, Any] = {}

环境的元数据,包含渲染模式、渲染 fps 等

VectorEnv.render_mode: str | None = None

环境的渲染模式,应遵循与 Env.render_mode 类似的规范。

VectorEnv.closed: bool = False

向量环境是否已关闭。

其他方法

property VectorEnv.unwrapped

返回基础环境。

property VectorEnv.np_random: Generator

返回环境的内部 _np_random,如果未设置,将使用随机种子初始化。

返回值:

`np.random.Generator` 的实例

property VectorEnv.np_random_seed: int | None

返回环境的内部 _np_random_seed,如果未设置,将首先使用随机整数作为种子进行初始化。

如果 np_random_seed 是直接设置的,而不是通过 reset()set_np_random_through_seed() 设置的,则种子将取值 -1。

返回值:

int – 当前 np_random 的种子,如果 rng 的种子未知,则为 -1

创建向量环境

为了创建向量环境,gymnasium 提供了 gymnasium.make_vec(),作为 gymnasium.make() 的等效函数。