• Stable Baselines/用户向导/使用自定义环境

    Stable Baselines官方文档中文版 Github CSDN 尝试翻译官方文档,水平有限,如有错误万望指正

    在自定义环境使用RL baselines,只需要遵循gym接口即可。

    也就是说,你的环境必须实现下述方法(并且继承自OpenAI Gym类):

    如果你用图像作为输入,输入值必须在[0,255]因为当用CNN策略时观测会被标准化(除以255让值落在[0,1])

    1. import gym
    2. from gym import spaces
    3. class CustomEnv(gym.Env):
    4. """Custom Environment that follows gym interface"""
    5. metadata = {'render.modes': ['human']}
    6. def __init__(self, arg1, arg2, ...):
    7. super(CustomEnv, self).__init__()
    8. # Define action and observation space
    9. # They must be gym.spaces objects
    10. # Example when using discrete actions:
    11. self.action_space = spaces.Discrete(N_DISCRETE_ACTIONS)
    12. # Example for using image as input:
    13. self.observation_space = spaces.Box(low=0, high=255,
    14. shape=(HEIGHT, WIDTH, N_CHANNELS), dtype=np.uint8)
    15. def step(self, action):
    16. ...
    17. def reset(self):
    18. ...
    19. def render(self, mode='human', close=False):
    20. ...

    然后你就可以用其训练一个RL智体:

    1. # Instantiate and wrap the env
    2. env = DummyVecEnv([lambda: CustomEnv(arg1, ...)])
    3. # Define and Train the agent
    4. model = A2C(CnnPolicy, env).learn(total_timesteps=1000)

    这里有一份创建自定义Gym环境的在线教程

    视需求,你还可以像gym注册环境,这可让用户实现一行创建Rl智体(并用gym.make()实例化环境)。

    本项目中,为测试方便,我们在这个文件夹下创建了名为IdentityEnv自定义环境。这里有一个如何使用的案例展示。