簡體   English   中英

如何使用自定義數據集訓練 Keras 自動編碼器?

[英]How to train a Keras autoencoder with custom dataset?

我正在閱讀本教程以創建我自己的基於 Keras 的自動編碼器。 我一步一步按照教程進行操作,唯一的區別是我想使用我自己的圖像數據集來訓練 model。 所以我更改/添加了以下代碼:


IMAGES = "/path/to/my/images"
SHAPE = (200, 200)
INIT_LR = 1e-3
EPOCHS = 20
BS = 32

(encoder, decoder, autoencoder) = ConvAutoencoder.build(SHAPE[0], SHAPE[1], 3)
opt = Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS)
autoencoder.compile(loss="mse", optimizer=opt)

image_generator = ImageDataGenerator(rescale=1.0 / 255)
train_gen = image_generator.flow_from_directory(
    os.path.join(IMAGES, "training"), 
    class_mode=None, target_size=SHAPE, batch_size=BS,
)
val_gen = image_generator.flow_from_directory(
    os.path.join(IMAGES, "validation"), 
    class_mode=None, target_size=SHAPE, batch_size=BS,
)

hist = autoencoder.fit(train_gen, validation_data=val_gen, epochs=EPOCHS, batch_size=BS)

我的圖像是 RGB 格式的普通.jpg文件。 但是,一旦訓練開始, fit()方法就會引發以下異常:

ValueError: No gradients provided for any variable: ['conv2d/kernel:0', 'conv2d/bias:0', 'batch_normalization/gamma:0', 'batch_normalization/beta:0', 'conv2d_1/kernel:0', 'conv2d_1/bias:0', 'batch_normalization_1/gamma:0', 'batch_normalization_1/beta:0', 'dense/kernel:0', 'dense/bias:0', 'dense_1/kernel:0', 'dense_1/bias:0', 'conv2d_transpose/kernel:0', 'conv2d_transpose/bias:0', 'batch_normalization_2/gamma:0', 'batch_normalization_2/beta:0', 'conv2d_transpose_1/kernel:0', 'conv2d_transpose_1/bias:0', 'batch_normalization_3/gamma:0', 'batch_normalization_3/beta:0', 'conv2d_transpose_2/kernel:0', 'conv2d_transpose_2/bias:0'].

有什么想法我在這里想念的嗎?

在 flow_from_directory 使用 class_mode="input" 所以返回的 Y 將與 X 相同

https://github.com/tensorflow/tensorflow/blob/v2.4.1/tensorflow/python/keras/preprocessing/image.py#L867-L958

class_mode :“分類”、“二進制”、“稀疏”、“輸入”或無之一。 默認值:“分類”。 Determines the type of label arrays that are returned: - "categorical" will be 2D one-hot encoded labels, - "binary" will be 1D binary labels, "sparse" will be 1D integer labels, - "input" will be images identical輸入圖像(主要用於自動編碼器)。 - 如果為 None,則不返回任何標簽(生成器將只生成批量圖像數據,這對於與model.predict()一起使用很有用)。 請注意,在 class_mode None 的情況下,數據仍然需要駐留在directory的子目錄中才能正常工作。

代碼最終應該是這樣的:

image_generator = ImageDataGenerator(rescale=1.0 / 255)
train_gen = image_generator.flow_from_directory(
    os.path.join(IMAGES, "training"), 
    class_mode="input", target_size=SHAPE, batch_size=BS,
)
val_gen = image_generator.flow_from_directory(
    os.path.join(IMAGES, "validation"), 
    class_mode="input", target_size=SHAPE, batch_size=BS,
)
hist = autoencoder.fit(train_gen, validation_data=val_gen, epochs=EPOCHS, batch_size=BS)

暫無
暫無

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

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