![](/img/trans.png)
[英]steps_per_epoch and validation_steps for infinite Dataset in Keras Model
[英]How to properly set steps_per_epoch and validation_steps in Keras?
我已經在 Keras 中訓練了幾個模型。 我的訓練集中有 39, 592 個樣本,驗證集中有 9, 899 個樣本。 我使用的批量大小為 2。
當我檢查我的代碼時,我突然想到我的生成器可能丟失了一些批次的數據。
這是我的生成器的代碼:
train_datagen = ImageDataGenerator(
rescale=1. / 255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
val_datagen = ImageDataGenerator(rescale=1. / 255)
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(224, 224)
batch_size=batch_size,
class_mode='categorical')
validation_generator = val_datagen.flow_from_directory(
val_dir,
target_size=(224, 224),
batch_size=batch_size,
class_mode='categorical')
我四處搜索以查看我的生成器的行為方式,並找到了這個答案: 如果 steps_per_epoch 不適合樣本數量怎么辦?
我是這樣計算我的 steps_per_epoch 和 validation_steps 的:
steps_per_epoch = int(number_of_train_samples / batch_size)
val_steps = int(number_of_val_samples / batch_size)
將此鏈接中的代碼與我自己的批量大小和樣本數量一起使用,我得到了以下結果:train_generator 的“缺少最后一批”和 val_generator 的“奇怪的行為”。
恐怕我必須再次重新訓練我的模型。 我應該為steps_per_epoch 和validation_steps 選擇什么值? 有沒有辦法為這些變量使用精確值(除了將 batch_size 設置為 1 或刪除一些樣本)? 我還有其他幾個具有不同樣本數量的模型,我認為它們都缺少一些批次。 任何幫助將非常感激。
兩個相關問題:
1- 關於我已經訓練過的模型,它們是否可靠且訓練有素?
2- 如果我使用以下值設置這些變量會發生什么:
steps_per_epoch = np.ceil(number_of_train_samples / batch_size)
val_steps = np.ceil(number_of_val_samples / batch_size)
在訓練和驗證期間,我的模型會在每個 epoch 中多次看到某些圖像嗎? 或者這是我問題的解決方案嗎?!
由於Keras數據生成器意圖無限循環, steps_per_epoch
表示在單個紀元期間從生成器獲取新批次的次數。 因此,如果您只是采用steps_per_epoch = int(number_of_train_samples / batch_size)
,那么您的上一批產品將少於batch_size
項,並將被丟棄。 但是,在您的情況下,每個訓練時期丟失1張圖像並不是什么大問題。 驗證步驟也是如此。 總結一下:你的模型正確地訓練[幾乎:)],因為丟失元素的數量很少。
對應於實現ImageDataGenerator
https://keras.io/preprocessing/image/#imagedatagenerator-class如果您的步數大於預期,在達到最大樣本數后,您將從頭開始接收新批次,因為您的數據循環。 在您的情況下,如果steps_per_epoch = np.ceil(number_of_train_samples / batch_size)
您將在每個時期收到一個額外的批次,其中包含重復的圖像。
除了 Greeser 的回答,為了避免丟失一些訓練樣本,您可以使用此函數計算您的步驟:
def cal_steps(num_images, batch_size):
# calculates steps for generator
steps = num_images // batch_size
# adds 1 to the generator steps if the steps multiplied by
# the batch size is less than the total training samples
return steps + 1 if (steps * batch_size) < num_images else steps
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.