質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
OpenAI Gym

OpenAI Gymは、強化学習を開発・強化するためのシミュレーション環境です。強化学習における実験や評価環境などを標準化し提供することを目的としています。さらに、結果をアップロードしたり、他の人の実行結果や実装を見ることも可能です。

強化学習

強化学習とは、ある環境下のエージェントが現状を推測し行動を決定することで報酬を獲得するという見解から、その報酬を最大限に得る方策を学ぶ機械学習のことを指します。問題解決時に得る報酬が選択結果によって変化することで、より良い行動を選択しようと学習する点が特徴です。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

1回答

2489閲覧

OpenAi gymの実行アニメーションを保存したい

pypyson

総合スコア4

OpenAI Gym

OpenAI Gymは、強化学習を開発・強化するためのシミュレーション環境です。強化学習における実験や評価環境などを標準化し提供することを目的としています。さらに、結果をアップロードしたり、他の人の実行結果や実装を見ることも可能です。

強化学習

強化学習とは、ある環境下のエージェントが現状を推測し行動を決定することで報酬を獲得するという見解から、その報酬を最大限に得る方策を学ぶ機械学習のことを指します。問題解決時に得る報酬が選択結果によって変化することで、より良い行動を選択しようと学習する点が特徴です。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2020/05/19 08:20

前提・実現したいこと

OpenAi gymの実行アニメーションを保存したいのですが、
プログラム実行時にエラーが発生し、なにも映像が表示されないmp4ファイルが生成されてしまう。

つくりながら学ぶ!深層強化学習を参考に強化学習の勉強をしているのですが、上記の内容で躓いています。
どなたかお力を貸していただけないでしょうか。
下記は著者様の元記事
https://book.mynavi.jp/manatee/detail/id=88961

Anacondaにて環境を構築し、以下は手動にて追加したパッケージ。

gym==0.9.7
matplotlib
JSAnimation
pyglet==1.2.4
conda install -c conda-forge ffmpeg

使用言語、Python3

問題解決法をご存じであれば、ご教授のほど宜しくお願い致します。

発生している問題・エラーメッセージ

AttributeError Traceback (most recent call last) <ipython-input-5-2d605f8148aa> in <module> 1 # 動画を保存と描画 ----> 2 display_frames_as_gif(frames) <ipython-input-3-9d95926f2835> in display_frames_as_gif(frames) 22 23 anim.save('movie_cartpole.mp4') # 追記:動画の保存です ---> 24 display(display_animation(anim, default_mode='loop')) E:\Anaconda3\envs\rl_env2\lib\site-packages\JSAnimation\IPython_display.py in display_animation(anim, **kwargs) 84 """Display the animation with an IPython HTML object""" 85 from IPython.display import HTML ---> 86 return HTML(anim_to_html(anim, **kwargs)) 87 88 E:\Anaconda3\envs\rl_env2\lib\site-packages\JSAnimation\IPython_display.py in anim_to_html(anim, fps, embed_frames, default_mode) 74 anim.save(f.name, writer=HTMLWriter(fps=fps, 75 embed_frames=embed_frames, ---> 76 default_mode=default_mode)) 77 html = open(f.name).read() 78 E:\Anaconda3\envs\rl_env2\lib\site-packages\matplotlib\animation.py in save(self, filename, writer, fps, dpi, codec, bitrate, extra_args, metadata, extra_anim, savefig_kwargs, progress_callback) 1150 progress_callback(frame_number, total_frames) 1151 frame_number += 1 -> 1152 writer.grab_frame(**savefig_kwargs) 1153 1154 # Reconnect signal for first draw if necessary E:\Anaconda3\envs\rl_env2\lib\contextlib.py in __exit__(self, type, value, traceback) 86 if type is None: 87 try: ---> 88 next(self.gen) 89 except StopIteration: 90 return False E:\Anaconda3\envs\rl_env2\lib\site-packages\matplotlib\animation.py in saving(self, fig, outfile, dpi, *args, **kwargs) 230 yield self 231 finally: --> 232 self.finish() 233 234 E:\Anaconda3\envs\rl_env2\lib\site-packages\matplotlib\animation.py in finish(self) 526 # Call run here now that all frame grabbing is done. All temp files 527 # are available to be assembled. --> 528 self._run() 529 MovieWriter.finish(self) # Will call clean-up 530 E:\Anaconda3\envs\rl_env2\lib\site-packages\JSAnimation\html_writer.py in _run(self) 321 of.write(JS_INCLUDE) 322 of.write(DISPLAY_TEMPLATE.format(id=self.new_id(), --> 323 Nframes=len(self._temp_names), 324 fill_frames=fill_frames, 325 interval=interval, AttributeError: 'HTMLWriter' object has no attribute '_temp_names'

該当のソースコード

python

1# 使用するパッケージの宣言 2import numpy as np 3import matplotlib.pyplot as plt 4%matplotlib inline 5import gym 6 7# 動画の描画関数の宣言 8# 参考URL http://nbviewer.jupyter.org/github/patrickmineault/xcorr-notebooks/blob/master/Render%20OpenAI%20gym%20as%20GIF.ipynb 9from JSAnimation.IPython_display import display_animation 10from matplotlib import animation 11from IPython.display import display 12 13 14def display_frames_as_gif(frames): 15 """ 16 Displays a list of frames as a gif, with controls 17 """ 18 plt.figure(figsize=(frames[0].shape[1]/72.0, frames[0].shape[0]/72.0), 19 dpi=72) 20 patch = plt.imshow(frames[0]) 21 plt.axis('off') 22 23 def animate(i): 24 patch.set_data(frames[i]) 25 26 anim = animation.FuncAnimation(plt.gcf(), animate, frames=len(frames), 27 interval=50) 28 29 anim.save('movie_cartpole.mp4') # 追記:動画の保存です 30 display(display_animation(anim, default_mode='loop')) 31 32# CartPoleをランダムに動かす 33 34frames = [] 35env = gym.make('CartPole-v0') 36observation = env.reset() # 最初に環境のresetが必要 37 38for step in range(0, 200): 39 frames.append(env.render(mode='rgb_array')) # framesに各時刻の画像を追加していく 40 action = np.random.choice(2) # 0(カートを左に押す), 1(カートを右に押す)をランダムに返す 41 observation, reward, done, info = env.step(action) # actionを実行する 42 43# 注意:実行後にipykernel_launcher.p...というindowが開いて固まりますが放置しておいてください 44 45# 動画を保存と描画 46display_frames_as_gif(frames)

試したこと

カーネルの更新

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

Solution 1

The first solution is a hack. You just need to make JSAnimation package compatible with the newer versions of matplotlib. And it's much easier than you might expect.

Find the JSAnimation package in your Anaconda installation. For the case of the base environment it might be:

C:\ProgramData\Anaconda3\Lib\site-packages\JSAnimation

For other environments it will be something like:

C:\ProgramData\Anaconda3\envs\your_env_name\Lib\site-packages\JSAnimation

Open html_writer.py file with Notepad++ or any other text editor, but not with PyCharm, as it will not allow you to modify a library file.

The only things you need to change are:

  • Change self._temp_names to self._temp_paths.

  • Change return ('', '') to return (''.encode('utf-8'), ''.encode('utf-8')) to return a tuple of byte arrays instead of strings.

Save the file (you will need admin privileges), run the Jupyter. It should work now. It worked for me.

For convenience here's code of the _run method in html_writer.py after changes:

def _run(self): # make a ducktyped subprocess standin # this is called by the MovieWriter base class, but not used here. class ProcessStandin(object): returncode = 0 def communicate(self): return (''.encode('utf-8'), ''.encode('utf-8')) self._proc = ProcessStandin() # save the frames to an html file if self.embed_frames: fill_frames = _embedded_frames(self._saved_frames, self.frame_format) else: # temp names is filled by FileMovieWriter fill_frames = _included_frames(self._temp_paths, self.frame_format) mode_dict = dict(once_checked='', loop_checked='', reflect_checked='') mode_dict[self.default_mode + '_checked'] = 'checked' interval = int(1000. / self.fps) with open(self.outfile, 'w') as of: of.write(JS_INCLUDE) of.write(DISPLAY_TEMPLATE.format(id=self.new_id(), Nframes=len(self._temp_paths), fill_frames=fill_frames, interval=interval, icons=_Icons(), **mode_dict))

Solution 2

This is a cleaner solution. As JSAnimation was merged into newer matplotlib it is better to use the integrated version. The solution is as follows:

  1. Open pong_utils.py.

  2. Find animate_frames method.

  3. Just before this method add:

def display_animation(anim): plt.close(anim._fig) return HTML(anim.to_jshtml())
  1. Change
display(display_animation(fanim, default_mode='once'))

to

display(display_animation(fanim))
  1. You can remove the import:
from JSAnimation.IPython_display import display_animation

That's it.

投稿2021/02/14 11:12

PiotrZiolo

総合スコア10

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問