簡體   English   中英

使用驗證集確定Keras中的紀元數

[英]Use validation set to determine number epochs in Keras

我想知道是否可能使用交叉驗證或固定的預定義驗證集來確定在Python中使用Keras的NN的“最佳”時期數。 我目前有以下代碼:

from tensorflow.keras.layers import Dense, Activation
from tensorflow.keras.models import Sequential
import pandas as pd
import numpy as np

model = Sequential()
# Adding the input layer and the first hidden layer
model.add(Dense(16, activation = 'relu', input_dim = 243))
# Adding the output layer
model.add(Dense(units = 1))
model.compile(optimizer = 'adam',loss = 'mean_squared_error')
model.fit(X, Y, batch_size = 32, epochs = 20)

如果可能,我必須在代碼中添加些什么? 我意識到這不是可復制的示例,盡管我認為我的問題不是必需的。

您完全正確! 查找“最佳”時期的最佳方法是使用回調

這樣,當您達到感興趣指標的最高分數時,就可以停止訓練。 這是一個例子

model = Sequential()
# Adding the input layer and the first hidden layer
model.add(Dense(16, activation = 'relu', input_dim = 243))
# Adding the output layer
model.add(Dense(units = 1))
model.compile(optimizer = 'adam',loss = 'mean_squared_error')

es = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=40) # Model stop training after 40 epoch where validation loss didnt decrease
mc = ModelCheckpoint('best_model.h5', monitor='val_loss', mode='min', verbose=1, save_best_only=True) #You save model weight at the epoch where validation loss is minimal
train = model.fit((train_X, train_label, batch_size=batch_size),epochs=1000,verbose=1,validation_data=(valid_X, valid_label),callbacks=[es,mc])#you can run for 1000 epoch btw model will stop after 40 epoch without better validation loss

如果您想減輕體重,我將讓您在互聯網上查看操作方法。 減輕重量使您可以重新使用模型,而無需再次訓練。

對於后者,請注意,遵循驗證損失分數並不總是最好的做法。 對您來說,一種鍛煉可能是找到在准確性達到最大值時如何保存模型的方法。

我不知道我是否完全理解您的問題,但是如果您想在代碼中添加某物,那將決定多少個時期足以訓練您的數據,那是不可能的。 您應該明確選擇時期數。 但除此之外,您可以使用回調或TensorBoard。 例如,選擇您的紀元為1000。然后,您可以使用回調方式,如果精度沒有變化,則停止訓練。 通常,對於回調,您可以指定條件,然后在條件發生時執行其他操作。 (在我們的示例中,如果在一個時期后精度沒有改變,請停止訓練)。 除此之外,您可以使用TensorBoard。 使用此工具,您可以在訓練后查看與模型相關的所有內容的歷史記錄。 這是回調和TensorBoard文檔的鏈接: https ://keras.io/callbacks/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM