keras 如何儲存最佳的訓練模型
阿新 • • 發佈:2020-05-25
1、只儲存最佳的訓練模型
2、儲存有所有有提升的模型
3、載入模型
4、引數說明
只儲存最佳的訓練模型
from keras.callbacks import ModelCheckpoint filepath='weights.best.hdf5' # 有一次提升,則覆蓋一次. checkpoint = ModelCheckpoint(filepath,monitor='val_acc',verbose=1,save_best_only=True,mode='max',period=2) callbacks_list = [checkpoint] model.compile(loss='categorical_crossentropy',optimizer=optimizers.Adam(lr=2e-6,decay=1e-7),metrics=['acc']) history1 = model.fit_generator( train_generator,steps_per_epoch=100,epochs=40,validation_data=validation_generator,validation_steps=100,callbacks=callbacks_list)
輸出的部分結果為:
Epoch 2/40 100/100 [==============================] - 24s 241ms/step - loss: 0.2715 - acc: 0.9380 - val_loss: 0.1635 - val_acc: 0.9600 Epoch 00002: val_acc improved from -inf to 0.96000,saving model to weights.best.hdf5 Epoch 3/40 100/100 [==============================] - 24s 240ms/step - loss: 0.1623 - acc: 0.9575 - val_loss: 0.1116 - val_acc: 0.9730 Epoch 4/40 100/100 [==============================] - 24s 242ms/step - loss: 0.1143 - acc: 0.9730 - val_loss: 0.0799 - val_acc: 0.9840 Epoch 00004: val_acc improved from 0.96000 to 0.98400,saving model to weights.best.hdf5
儲存所有有提升的模型
from keras.callbacks import ModelCheckpoint # checkpoint filepath = "weights-improvement-{epoch:02d}-{val_acc:.2f}.hdf5" # 中途訓練效果提升,則將檔案儲存,每提升一次,儲存一次 checkpoint = ModelCheckpoint(filepath,mode='max') callbacks_list = [checkpoint] model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy']) history1 = model.fit_generator( train_generator,callbacks=callbacks_list)
因為我只想要最佳的模型,所以沒有嘗試儲存所有有提升的模型,結果是什麼樣自己試。。。
載入最佳的模型
# load weights 載入模型權重 model.load_weights('weights.best.hdf5') #如果想載入模型,則將model.load_weights('weights.best.hdf5')改為 #model.load_model('weights.best.hdf5') # compile 編譯 model.compile(loss='categorical_crossentropy',metrics=['accuracy']) print('Created model and loaded weights from hdf5 file') # estimate scores = model.evaluate(validation_generator,steps=30, verbose=0) print("{0}: {1:.2f}%".format(model.metrics_names[1],scores[1]*100)) ModelCheckpoint引數說明 keras.callbacks.ModelCheckpoint(filepath,monitor='val_loss',verbose=0,save_best_only=False,save_weights_only=False,mode='auto',period=1)
filename:字串,儲存模型的路徑
monitor:需要監視的值
verbose:資訊展示模式,0或1(checkpoint的儲存資訊,類似Epoch 00001: saving model to ...)
(verbose = 0 為不在標準輸出流輸出日誌資訊;verbose = 1 為輸出進度條記錄;verbose = 2 為每個epoch輸出一行記錄)
save_best_only:當設定為True時,監測值有改進時才會儲存當前的模型( the latest best model according to the quantity monitored will not be overwritten)
mode:‘auto',‘min',‘max'之一,在save_best_only=True時決定效能最佳模型的評判準則,例如,當監測值為val_acc時,模式應為max,當監測值為val_loss時,模式應為min。在auto模式下,評價準則由被監測值的名字自動推斷。
save_weights_only:若設定為True,則只儲存模型權重,否則將儲存整個模型(包括模型結構,配置資訊等)
period:CheckPoint之間的間隔的epoch數
以上這篇keras 如何儲存最佳的訓練模型就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。