Korakot 的回答不正确。
您确实可以在协作中渲染 OpenAi Gym,尽管使用 matplotlib 有点慢。
方法如下:
安装 xvfb 和其他依赖项(感谢 Peter 的评论)
!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
还有pyvirtual display:
!pip install gym pyvirtualdisplay > /dev/null 2>&1
然后导入所有库,包括 matplotlib 和 ipythondisplay:
import gym
import numpy as np
import matplotlib.pyplot as plt
from IPython import display as ipythondisplay
然后您想从 pyvirtual display 导入 Display 并初始化您的屏幕尺寸,在本例中为 400x300...:
from pyvirtualdisplay import Display
display = Display(visible=0, size=(400, 300))
display.start()
最后但同样重要的是,在功能上使用gym的“rgb_array”渲染,渲染到“Screen”变量,然后使用Matplotlib绘制屏幕变量! (使用 Ipython 显示间接渲染)
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()
链接到我正在使用的 Colaboratory 笔记本演示手推车:
https://colab.research.google.com/drive/16gZuQlwxmxR5ZWYLZvBeq3bTdFfb1r_6
注意:并非所有 Gym 环境都支持“rgb_array”渲染模式,但大多数基本环境都支持。