keras 回調(diào)函數(shù)Callbacks 斷點(diǎn)ModelCheckpoint教程
整理自keras:https://keras-cn.readthedocs.io/en/latest/other/callbacks/
回調(diào)函數(shù)Callbacks
回調(diào)函數(shù)是一個(gè)函數(shù)的合集,會(huì)在訓(xùn)練的階段中所使用。你可以使用回調(diào)函數(shù)來查看訓(xùn)練模型的內(nèi)在狀態(tài)和統(tǒng)計(jì)。你可以傳遞一個(gè)列表的回調(diào)函數(shù)(作為 callbacks 關(guān)鍵字參數(shù))到 Sequential 或 Model 類型的 .fit() 方法。在訓(xùn)練時(shí),相應(yīng)的回調(diào)函數(shù)的方法就會(huì)被在各自的階段被調(diào)用。
Callback
keras.callbacks.Callback()
這是回調(diào)函數(shù)的抽象類,定義新的回調(diào)函數(shù)必須繼承自該類
類屬性
params:字典,訓(xùn)練參數(shù)集(如信息顯示方法verbosity,batch大小,epoch數(shù))
model:keras.models.Model對(duì)象,為正在訓(xùn)練的模型的引用
回調(diào)函數(shù)以字典logs為參數(shù),該字典包含了一系列與當(dāng)前batch或epoch相關(guān)的信息。
目前,模型的.fit()中有下列參數(shù)會(huì)被記錄到logs中:
在每個(gè)epoch的結(jié)尾處(on_epoch_end),logs將包含訓(xùn)練的正確率和誤差,acc和loss,如果指定了驗(yàn)證集,還會(huì)包含驗(yàn)證集正確率和誤差val_acc)和val_loss,val_acc還額外需要在.compile中啟用metrics=['accuracy']。
在每個(gè)batch的開始處(on_batch_begin):logs包含size,即當(dāng)前batch的樣本數(shù)
在每個(gè)batch的結(jié)尾處(on_batch_end):logs包含loss,若啟用accuracy則還包含acc
ModelCheckpoint
keras.callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=0, save_best_only=False, save_weights_only=False, mode='auto', period=1)
該回調(diào)函數(shù)將在每個(gè)epoch后保存模型到filepath
filepath 可以包括命名格式選項(xiàng),可以由 epoch 的值和 logs 的鍵(由 on_epoch_end 參數(shù)傳遞)來填充。
參數(shù):
filepath: 字符串,保存模型的路徑。
monitor: 被監(jiān)測(cè)的數(shù)據(jù)。val_acc或這val_loss
verbose: 詳細(xì)信息模式,0 或者 1 。0為不打印輸出信息,1打印
save_best_only: 如果 save_best_only=True, 將只保存在驗(yàn)證集上性能最好的模型
mode: {auto, min, max} 的其中之一。 如果 save_best_only=True,那么是否覆蓋保存文件的決定就取決于被監(jiān)測(cè)數(shù)據(jù)的最大或者最小值。 對(duì)于 val_acc,模式就會(huì)是 max,而對(duì)于 val_loss,模式就需要是 min,等等。 在 auto 模式中,方向會(huì)自動(dòng)從被監(jiān)測(cè)的數(shù)據(jù)的名字中判斷出來。
save_weights_only: 如果 True,那么只有模型的權(quán)重會(huì)被保存 (model.save_weights(filepath)), 否則的話,整個(gè)模型會(huì)被保存 (model.save(filepath))。
period: 每個(gè)檢查點(diǎn)之間的間隔(訓(xùn)練輪數(shù))。
代碼實(shí)現(xiàn)過程:
① 從keras.callbacks導(dǎo)入ModelCheckpoint類
from keras.callbacks import ModelCheckpoint
② 在訓(xùn)練階段的model.compile之后加入下列代碼實(shí)現(xiàn)每一次epoch(period=1)保存最好的參數(shù)
checkpoint = ModelCheckpoint(filepath,
monitor='val_loss', save_weights_only=True,verbose=1,save_best_only=True, period=1)
③ 在訓(xùn)練階段的model.fit之前加載先前保存的參數(shù)
if os.path.exists(filepath): model.load_weights(filepath) # 若成功加載前面保存的參數(shù),輸出下列信息 print("checkpoint_loaded")
④ 在model.fit添加callbacks=[checkpoint]實(shí)現(xiàn)回調(diào)
model.fit_generator(data_generator_wrap(lines[:num_train], batch_size, input_shape, anchors, num_classes), steps_per_epoch=max(1, num_train//batch_size), validation_data=data_generator_wrap(lines[num_train:], batch_size, input_shape, anchors, num_classes), validation_steps=max(1, num_val//batch_size), epochs=3, initial_epoch=0, callbacks=[checkpoint])
補(bǔ)充知識(shí):keras之多輸入多輸出(多任務(wù))模型
keras多輸入多輸出模型,以keras官網(wǎng)的demo為例,分析keras多輸入多輸出的適用。
主要輸入(main_input): 新聞標(biāo)題本身,即一系列詞語。
輔助輸入(aux_input): 接受額外的數(shù)據(jù),例如新聞標(biāo)題的發(fā)布時(shí)間等。
該模型將通過兩個(gè)損失函數(shù)進(jìn)行監(jiān)督學(xué)習(xí)。
較早地在模型中使用主損失函數(shù),是深度學(xué)習(xí)模型的一個(gè)良好正則方法。
完整過程圖示如下:
其中,紅圈中的操作為將輔助數(shù)據(jù)與LSTM層的輸出連接起來,輸入到模型中。
代碼實(shí)現(xiàn):
import keras from keras.layers import Input, Embedding, LSTM, Dense from keras.models import Model # 定義網(wǎng)絡(luò)模型 # 標(biāo)題輸入:接收一個(gè)含有 100 個(gè)整數(shù)的序列,每個(gè)整數(shù)在 1 到 10000 之間 # 注意我們可以通過傳遞一個(gè) `name` 參數(shù)來命名任何層 main_input = Input(shape=(100,), dtype='int32', name='main_input') # Embedding 層將輸入序列編碼為一個(gè)稠密向量的序列,每個(gè)向量維度為 512 x = Embedding(output_dim=512, input_dim=10000, input_length=100)(main_input) # LSTM 層把向量序列轉(zhuǎn)換成單個(gè)向量,它包含整個(gè)序列的上下文信息 lstm_out = LSTM(32)(x) # 在這里我們添加輔助損失,使得即使在模型主損失很高的情況下,LSTM層和Embedding層都能被平穩(wěn)地訓(xùn)練 auxiliary_output = Dense(1, activation='sigmoid', name='aux_output')(lstm_out) # 此時(shí),我們將輔助輸入數(shù)據(jù)與LSTM層的輸出連接起來,輸入到模型中 auxiliary_input = Input(shape=(5,), name='aux_input') x = keras.layers.concatenate([lstm_out, auxiliary_output]) # 再添加剩余的層 # 堆疊多個(gè)全連接網(wǎng)絡(luò)層 x = Dense(64, activation='relu')(x) x = Dense(64, activation='relu')(x) x = Dense(64, activation='relu')(x) # 最后添加主要的邏輯回歸層 main_output = Dense(1, activation='sigmoid', name='main_output')(x) # 定義這個(gè)具有兩個(gè)輸入和輸出的模型 model = Model(inputs=[main_input, auxiliary_input], outputs=[main_output, auxiliary_output]) # 編譯模型時(shí)候分配損失函數(shù)權(quán)重:編譯模型的時(shí)候,給 輔助損失 分配一個(gè)0.2的權(quán)重 model.compile(optimizer='rmsprop', loss='binary_crossentropy', loss_weights=[1., 0.2]) # 訓(xùn)練模型:我們可以通過傳遞輸入數(shù)組和目標(biāo)數(shù)組的列表來訓(xùn)練模型 model.fit([headline_data, additional_data], [labels, labels], epochs=50, batch_size=32) # 另外一種利用字典的編譯、訓(xùn)練方式 # 由于輸入和輸出均被命名了(在定義時(shí)傳遞了一個(gè) name 參數(shù)),我們也可以通過以下方式編譯模型 model.compile(optimizer='rmsprop', loss={'main_output': 'binary_crossentropy', 'aux_output': 'binary_crossentropy'}, loss_weights={'main_output': 1., 'aux_output': 0.2}) # 然后使用以下方式訓(xùn)練: model.fit({'main_input': headline_data, 'aux_input': additional_data}, {'main_output': labels, 'aux_output': labels}, epochs=50, batch_size=32)
相關(guān)參考:https://keras.io/zh/getting-started/functional-api-guide/
以上這篇keras 回調(diào)函數(shù)Callbacks 斷點(diǎn)ModelCheckpoint教程就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
python 在某.py文件中調(diào)用其他.py內(nèi)的函數(shù)的方法
這篇文章主要介紹了python 在某.py文件中調(diào)用其他.py內(nèi)的函數(shù)的方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-06-06Python中的sorted函數(shù)應(yīng)用及文件操作詳解
這篇文章主要介紹了Python中的sorted函數(shù)應(yīng)用及文件操作詳解,python只能將字符串寫入到文本文件,要將數(shù)值數(shù)據(jù)存儲(chǔ)到文本本件中,必須先試用函數(shù)str()將其轉(zhuǎn)換為字符串格式,需要的朋友可以參考下2023-12-12python讀取并顯示圖片的三種方法(opencv、matplotlib、PIL庫)
這篇文章主要給大家介紹了關(guān)于python讀取并顯示圖片的三種方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04