스페이스

This module implements various spaces.

Spaces describe mathematical sets and are used in Gym to specify valid actions and observations. Every Gym environment must have the attributes action_space and observation_space. If, for instance, three possible actions (0,1,2) can be performed in your environment and observations are vectors in the two-dimensional unit cube, the environment code may contain the following two lines:

self.action_space = spaces.Discrete(3)
self.observation_space = spaces.Box(0, 1, shape=(2,))

All spaces inherit from the Space superclass.

class gymnasium.spaces.Space(shape: Sequence[int] | None = None, dtype: dtype[Any] | None | type[Any] | _SupportsDType[dtype[Any]] | str | tuple[Any, int] | tuple[Any, SupportsIndex | Sequence[SupportsIndex]] | list[Any] | _DTypeDict | tuple[Any, Any] = None, seed: int | Generator | None = None)[source]

Superclass that is used to define observation and action spaces.

Spaces are crucially used in Gym to define the format of valid actions and observations. They serve various purposes:

  • They clearly define how to interact with environments, i.e. they specify what actions need to look like and what observations will look like

  • They allow us to work with highly structured data (e.g. in the form of elements of Dict spaces) and painlessly transform them into flat arrays that can be used in learning code

  • They provide a method to sample random elements. This is especially useful for exploration and debugging.

Different spaces can be combined hierarchically via container spaces (Tuple and Dict) to build a more expressive space

Warning

Custom observation & action spaces can inherit from the Space class. However, most use-cases should be covered by the existing space classes (e.g. Box, Discrete, etc…), and container classes (Tuple & Dict). Note that parametrized probability distributions (through the Space.sample() method), and batching functions (in gym.vector.VectorEnv), are only well-defined for instances of spaces provided in gym by default. Moreover, some implementations of Reinforcement Learning algorithms might not handle custom spaces properly. Use custom spaces with care.

Parameters:
  • shape (Optional[Sequence[int]]) – If elements of the space are numpy arrays, this should specify their shape.

  • dtype (Optional[Type | str]) – If elements of the space are numpy arrays, this should specify their dtype.

  • seed – Optionally, you can use this argument to seed the RNG that is used to sample from the space

속성

property Space.shape: tuple[int, ...] | None

Return the shape of the space as an immutable property.

property Space.dtype

이 스페이스의 데이터 유형을 반환합니다.

property Space.is_np_flattenable: bool

Checks whether this space can be flattened to a gymnasium.spaces.Box.

property Space.np_random: Generator

Lazily seed the PRNG since this is expensive and only needed if sampling from this space.

As seed() is not guaranteed to set the _np_random for particular seeds. We add a check after seed() to set a new random number generator.

메소드

각 스페이스는 다음 함수를 구현합니다:

Space.sample(mask: Any | None = None, probability: Any | None = None) T_cov[source]

Randomly sample an element of this space.

Can be uniform or non-uniform sampling based on boundedness of space.

The binary mask and the probability mask can’t be used at the same time.

Parameters:
  • mask – A mask used for random sampling, expected dtype=np.int8 and see sample implementation for expected shape.

  • probability – A probability mask used for sampling according to the given probability distribution, expected dtype=np.float64 and see sample implementation for expected shape.

Returns:

A sampled actions from the space

Space.contains(x: Any) bool[source]

Return boolean specifying if x is a valid member of this space, equivalent to sample in space.

Space.seed(seed: int | None = None) int | list[int] | dict[str, int][source]

Seed the pseudorandom number generator (PRNG) of this space and, if applicable, the PRNGs of subspaces.

Parameters:

seed – The seed value for the space. This is expanded for composite spaces to accept multiple values. For further details, please refer to the space’s documentation.

Returns:

The seed values used for all the PRNGs, for composite spaces this can be a tuple or dictionary of values.

Space.to_jsonable(sample_n: Sequence[T_cov]) list[Any][source]

Convert a batch of samples from this space to a JSONable data type.

Space.from_jsonable(sample_n: list[Any]) list[T_cov][source]

Convert a JSONable data type to a batch of samples from this space.

기본 스페이스

Gymnasium은 더 복잡한 스페이스를 위한 구성 요소로 사용되는 여러 기본 스페이스를 가지고 있습니다.

  • Box - 연속형(및 이산형) 벡터 또는 행렬을 지원하며, 벡터 관찰, 이미지 등에 사용됩니다.

  • Discrete - 단일 이산형 값을 지원하며, 값의 시작점을 선택적으로 지정할 수 있습니다.

  • MultiBinary - 단일 또는 행렬 형태의 이진 값을 지원하며, 버튼을 누르거나 에이전트가 객체를 가지고 있는지 등에 사용됩니다.

  • MultiDiscrete - 여러 축에 걸쳐 다중 이산형 값을 지원하며, 컨트롤러 액션에 사용됩니다.

  • Text - 문자열을 지원하며, 에이전트 메시지 전달, 미션 세부 정보 등에 사용됩니다.

복합 스페이스

종종 환경 스페이스는 벡터화된 환경, 별도의 에이전트 또는 스페이스의 가독성을 위해 기본 스페이스를 함께 결합해야 합니다.

  • Dict - 키와 서브스페이스의 딕셔너리를 지원하며, 고정된 수의 순서 없는 스페이스에 사용됩니다.

  • Tuple - 서브스페이스의 튜플을 지원하며, 고정된 수의 순서 있는 스페이스에 사용됩니다.

  • Sequence - 단일 서브스페이스의 가변 개수 인스턴스를 지원하며, 엔티티 스페이스 또는 가변 개수의 액션 선택에 사용됩니다.

  • Graph - 이산형 또는 연속형 노드 및 에지 값을 가진 그래프 기반 액션 또는 관찰을 지원합니다.

  • OneOf - 액션이 N개의 가능한 서브스페이스 중 하나일 수 있도록 선택적 액션 스페이스를 지원합니다.

유틸리티 함수

Gymnasium은 스페이스를 평탄화하고 다시 평탄화하는 데 유용한 여러 유틸리티 함수를 포함하고 있습니다. 이는 신경망에 정보를 전달하는 데 중요할 수 있습니다.

벡터 유틸리티 함수

환경을 벡터화할 때, 새로운 배치 스페이스 크기에 맞게 관찰 및 액션 스페이스를 수정해야 합니다. 따라서 Gymnasium은 Vector 환경과 함께 스페이스를 사용할 때 사용되는 여러 추가 함수를 제공합니다.