python - OpenAI Gym - 如何打造独热观察空间?

标签 python reinforcement-learning openai-gym

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

我需要知道正确的创建方法:

  1. 一个具有 1..n 个可能操作的操作空间。 (当前使用离散 Action 空间)

  2. 具有 2^n 状态的观察空间 - 已采取的每种可能的操作组合的状态。 我想要 Action 向量的 one-hot 表示 - 1 表示已采取行动,0 表示尚未采取行动

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

谢谢

最佳答案

在撰写本文时,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.])

希望能帮到你

关于python - OpenAI Gym - 如何打造独热观察空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54022606/

相关文章:

deep-learning - 在健身房自定义环境中定义观察空间时出错

Python、redis : How do I set multiple key-value pairs at once

machine-learning - Q-学习(多目标)

tensorflow - 如何提高机器学习性能——DQ学习模型

python - DQN 理解输入和输出(层)

python - gym.make ('CartPole-v0' ) 返回什么以及它是如何工作的?

python - 应用 Horizo​​ntal Sobel Mask 将图像旋转 180 度

python - 如何实现 matlab 的 ismember(A, b),A 是一个 numpy ndarray,b 是一个列表

python - 克服 Active Directory 的 1000 条记录限制