2023-01-08 Jupyter 中显示gym渲染窗口及保存为gif

最近开始尝试深度强化学习,很好的一个环境平台是Gym: https://www.gymlibrary.dev/content/basic_usage/

安装: pip install gym[all]

强化学习、深度强化学习资源:

Jupyter 中显示gym渲染窗口及保存为gif

参考:

import numpy as np
import time 
import gym
import matplotlib.pyplot as plt 
from matplotlib import animation 
%matplotlib inline
from IPython import display
# 显示gym渲染窗口的函数,在运行过程中将 env.render() 替换为 show_state(env, step, info).
def show_state(env, step=0, info=""):
    plt.figure(3)
    plt.clf()
    plt.imshow(env.render(mode='rgb_array'))
    plt.title("Step: %d %s" % (step, info))
    plt.axis('off')

    display.clear_output(wait=True)
    display.display(plt.gcf())
def display_frames_as_gif(frames, SavePath = './test.gif'):
    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=1)
    anim.save(SavePath, writer='ffmpeg', fps=30)
# 运行环境实例1

import gym

frames=[]
env = gym.make('CartPole-v1')
info = env.reset() # 重置环境 

for step in range(100):
    frames.append(env.render(mode='rgb_array')) # 加载各个时刻图像到帧
    show_state(env, step, info = 'CartPole_test') # 显示渲染窗口
    action = env.action_space.sample() # 随机动作,需要学习的动作模型
    # action=np.random.choice(2) # 随机返回: 0 小车向左,1 小车向右

    observation,reward,done,info = env.step(action) # 执行动作并返回结果

env.close()

display_frames_as_gif(frames, SavePath = './CartPole_result.gif') # 保存运行结果动图
CartPole_result.gif
# 运行环境实例2

import gym

frames=[]
env = gym.make("LunarLander-v2")
env.reset()
env.action_space.seed(42)

observation, info = env.reset(seed=42, return_info=True)

for step in range(100):
    frames.append(env.render(mode='rgb_array')) # 加载各个时刻图像到帧
    env.render(mode='human') # 这行不能和env定义写在一行,否则会报错,原因不明
    time.sleep(0.1) # 控制显示速度变慢
    show_state(env, step, info="LunarLander_test")
    observation, reward, done, info = env.step(env.action_space.sample())

    if done:
        observation, info = env.reset(return_info=True)

env.close()
display_frames_as_gif(frames, SavePath = './LunarLander_result.gif') # 保存运行结果动图
LunarLander_result.gif
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容