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

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

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

Kerasは、TheanoやTensorFlow/CNTK対応のラッパーライブラリです。DeepLearningの数学的部分を短いコードでネットワークとして表現することが可能。DeepLearningの最新手法を迅速に試すことができます。

Python

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

Q&A

解決済

1回答

3182閲覧

Keras グラフ表示について

22Go

総合スコア55

Keras

Kerasは、TheanoやTensorFlow/CNTK対応のラッパーライブラリです。DeepLearningの数学的部分を短いコードでネットワークとして表現することが可能。DeepLearningの最新手法を迅速に試すことができます。

Python

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

0グッド

1クリップ

投稿2019/08/12 13:06

下記のように学習をしています

python

1# coding:utf-8 2import keras 3from keras.utils import np_utils 4from keras.layers.convolutional import Conv2D, MaxPooling2D 5from keras.models import Sequential 6from keras.layers.core import Dense, Dropout, Activation, Flatten 7from keras.preprocessing.image import array_to_img, img_to_array, list_pictures, load_img 8import numpy as np 9import pandas as pd 10import matplotlib.pyplot as plt 11import seaborn as sns 12from sklearn.metrics import confusion_matrix 13from sklearn.neighbors import KNeighborsClassifier 14from sklearn.model_selection import train_test_split 15 16X = []#train 17Y = [] 18A = []#validation 19B = [] 20V = []#test 21W = [] 22 23ep = 10 24size = 10,10 25 26 27 28# aの画像 29for picture in list_pictures('dir/train/a'): 30 img = img_to_array(load_img(picture, target_size=(size))) 31 X.append(img) 32 Y.append(0) 33 34for picture in list_pictures('dir/vali/a'): 35 img = img_to_array(load_img(picture, target_size=(size))) 36 A.append(img) 37 B.append(0) 38 39for picture in list_pictures('dir/test/a'): 40 img = img_to_array(load_img(picture, target_size=(size))) 41 V.append(img) 42 W.append(0) 43 44# bの画像 45for picture in list_pictures('dir/train/b'): 46 img = img_to_array(load_img(picture, target_size=(size))) 47 X.append(img) 48 Y.append(1) 49 50for picture in list_pictures('dir/vali/b'): 51 img = img_to_array(load_img(picture, target_size=(size))) 52 A.append(img) 53 B.append(1) 54 55for picture in list_pictures('dir/test/b'): 56 img = img_to_array(load_img(picture, target_size=(size))) 57 V.append(img) 58 W.append(1) 59 60# cの画像 61for picture in list_pictures('dir/train/c'): 62 img = img_to_array(load_img(picture, target_size=(size))) 63 X.append(img) 64 Y.append(2) 65 66for picture in list_pictures('dir/train/c'): 67 img = img_to_array(load_img(picture, target_size=(size))) 68 A.append(img) 69 B.append(2) 70 71for picture in list_pictures('dir/train/c'): 72 img = img_to_array(load_img(picture, target_size=(size))) 73 V.append(img) 74 W.append(2) 75 76X = np.asarray(X) 77Y = np.asarray(Y) 78A = np.asarray(A) 79B = np.asarray(B) 80V = np.asarray(V) 81W = np.asarray(W) 82 83# 画素値を0から1の範囲に変換 84X = X.astype('float32') 85X = X / 255.0 86A = A.astype('float32') 87A = A / 255.0 88V = V.astype('float32') 89V = V / 255.0 90 91# クラスの形式を変換 92Y = np_utils.to_categorical(Y, 3)#(ベクトル変換したいラベル、配列数) 93B = np_utils.to_categorical(B, 3) 94W = np_utils.to_categorical(W, 3) 95 96X_train, Y_train = (X, Y) 97A_vali, B_vali = (A, B) 98V_test, W_test = (V, W) 99 100# 【CNNを構築】 101model = Sequential() 102model.add(Conv2D(32, (3, 3), padding='same', 103 input_shape=X_train.shape[1:])) 104model.add(Activation('relu')) 105model.add(Conv2D(32, (3, 3))) 106model.add(Activation('relu')) 107model.add(MaxPooling2D(pool_size=(2, 2))) 108model.add(Dropout(0.4)) 109model.add(Conv2D(64, (3, 3), padding='same')) 110model.add(Activation('relu')) 111model.add(Conv2D(64, (3, 3))) 112model.add(Activation('relu')) 113model.add(MaxPooling2D(pool_size=(2, 2))) 114model.add(Dropout(0.4)) 115model.add(Flatten()) 116model.add(Dense(512)) 117model.add(Activation('relu')) 118model.add(Dropout(0.4)) 119model.add(Dense(3))#カテゴリー数 120model.add(Activation('softmax')) 121 122# 【コンパイル】 123model.compile(loss='categorical_crossentropy',#損失関数 124 optimizer='adam',#最適化、オブジェクト 125 metrics=['accuracy'])#評価関数、正解率 126 127#【学習実行】 128history = model.fit(X_train, Y_train, batch_size=2048, epochs=ep, 129 validation_data = (A_vali, B_vali), verbose = 1) 130 131score = model.evaluate(V_test, W_test, verbose = 1) 132print("test_acc", score[1], "test_loss", score[0])

以下のようにグラフで学習過程とheatmapを作成し、その後にデスクトップに保存したいのです

python

1%matplotlib inline 2plt.plot(history.history['acc'], "o-") 3plt.plot(history.history['val_acc'], "o-") 4plt.xlabel('epoch') 5plt.ylabel('accuracy') 6plt.title('model accuracy') 7plt.legend(['train', 'validation'], loc='upper left') 8plt.savefig('Desktop/result/acc.png') 9plt.show() 10plt.plot(history.history['loss'], "o-") 11plt.plot(history.history['val_loss'], "o-") 12plt.xlabel('epoch') 13plt.ylabel('loss') 14plt.title('model loss') 15 16plt.legend(['loss', 'val_loss'], loc='upper left') 17plt.savefig('Desktop/result/loss.png') 18plt.show() 19 20predict_classes = model.predict_classes(V_test) 21true_classes = np.argmax(W_test, 1) 22cmx = confusion_matrix(true_classes, predict_classes, ) 23df = pd.DataFrame(data=cmx, index=["a","b","c"] 24 columns=[""a","b", "c"]) 25 26sns.heatmap(df, annot=True, fmt='g', square=True) 27plt.xlabel('predict') 28plt.ylabel('true') 29plt.savefig('Desktop/result/heatmap.png') 30plt.show()

現在はaccとlossのグラフを別々で保存しているのですが、隣に並べて1枚の画像として保存することは可能でしょうか?

また、heatmapの画像ですが、jupyternotebook上ではindexとcolumnsが全て見えるのですが、保存した画像を見ると下の方が切れています。どのように変更したらいいのか教えていだたきたいです。

宜しくお願い致します。

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

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

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

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

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

guest

回答1

0

ベストアンサー

現在はaccとlossのグラフを別々で保存しているのですが、隣に並べて1枚の画像として保存することは可能でしょうか?

matplotlib では1つの図に複数のグラフを追加できます。
具体的には以下のようにすればよいです。

参考記事

python

1epochs = np.arange(1, ep + 1) 2 3fig, [ax1, ax2] = plt.subplots(1, 2, figsize=(10, 4)) 4 5# 損失関数の履歴を可視化する。 6ax1.plot(epochs, history.history["loss"], label="loss") 7ax1.plot(epochs, history.history["val_loss"], label="validation loss") 8ax1.set_xlabel("epochs") 9ax1.legend() 10 11# 精度の履歴を可視化する。 12ax2.plot(epochs, history.history["acc"], label="accuracy") 13ax2.plot(epochs, history.history["val_acc"], label="validation accuracy") 14ax2.set_xlabel("epochs") 15ax2.legend() 16 17plt.show()

イメージ説明

また、heatmapの画像ですが、jupyternotebook上ではindexとcolumnsが全て見えるのですが、保存した画像を見ると下の方が切れています。どのように変更したらいいのか教えていだたきたいです。

Heatmaps are being truncated when using with seaborn · Issue #14675 · matplotlib/matplotlib

seaborn のバグなので、古いバージョンを使うか、バグが修正されるのを待つしかありません。

類似質問

Python 3.x - Python3 seaborn heatmap表示時|teratail

投稿2019/08/12 16:20

tiitoi

総合スコア21956

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

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

22Go

2019/08/12 18:37

大変参考になりました。ありがとうございます!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問