티스토리 뷰

playing-openai-gym-in-jupyter-notebook

OpenAI GYM을 Jupyter notebook환경에서 실행하기 & headless playing

updated: 2018.02.19

문제

  • OpenAI GYM을 실행하려면 *.py스크립트로 만들어 실행해야하는 불편함이 있었습니다.
  • Jupyter notebook에서 실행 후, env가 종료되지않던 문제가 있었습니다.

해결법

# The typical imports
import gym
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

# Imports specifically so we can render outputs in Jupyter.
from JSAnimation.IPython_display import display_animation
from matplotlib import animation
from IPython.display import display


def display_frames_as_gif(frames):
    """
    Displays a list of frames as a gif, with controls
    """
    #plt.figure(figsize=(frames[0].shape[1] / 72.0, frames[0].shape[0] / 72.0), dpi = 72)
    patch = plt.imshow(frames[0])
    plt.axis('off')

    def animate(i):
        patch.set_data(frames[i])

    anim = animation.FuncAnimation(plt.gcf(), animate, frames = len(frames), interval=50)
    display(display_animation(anim, default_mode='loop'))

CartPole 예제

env = gym.make('CartPole-v0') # Run a demo of the environment observation = env.reset() cum_reward = 0 frames = [] for t in range(5000): # Render into buffer. frames.append(env.render(mode = 'rgb_array')) action = env.action_space.sample() observation, reward, done, info = env.step(action) if done: break env.close() display_frames_as_gif(frames)

참고 사항

OpenAI GYM Github repo 에서 발견한 이슈는 2018.01.25일자 업데이트된 사항으로 더 이상 env.render(close=True) 을 사용하지 않고 창을 닫고싶으면 env-specific method를 사용하라고 나와있었습니다.
env.env.close() 을 실행하면 창이 닫히는걸 확인할 수 있었습니다.


* 수정(180219 T 14:27) - env.env.close() 뿐 아니라 env.close()도 작동합니다.

https://github.com/openai/gym#pip-version