[英]How to plot loss terms and accuracy in keras?
我嘗試繪制我的 model 的損失項,同時使用 keras。我得到了“損失”的 plot,但“val_loss”引發了關鍵字錯誤:我嘗試搜索 inte.net 並獲得此鏈接: 鏈接到上一篇文章。 但在這篇文章中,他們使用了檢查點和回調。 雖然我還沒有實現這樣的功能(它沒有包含在我正在關注的教程中)。 有人可以幫我解決這些錯誤嗎? 謝謝。
KeyError: 'val_loss'
代碼:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import math
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from keras.models import Sequential
from keras.layers import Dense, Activation, Dropout
from keras.layers import LSTM
model = Sequential()
model.add(LSTM(128, input_shape=(1, step_size)))
model.add(Dropout(0.1)) # randomly select neurons to be ignored during training.
model.add(Dense(64))
model.add(Dense(1))
model.add(Activation('linear'))
model.summary()
model.compile(loss='mean_squared_error', optimizer='adam')
history = model.fit(trainX, trainY, epochs=1000, batch_size=25, verbose=2)
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
准確性也一樣:請注意,我嘗試將關鍵字“acc”更改為“accuracy”,如前一篇文章中所述。 但是同樣的錯誤也會彈出: 鏈接
錯誤:KeyError:'acc'
acc = history.history['acc']
val_acc = history.history['val_accuracy']
plt.plot(history.history['acc'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
為了 plot 驗證數據,您需要有一個您沒有的驗證數據集。您可以使用 sklearn 的 train_test_split 創建一個驗證集。 然后在 model.fit 中確保包含 validation_data(valx, valy) 並設置驗證 batch_size。 下面的代碼使訓練和驗證 model 性能非常好 plot
import seaborn as sns
sns.set_style('darkgrid')
def tr_plot(tr_data, start_epoch):
#Plot the training and validation data
tacc=tr_data.history['accuracy']
tloss=tr_data.history['loss']
vacc=tr_data.history['val_accuracy']
vloss=tr_data.history['val_loss']
Epoch_count=len(tacc)+ start_epoch
Epochs=[]
for i in range (start_epoch ,Epoch_count):
Epochs.append(i+1)
index_loss=np.argmin(vloss)# this is the epoch with the lowest validation loss
val_lowest=vloss[index_loss]
index_acc=np.argmax(vacc)
acc_highest=vacc[index_acc]
plt.style.use('fivethirtyeight')
sc_label='best epoch= '+ str(index_loss+1 +start_epoch)
vc_label='best epoch= '+ str(index_acc + 1+ start_epoch)
fig,axes=plt.subplots(nrows=1, ncols=2, figsize=(25,10))
axes[0].plot(Epochs,tloss, 'r', label='Training loss')
axes[0].plot(Epochs,vloss,'g',label='Validation loss' )
axes[0].scatter(index_loss+1 +start_epoch,val_lowest, s=150, c= 'blue', label=sc_label)
axes[0].scatter(Epochs, tloss, s=100, c='red')
axes[0].set_title('Training and Validation Loss')
axes[0].set_xlabel('Epochs', fontsize=18)
axes[0].set_ylabel('Loss', fontsize=18)
axes[0].legend()
axes[1].plot (Epochs,tacc,'r',label= 'Training Accuracy')
axes[1].scatter(Epochs, tacc, s=100, c='red')
axes[1].plot (Epochs,vacc,'g',label= 'Validation Accuracy')
axes[1].scatter(index_acc+1 +start_epoch,acc_highest, s=150, c= 'blue', label=vc_label)
axes[1].set_title('Training and Validation Accuracy')
axes[1].set_xlabel('Epochs', fontsize=18)
axes[1].set_ylabel('Accuracy', fontsize=18)
axes[1].legend()
plt.tight_layout
plt.show()
return index_loss
loss_index=tr_plot(history,0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.