OpenAI Gym のプログラムを試してみる

https://www.gymlibrary.ml/ に記載の手順をなぞっている(現在,このページは公開されていない)

Web ページhttps://github.com/openai/gym/blob/master/examples/agents/random_agent.py のプログラムを実行してみる.

前準備

OpenAI Gym のインストール

OpenAI Gym のインストールは,別ページ »で説明

OpenAI Gym を使ってみる

ランダム動作のプログラム

まずは、ランダムな動作.前準備がうまくいったかの確認も兼ねる.

Python プログラムを動かしたい.

Python プログラムの実行

【サイト内の関連ページ】 Python のまとめ: 別ページ »

import gym

env = gym.make('CartPole-v1')  # make your environment!

for i_episode in range(20):
    observation = env.reset()
    for t in range(100):
        env.render()  # render game screen
        action = env.action_space.sample()  # this is random action. replace here to your algorithm!
        observation, reward, done, info = env.step(action)  # get reward and next scene
        if done:
            print("Episode finished after {} timesteps".format(t+1))
            break

次のような画面が出る.

Environment の確認

Python プログラムを動かしたい.

Python プログラムの実行

【サイト内の関連ページ】 Python のまとめ: 別ページ »

import gym

env = gym.make('CartPole-v1')  # make your environment!

for i_episode in range(20):
    observation = env.reset()
    for t in range(100):
        env.render()  # render game screen
        print(observation)
        action = env.action_space.sample()  # this is random action. replace here to your algorithm!
        observation, reward, done, info = env.step(action)  # get reward and next scene
        if done:
            print("Episode finished after {} timesteps".format(t+1))
            break

結果を確認する.

ここに出ているのは、各繰り返し (timestep) での Environment の値 (変数名は observation). 繰り返しが進むと、Environment の値が変化していることがわかる。

空間 (space)

Python プログラムを動かしたい.

Python プログラムの実行

【サイト内の関連ページ】 Python のまとめ: 別ページ »

import gym
env = gym.make('CartPole-v1')
print(env.action_space)
#> Discrete(2)
print(env.observation_space)
#> Box(4,)

結果を確認する.

ログを残すプログラム

関連する外部ページ】https://github.com/openai/gym/blob/master/examples/agents/random_agent.py のプログラムを使用している.

  1. FFmpeg のインストール
  2. Python プログラムの実行

    Python プログラムの実行

    Python 開発環境(Jupyter Qt Console, Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, Spyder, PyCharm, PyScripterなど)も便利である.

    Python のまとめ: 別ページ »にまとめ

    python
    
    import argparse
    import logging
    import sys
    
    import gym
    from gym import wrappers
    
    
    class RandomAgent(object):
        """The world's simplest agent!"""
        def __init__(self, action_space):
            self.action_space = action_space
    
        def act(self, observation, reward, done):
            return self.action_space.sample()
    
    if __name__ == '__main__':    parser = argparse.ArgumentParser(description=None)
        parser.add_argument('env_id', nargs='?', default='CartPole-v1', help='Select the environment to run')
        args = parser.parse_args()
    
        # Call `undo_logger_setup` if you want to undo Gym's logger setup
        # and configure things manually. (The default should be fine most
        # of the time.)
        gym.undo_logger_setup()
        logger = logging.getLogger()
        formatter = logging.Formatter('[%(asctime)s] %(message)s')
        handler = logging.StreamHandler(sys.stderr)
        handler.setFormatter(formatter)
        logger.addHandler(handler)
    
        # You can set the level to logging.DEBUG or logging.WARN if you
        # want to change the amount of output.
        logger.setLevel(logging.INFO)
    
        env = gym.make(args.env_id)
    
        # You provide the directory to write to (can be an existing
        # directory, including one with existing data -- all monitor files
        # will be namespaced). You can also dump to a tempdir if you'd
        # like: tempfile.mkdtemp().
        outdir = 'random-agent-results'
        env = wrappers.Monitor(env, directory=outdir, force=True)
        env.seed(0)
        agent = RandomAgent(env.action_space)
    
        episode_count = 100
        reward = 0
        done = False
    
        for i in range(episode_count):
            ob = env.reset()
            while True:
                action = agent.act(ob, reward, done)
                ob, reward, done, _ = env.step(action)
                if done:
                    break
                # Note there's no env.render() here. But the environment still can open window and
                # render if asked by env.monitor: it calls env.render('rgb_array') to record video.
                # Video is not recorded every episode, see capped_cubic_video_schedule for details.
    
        # Close the env and write monitor result info to disk
        env.close()
    

    結果を確認する.

    これは、ログを記録しましたよというメッセージ.ログファイルのディレクトリ名を確認

    いま確認したログファイルのディレクトリを開いてみる

    拡張子 .stats.json のファイルを開いてみる

    episode_types, episode_length, episode_rewards などの値が確認できる.

OpenAI に付属の強化学習のサンプルプログラム cem.py を動かしてみる

  1. 次のサイトから zip 形式ファイルをダウンロードし展開(解凍)

    https://github.com/openai/gym

  2. cem.py を確認
  3. Python プログラムの実行

    Python プログラムの実行

    Python 開発環境(Jupyter Qt Console, Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, Spyder, PyCharm, PyScripterなど)も便利である.

    Python のまとめ: 別ページ »にまとめ

    python
    
    python cem.py
    

    これは強化学習のプログラムになっている