【问题标题】:OpenAI Gym - How to create one-hot observation space?OpenAI Gym - 如何打造一热式观察空间?
【发布时间】:2019-01-03 12:47:18
【问题描述】:

除了openAI's doc,我找不到更详细的文档。

我要知道正确的创作方式:

  1. 具有1..n 可能操作的操作空间。 (目前使用离散动作空间)

  2. 具有2^n 状态的观察空间 - 已采取的每种可能的操作组合的状态。 我想要动作向量的 one-hot 表示 - 1 表示 action was already taken,0 表示 action still hadn't been taken

如何使用 openAI 的 Gym 做到这一点?

谢谢

【问题讨论】:

    标签: python reinforcement-learning openai-gym


    【解决方案1】:

    在撰写本文时,gym 包提供的gym.Spaces 均不能用于镜像单热编码表示。

    幸运的是,我们可以通过创建gym.Spaces 的子类来定义自己的空间。

    我做了这样一个类,可能是你需要的:

    import gym
    import numpy as np
    
    
    class OneHotEncoding(gym.Space):
        """
        {0,...,1,...,0}
    
        Example usage:
        self.observation_space = OneHotEncoding(size=4)
        """
        def __init__(self, size=None):
            assert isinstance(size, int) and size > 0
            self.size = size
            gym.Space.__init__(self, (), np.int64)
    
        def sample(self):
            one_hot_vector = np.zeros(self.size)
            one_hot_vector[np.random.randint(self.size)] = 1
            return one_hot_vector
    
        def contains(self, x):
            if isinstance(x, (list, tuple, np.ndarray)):
                number_of_zeros = list(x).contains(0)
                number_of_ones = list(x).contains(1)
                return (number_of_zeros == (self.size - 1)) and (number_of_ones == 1)
            else:
                return False
    
        def __repr__(self):
            return "OneHotEncoding(%d)" % self.size
    
        def __eq__(self, other):
            return self.size == other.size
    

    你可以这样使用它:

    -> space = OneHotEncoding(size=3)
    -> space.sample()
    array([0., 1., 0.])
    -> space.sample()
    array([1., 0., 0.])
    -> space.sample()
    array([0., 0., 1.])
    

    希望能帮到你

    【讨论】:

    • 不错的一个!谢谢!我会接受,因为这是我问的,但我现在意识到我真正想要的是一个多合一热空间,这意味着,多个 1 可以同时存在。你将如何实现它?
    【解决方案2】:

    你要求的“多一热”空间已经实现了

    https://github.com/openai/gym/blob/master/gym/spaces/multi_binary.py

    import gym
    
    # create a MultiBinary Space
    # by passing n=10, each sample will contain 10 elements
    
    mb = gym.spaces.MultiBinary(n=10)
    
    mb.sample()
    
    # array([1, 0, 1, 0, 0, 0, 0, 0, 0, 1], dtype=int8)
    

    如果您想自己实现以确保在调用sample 时不超过一定数量的x 个正元素,您可以随机选择x 个索引从 n 选项中,然后在所有 0 的数组中翻转这些索引,然后返回。

    【讨论】:

      猜你喜欢
      • 2017-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-09
      • 2022-10-08
      • 2017-11-17
      相关资源
      最近更新 更多