在keras中實現檢視其訓練loss值
阿新 • • 發佈:2020-06-17
想要檢視每次訓練模型後的 loss 值變化需要如下操作
loss_value= [ ] self.history = model.fit(state,target_f,epochs=1,batch_size =32) b = abs(float(self.history.history[‘loss'][0])) loss_value.append(b) print(loss_value) loss_value = np.array( loss_value) x = np.array(range(len( loss_value))) plt.plot(x,loss_value,c = ‘g') pt.svefit('c地址‘, dpi= 100) plt.show()
scipy.sparse 稀疏矩陣 函式集合
pandas 用於在各種檔案中提取,並處理分析資料; 有DataFrame資料結構,類似表格。
x=np.linspace(-10,10,100) 生成100個在-10到10之間的陣列
補充知識:對keras訓練過程中loss,val_loss,以及accuracy,val_accuracy的視覺化
我就廢話不多說了,大家還是直接看程式碼吧!
hist = model.fit_generator(generator=data_generator_reg(X=x_train,Y=[y_train_a,y_train_g],batch_size=batch_size),steps_per_epoch=train_num // batch_size,validation_data=(x_test,[y_test_a,y_test_g]),epochs=nb_epochs,verbose=1,workers=8,use_multiprocessing=True,callbacks=callbacks) logging.debug("Saving weights...") model.save_weights(os.path.join(db_name+"_models/"+save_name,save_name+'.h5'),overwrite=True) pd.DataFrame(hist.history).to_hdf(os.path.join(db_name+"_models/"+save_name,'history_'+save_name+'.h5'),"history")
在訓練時,會輸出如下列印:
640/640 [==============================] - 35s 55ms/step - loss: 4.0216 - mean_absolute_error: 4.6525 - val_loss: 3.2888 - val_mean_absolute_error: 3.9109
有訓練loss,訓練預測準確度,以及測試loss,以及測試準確度,將檔案儲存後,使用下面的程式碼可以對訓練以及評估進行視覺化,下面有對應的引數名稱:
loss,mean_absolute_error,val_loss,val_mean_absolute_error
import pandas as pd import matplotlib.pyplot as plt import argparse import os import numpy as np def get_args(): parser = argparse.ArgumentParser(description="This script shows training graph from history file.") parser.add_argument("--input","-i",type=str,required=True,help="path to input history h5 file") args = parser.parse_args() return args def main(): args = get_args() input_path = args.input df = pd.read_hdf(input_path,"history") print(np.min(df['val_mean_absolute_error'])) input_dir = os.path.dirname(input_path) plt.plot(df["loss"],'-o',label="loss (age)",linewidth=2.0) plt.plot(df["val_loss"],label="val_loss (age)",linewidth=2.0) plt.xlabel("Number of epochs",fontsize=20) plt.ylabel("Loss",fontsize=20) plt.legend() plt.grid() plt.savefig(os.path.join(input_dir,"loss.pdf"),bbox_inches='tight',pad_inches=0) plt.cla() plt.plot(df["mean_absolute_error"],label="training",linewidth=2.0) plt.plot(df["val_mean_absolute_error"],label="validation",linewidth=2.0) ax = plt.gca() ax.set_ylim([2,13]) ax.set_aspect(0.6/ax.get_data_ratio()) plt.xticks(fontsize=20) plt.yticks(fontsize=20) plt.xlabel("Number of epochs",fontsize=20) plt.ylabel("Mean absolute error",fontsize=20) plt.legend(fontsize=20) plt.grid() plt.savefig(os.path.join(input_dir,"performance.pdf"),pad_inches=0) if __name__ == '__main__': main()
以上這篇在keras中實現檢視其訓練loss值就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。