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

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

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

MatplotlibはPythonのおよび、NumPy用のグラフ描画ライブラリです。多くの場合、IPythonと連携して使われます。

Python

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

Q&A

解決済

1回答

5681閲覧

matplotlibのanimationで一枚ごとに違うタイトルを付けたい

tera_nsykuh

総合スコア12

Matplotlib

MatplotlibはPythonのおよび、NumPy用のグラフ描画ライブラリです。多くの場合、IPythonと連携して使われます。

Python

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

0グッド

0クリップ

投稿2018/11/20 06:50

機械学習の勉強をしています
線形回帰が進む様子をmatplotlibのanimationにしてみています.
epoch数をタイトルにいれたいのですが,表示されません.

具体的には以下のコードです.

import torch import torch.nn as nn import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib.animation import PillowWriter # hyper parameters input_size = 1 output_size = 1 num_epochs = 200 learning_rate = 0.001 # toy dataset # 15 samples, 1 features x_train = np.array([3.3, 4.4, 5.5, 6.71, 6.93, 4.168, 9.779, 6.182, 7.59, 2.167, 7.042, 10.791, 5.313, 7.997, 3.1], dtype=np.float32) y_train = np.array([1.7, 2.76, 2.09, 3.19, 1.694, 1.573, 3.366, 2.596, 2.53, 1.221, 2.827, 3.465, 1.65, 2.904, 1.3], dtype=np.float32) x_train = x_train.reshape(15,1) y_train = y_train.reshape(15,1) # linear regression model class LinearRegression(nn.Module): def __init__(self, input_size, output_size): super(LinearRegression, self).__init__() self.linear = nn.Linear(input_size, output_size) def forward(self, x): out = self.linear(x) return out model = LinearRegression(input_size, output_size) # loss and optimizer # loss function mean squared error # optimizer stochastic gradient descent criterion = nn.MSELoss() optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate) # Figure Setting fig = plt.figure() ims = [] # train the model for epoch in range(num_epochs): inputs = torch.from_numpy(x_train) targets = torch.from_numpy(y_train) optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, targets) loss.backward() optimizer.step() if (epoch + 1) % 10 == 0: print('Epoch [%d/%d], Loss: %.4f' % (epoch + 1, num_epochs, loss.item())) predicted = model(torch.from_numpy(x_train)).detach().numpy() line, = plt.plot(x_train,predicted,"skyblue") tm = plt.title("Epoch = {0}".format(epoch+1)) ims.append([line,tm]) # save the model torch.save(model.state_dict(), "model.pkl") od, = plt.plot(x_train,y_train,"ro") #plt.title("test") plt.legend([od,line],["Original Data","Fitted Line"]) ani = animation.ArtistAnimation(fig,ims,interval=50,blit=True,repeat_delay=1000) plt.show() print("Save Animation? [y/n]") should_save_animation = str(input()) if should_save_animation == "y": anim.save("anim.gif",writer="pillow")

ArtistAnimationに渡すArtistのリストに問題があると思うのですが,解決策が分かりません.
よろしくお願いいたします.

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

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

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

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

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

guest

回答1

0

ベストアンサー

FuncAnimation を使うとタイトルも動的に変更できます。

python

1import matplotlib.pyplot as plt 2import numpy as np 3from matplotlib.animation import FuncAnimation 4 5fig = plt.figure(figsize=(4, 3)) 6 7def plot(data): 8 plt.cla() 9 x = np.linspace(0, np.pi * 4, 100) 10 y = np.sin(x + data) 11 plt.plot(x, y, c='b') 12 plt.title('data={}'.format(data)) 13 14# アニメーションを作成する。 15anim = FuncAnimation(fig, plot, frames=100) 16anim.save('animation.gif', writer='imagemagick') 17 18# Figure を表示する。 19fig.show()

イメージ説明

追記

Axes.set_title() の返り値 matplotlib.text.Text を Artists として入れてもタイトルはアニメーションできないようです。
代わりに Axes.text() の返り値ならできるので、これでタイトルをアニメーションできました。

参考
matplotlib artist animation : title or text not changing

python

1# Notebook で inline 表示する場合は以下が必要 2%matplotlib nbagg 3 4#import packages 5import matplotlib.pyplot as plt 6import numpy as np 7from matplotlib.animation import ArtistAnimation 8 9x = np.linspace(0, np.pi * 4, 100) 10 11fig, ax = plt.subplots(figsize=(4, 4)) 12frames = [] # 各フレームを構成する Artist 一覧 13for delta in np.linspace(0, np.pi, 30): 14 y = np.sin(x + delta) 15 16 # 折れ線グラフを作成する。 17 lines = ax.plot(x, y, c='b') 18 title = ax.text(0.5, 1.01, 'delta={:.2f}'.format(delta), 19 ha='center', va='bottom', 20 transform=ax.transAxes, fontsize='large') 21 frames.append(lines + [title]) 22 23# アニメーションを作成する。 24anim = ArtistAnimation(fig, frames, interval=500) 25 26# gif 画像として保存する。 27anim.save('animation.gif', writer='imagemagick') 28 29# Figure を表示する。 30fig.show()

イメージ説明

投稿2018/11/20 07:16

編集2018/11/20 08:39
tiitoi

総合スコア21956

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

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

tera_nsykuh

2018/11/20 07:33

ArtistAnimationを使って,同様の変更は可能でしょうか?
tiitoi

2018/11/20 08:39 編集

追記しました。 一応できますが、title() ではなく、text() でタイトルを作成する必要があるそうです。
tera_nsykuh

2018/11/20 08:41

そもそもtitleがArtistに入らないんですね. ご回答頂いた方法を使わせて頂きます. ありがとうございました.
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問