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

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

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

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

Q&A

解決済

1回答

1964閲覧

「つくりながら学ぶ!深層強化学習」の3章P.79にて、動画の描画関数でTypeErrorが出ます。

sasakaman

総合スコア53

Python

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

0グッド

0クリップ

投稿2020/03/29 13:09

編集2020/04/09 11:19

前提・実現したいこと

「つくりながら学ぶ!深層強化学習」の3章P.79にて、動画の描画関数でTypeErrorが出ます。
本書(https://book.mynavi.jp/manatee/detail/id=88961)や参考URL(https://nbviewer.jupyter.org/github/patrickmineault/xcorr-notebooks/blob/master/Render%20OpenAI%20gym%20as%20GIF.ipynb)にも詳細な内容が書かれていないため、エラーの原因がよくわかりません。
どのようにして対処すればいいのか、ご教授いただきたいです。
よろしくお願いします。

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


TypeError Traceback (most recent call last)
<ipython-input-1-c6ee8c27c8b9> in <module>
34 observation, reward, done, info = env.step(action)
35
---> 36 display_frames_as_gif(frames)

<ipython-input-1-c6ee8c27c8b9> in display_frames_as_gif(frames)
22 anim = animation.FuncAnimation(plt.gcf(), animate, frames = len(frames), interval=50)
23 anim.save('movie_cartpole.mp4') # 追記:動画の保存です
---> 24 display(display_animation(anim, default_mode='loop'))
25
26

~\Anaconda3\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

~\Anaconda3\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

~\Anaconda3\lib\site-packages\matplotlib\animation.py in save(self, filename, writer, fps, dpi, codec, bitrate, extra_args, metadata, extra_anim, savefig_kwargs, progress_callback)
1154 progress_callback(frame_number, total_frames)
1155 frame_number += 1
-> 1156 writer.grab_frame(**savefig_kwargs)
1157
1158 # Reconnect signal for first draw if necessary

~\Anaconda3\lib\contextlib.py in exit(self, type, value, traceback)
117 if type is None:
118 try:
--> 119 next(self.gen)
120 except StopIteration:
121 return False

~\Anaconda3\lib\site-packages\matplotlib\animation.py in saving(self, fig, outfile, dpi, *args, **kwargs)
230 yield self
231 finally:
--> 232 self.finish()
233
234

~\Anaconda3\lib\site-packages\matplotlib\animation.py in finish(self)
526 # are available to be assembled.
527 self._run()
--> 528 MovieWriter.finish(self) # Will call clean-up
529
530 def cleanup(self):

~\Anaconda3\lib\site-packages\matplotlib\animation.py in finish(self)
365 def finish(self):
366 '''Finish any processing for writing the movie.'''
--> 367 self.cleanup()
368
369 def grab_frame(self, **savefig_kwargs):

~\Anaconda3\lib\site-packages\matplotlib\animation.py in cleanup(self)
529
530 def cleanup(self):
--> 531 MovieWriter.cleanup(self)
532
533 # Delete temporary files

~\Anaconda3\lib\site-packages\matplotlib\animation.py in cleanup(self)
397 self._frame_sink().close()
398 # Use the encoding/errors that universal_newlines would use.
--> 399 out = TextIOWrapper(BytesIO(out)).read()
400 err = TextIOWrapper(BytesIO(err)).read()
401 if out:

TypeError: a bytes-like object is required, not 'str'

該当のソースコード

Python

1 2import numpy as np 3import matplotlib.pyplot as plt 4%matplotlib inline 5import gym 6 7from JSAnimation.IPython_display import display_animation 8from matplotlib import animation 9from IPython.display import display 10 11def display_frames_as_gif(frames): 12 """ 13 Displays a list of frames as a gif, with controls 14 """ 15 plt.figure(figsize=(frames[0].shape[1]/72.0, frames[0].shape[0]/72.0), 16 dpi=72) 17 patch = plt.imshow(frames[0]) 18 plt.axis('off') 19 20 def animate(i): 21 patch.set_data(frames[i]) 22 23 24 anim = animation.FuncAnimation(plt.gcf(), animate, frames = len(frames), interval=50) 25 anim.save('movie_cartpole.mp4') # 追記:動画の保存です 26 display(display_animation(anim, default_mode='loop')) 27 28 29frames = [] 30env = gym.make('CartPole-v0') 31observation = env.reset() 32 33for step in range(0,200): 34 frames.append(env.render(mode='rgb_array')) 35 action = np.random.choice(2) 36 observation, reward, done, info = env.step(action) 37 38display_frames_as_gif(frames) 39

補足情報(FW/ツールのバージョンなど)

anacondaを使用
python 3.7.4
JSAnimation 0.1
ipython 7.8.0

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

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

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

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

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

nskydiving

2020/04/08 01:54

コードのインデントが崩れているので実行できません。 コードを貼るときはマークダウンの<code>タグを使用するようにしてください。
sasakaman

2020/04/09 11:19

修正しました。 ご指摘ありがとうございました。
guest

回答1

0

ベストアンサー

著者の小川です。
拙著をご利用いただき、誠にありがとうございます。

私も環境を再構築して試したところ、同じ現象を確認しました。

また、以下の問題と同様の現象ですね。
http://quabr.com:8182/59552187/matplotlib-animation-py-typeerror-a-bytes-like-object-is-required-not-str

描画ライブラリであるmatplotlibが2020年からバージョン3系になったことに起因しています。

一度、matplotlibをアンインストールし、バージョン2系をインストールすると上手くいきました。

以下試していただけますでしょうか

pip uninstall matplotlib
pip install matplotlib==2.2.5

投稿2020/04/14 10:06

編集2020/04/16 23:19
yyyyogawa

総合スコア19

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

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

sasakaman

2020/04/16 11:34

無事解決できました。 ありがとうございました。 uninstallのスペルが間違っているので、そこだけ直していただければと思います。
yyyyogawa

2020/04/16 23:20

ありがとうございます。非常に重要な質問でした。 unintallのtypoを修正しました。 重ねて御礼申し上げます。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問