Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Implementation:Farama Foundation Gymnasium FlattenObservation Wrapper

From Leeroopedia
Knowledge Sources
Domains Reinforcement_Learning, Preprocessing
Last Updated 2026-02-15 03:00 GMT

Overview

Concrete tool for flattening structured observations into flat vectors provided by the Gymnasium library.

Description

The FlattenObservation wrapper flattens the environment's observation space and each observation from reset and step. It uses spaces.utils.flatten_space to compute the flattened space and spaces.utils.flatten to transform each observation. This converts Dict, Tuple, or multi-dimensional Box observations into a single flat Box vector suitable for standard neural network architectures.

Usage

Wrap environments with Dict or Tuple observation spaces when using agents that expect flat vector inputs (e.g., MLP-based policies). Not needed for environments that already produce flat observations.

Code Reference

Source Location

  • Repository: Gymnasium
  • File: gymnasium/wrappers/transform_observation.py
  • Lines: L219-256

Signature

class FlattenObservation(TransformObservation):
    def __init__(self, env: gym.Env[ObsType, ActType]):
        """Flattens the environment's observation space and each observation.

        Args:
            env: The environment to wrap. Must have an observation space
                 that implements spaces.utils.flatten_space and spaces.utils.flatten.
        """

Import

from gymnasium.wrappers import FlattenObservation

I/O Contract

Inputs

Name Type Required Description
env gym.Env Yes Environment with any flattenable observation space

Outputs

Name Type Description
observation_space Box Flattened 1D Box space
observations np.ndarray Flat 1D arrays from reset() and step()

Usage Examples

Flatten Dict Observations

import gymnasium as gym
from gymnasium.wrappers import FlattenObservation

# Environment with Dict observation space
env = gym.make("CarRacing-v3")
print(env.observation_space.shape)  # (96, 96, 3)

env = FlattenObservation(env)
print(env.observation_space.shape)  # (27648,)

obs, _ = env.reset()
print(obs.shape)  # (27648,)
env.close()

Related Pages

Implements Principle

Requires Environment

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment