整理自keras:https://keras-cn.readthedocs.io/en/latest/other/callbacks/
回調(diào)函數(shù)是一個(gè)函數(shù)的合集,會(huì)在訓(xùn)練的階段中所使用。你可以使用回調(diào)函數(shù)來(lái)查看訓(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ù)傳遞)來(lái)填充。
參數(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ù)的名字中判斷出來(lái)。
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)過(guò)程:
① 從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ù)
1
2
3
4
|
if os.path.exists(filepath): model.load_weights(filepath) # 若成功加載前面保存的參數(shù),輸出下列信息 print ( "checkpoint_loaded" ) |
④ 在model.fit添加callbacks=[checkpoint]實(shí)現(xiàn)回調(diào)
1
2
3
4
5
6
7
|
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)題本身,即一系列詞語(yǔ)。
輔助輸入(aux_input): 接受額外的數(shù)據(jù),例如新聞標(biāo)題的發(fā)布時(shí)間等。
該模型將通過(guò)兩個(gè)損失函數(shù)進(jìn)行監(jiān)督學(xué)習(xí)。
較早地在模型中使用主損失函數(shù),是深度學(xué)習(xí)模型的一個(gè)良好正則方法。
完整過(guò)程圖示如下:
其中,紅圈中的操作為將輔助數(shù)據(jù)與LSTM層的輸出連接起來(lái),輸入到模型中。
代碼實(shí)現(xiàn):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
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 之間 # 注意我們可以通過(guò)傳遞一個(gè) `name` 參數(shù)來(lái)命名任何層 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層的輸出連接起來(lái),輸入到模型中 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)練模型:我們可以通過(guò)傳遞輸入數(shù)組和目標(biāo)數(shù)組的列表來(lái)訓(xùn)練模型 model.fit([headline_data, additional_data], [labels, labels], epochs = 50 , batch_size = 32 ) # 另外一種利用字典的編譯、訓(xùn)練方式 # 由于輸入和輸出均被命名了(在定義時(shí)傳遞了一個(gè) name 參數(shù)),我們也可以通過(guò)以下方式編譯模型 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è)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/jieshaoxiansen/article/details/82762922