如何绘制损失条款和准确性在keras?

6jjcrrmo  于 2022-11-13  发布在  其他
关注(0)|答案(1)|浏览(151)

我试着用keras绘制模型的损失项,我得到了'loss'的图,但是'瓦尔_loss'抛出了一个关键字错误:我试着在网上搜索,得到了这个链接:link到以前的帖子。但在这篇帖子中,他们使用了检查点和回调。虽然我还没有实现这样的功能(它没有包括在我下面的教程中)。有人能帮助我绕过这些错误吗?谢谢。
关键字错误:'瓦尔_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”,就像前面的帖子里提到的那样,但是同样的错误也出现了:link
错误:键错误:'加速'

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()
8xiog9wr

8xiog9wr1#

为了绘制验证数据,您需要有一个您没有的验证数据集。您可以使用sklearn的train_test_split来创建一个验证集。然后在www.example.com中model.fit确保包含validation_data(valx,valy)并设置验证batch_size。下面的代码绘制了一个非常好的训练和验证模型性能图

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)

相关问题