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

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

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

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

Matplotlib

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

機械学習

機械学習は、データからパターンを自動的に発見し、そこから知能的な判断を下すためのコンピューターアルゴリズムを指します。人工知能における課題のひとつです。

Python

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

Q&A

解決済

1回答

417閲覧

機械学習の学習過程をmatplotlibで図示したい

yu__ya

総合スコア6

Keras

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

Matplotlib

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

機械学習

機械学習は、データからパターンを自動的に発見し、そこから知能的な判断を下すためのコンピューターアルゴリズムを指します。人工知能における課題のひとつです。

Python

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

0グッド

1クリップ

投稿2019/10/11 08:00

python

1import numpy as np 2import pandas as pd 3 4import matplotlib.pyplot as plt 5 6pd.options.display.max_rows = 8 7state = np.random.RandomState(1) 8# csv からデータ読み込み 9names = ['Hue', 'Hue_figures', 'Value', 'Chroma','season'] 10coloer = pd.read_csv('personal_coloer_data2.csv', header=None, names=names) 11df=coloer 12label=df[['season']] 13data=df[['Hue', 'Hue_figures', 'Value', 'Chroma']] 14 15X=data 16T=label 17 18 19#訓練データとテストデータに分割 20from sklearn.model_selection import StratifiedKFold 21 22 23skf = StratifiedKFold(n_splits=6) 24for train_index, test_index in skf.split(X,T): 25 print("train_index:", train_index, "test_index:", test_index) 26 X_train=X.values[train_index] 27 T_train=T.values[train_index] 28 X_test=X.values[test_index] 29 T_test=T.values[test_index] 30 T_train=np.ravel(T_train) 31 T_test=np.ravel(T_test) 32 T_train_array=np.identity(4)[T_train] 33 T_test_array=np.identity(4)[T_test] 34 35 epochs=10 36 batch_size=120 37 38 #モデル作成 39 from keras.models import Sequential 40 from keras.layers import Dense, Activation 41 from keras.optimizers import SGD 42 43 model = Sequential() 44#入力が4つの特徴、4つのラベルに分類なので出力ユニット4 45 model.add(Dense(input_dim=4, units=4)) 46 model.add(Activation('softmax')) 47 model.compile(loss='categorical_crossentropy', optimizer=SGD(lr=0.1),metrics=['accuracy']) 48 49#トレーニング 50 history=model.fit(X_train, T_train_array, epochs=epochs, batch_size=batch_size,validation_data=(X_test, T_test_array)) 51 52#学習済みモデルでデータ分類 53Y = model.predict_classes(X_test, batch_size=batch_size,) 54 55 56plt.plot(range(1, epochs+1), Y.history['acc'], label="training") 57plt.plot(range(1, epochs+1), Y.history['val_acc'], label="validation") 58plt.xlabel('Epochs') 59plt.ylabel('Accuracy') 60plt.legend() 61plt.show() 62 63#結果検証 64_, T_index = np.where(T_test_array > 0) # to_categorical の逆変換 65print() 66print('RESULT') 67print(Y == T_index) 68

#エラーコード
'numpy.ndarray' object has no attribute 'history'

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

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

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

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

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

guest

回答1

0

ベストアンサー

学習過程のデータが格納されているのは
model.predict_classes() の戻り値(Y)ではなく、model.fit() の戻り値(history)ではないでしょうか?

ですので

Python

1plt.plot(range(1, epochs+1), Y.history['acc'], label="training") 2plt.plot(range(1, epochs+1), Y.history['val_acc'], label="validation")

の部分は

Python

1plt.plot(range(1, epochs+1), history.history['acc'], label="training") 2plt.plot(range(1, epochs+1), history.history['val_acc'], label="validation")

となるかと思います。


ただ個人的には、KFoldにて6回学習を繰り返しているにも関わらず、変数historyを毎回上書きしているため、最後の1回のみしか表示することができないのが気になります。

これを解決するためには

Python

1historys = [] 2skf = StratifiedKFold(n_splits=6) 3for train_index, test_index in skf.split(X,T): 4 print("train_index:", train_index, "test_index:", test_index) 5 # (略) 6 #トレーニング 7 history=model.fit(X_train, T_train_array, epochs=epochs, batch_size=batch_size,validation_data=(X_test, T_test_array)) 8 historys.append(history)

のようにfit()の戻り値(history)をリストに格納し

fig, ax = plt.subplots(2, 6, figsize=(24,8)) for i, hist in enumerate(historys): ax[0,i].plot(hist.history['loss'], 'r-', label='Train') ax[0,i].plot(hist.history['val_loss'], 'b-', label='Valid') ax[0,i].legend() ax[1,i].plot(hist.history['acc'], 'r-', label='Train') ax[1,i].plot(hist.history['val_acc'], 'b-', label='Valid') ax[1,i].legend() plt.show()

のようにして6回分まとめて表示すると良いのではないでしょうか

投稿2019/10/11 09:32

magichan

総合スコア15898

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

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

yu__ya

2019/10/25 08:34

ありがとうございます。グラフの目盛りを揃えたいのですが、どのようにしたらよいでしょうか・・・
magichan

2019/10/25 08:52

ループ内に ax[0,i].set_ylim(0,100) # 範囲は適当 のように記述して、グラフの Y軸の範囲を設定するとよいかと思います。
yu__ya

2019/10/25 08:58

ありがとうございます!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問