题意:如何在Google Colab中渲染OpenAI Gym
问题背景:
I'm trying to use OpenAI gym in google colab. As the Notebook is running on a remote server I can not render gym's environment.
我正在尝试在Google Colab中使用OpenAI Gym。由于Notebook运行在远程服务器上,我无法渲染Gym的环境。
I found some solution for Jupyter notebook, however, these solutions do not work with colab as I don't have access to the remote server.
我发现了一些针对Jupyter notebook的解决方案,然而,这些解决方案不适用于Colab,因为我无法访问远程服务器。
I wonder if someone knows a workaround for this that works with google Colab?
我想知道是否有人知道一个适用于Google Colab的解决方案或变通方法?
问题解决:
Korakot's answer is not correct. Korakot 的回答是不正确的。
You can indeed render OpenAi Gym in colaboratory, albiet kind of slowly using none other than matplotlib.
你确实可以在Google Colab中渲染OpenAI Gym环境,尽管使用matplotlib可能会有点慢。
Heres how: 方法如下:
Install xvfb & other dependencies
安装 xvfb 及其他依赖项
!apt-get install x11-utils > /dev/null 2>&1
!pip install pyglet > /dev/null 2>&1
!apt-get install -y xvfb python-opengl > /dev/null 2>&1
As well as pyvirtual display:
以及 pyvirtualdisplay:
!pip install gym pyvirtualdisplay > /dev/null 2>&1
then import all your libraries, including matplotlib & ipythondisplay:
然后导入所有库,包括 matplotlib 和 ipythondisplay:
import gym
import numpy as np
import matplotlib.pyplot as plt
from IPython import display as ipythondisplay
then you want to import Display from pyvirtual display & initialise your screen size, in this example 400x300... :
然后你需要从 pyvirtualdisplay 导入 Display 并初始化你的屏幕尺寸,在这个例子中为 400x300...:
from pyvirtualdisplay import Display
display = Display(visible=0, size=(400, 300))
display.start()
last but not least, using gym's "rgb_array" render functionally, render to a "Screen" variable, then plot the screen variable using Matplotlib! (rendered indirectly using Ipython display)
最后但同样重要的是,使用 Gym 的 "rgb_array" 渲染函数将图像渲染到一个 "Screen" 变量中,然后使用 Matplotlib 绘制这个屏幕变量!(通过 Ipython display 间接渲染)
env = gym.make("CartPole-v0")
env.reset()
prev_screen = env.render(mode='rgb_array')
plt.imshow(prev_screen)
for i in range(50):
action = env.action_space.sample()
obs, reward, done, info = env.step(action)
screen = env.render(mode='rgb_array')
plt.imshow(screen)
ipythondisplay.clear_output(wait=True)
ipythondisplay.display(plt.gcf())
if done:
break
ipythondisplay.clear_output(wait=True)
env.close()
Link to my working Colaboratory notebook demoing cartpole:
链接到我的工作 Colaboratory 笔记本,它演示了 CartPole 环境:
https://colab.research.google.com/drive/16gZuQlwxmxR5ZWYLZvBeq3bTdFfb1r_6
Note: not all Gym Environments support "rgb_array" render mode, but most of the basic ones do.
注意:并非所有 Gym 环境都支持 "rgb_array" 渲染模式,但大多数基础环境都支持。