【发布时间】:2021-06-09 05:49:32
【问题描述】:
我正在关注本教程https://blog.keras.io/building-autoencoders-in-keras.html,特别是卷积示例。我不明白为什么如果我将损失函数从 binary_crossentropy 更改为 MSE,它只适用于 fashion_mnist。
使用 mnist,损失在第一个 epoch 后下降,不再变化。训练后,测试集上的预测图像只是黑色图像。使用 fashion_mnist 效果很好。
import keras
from keras import layers
import keras.backend as K
input_img = keras.Input(shape=(28, 28, 1))
x = layers.Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)
x = layers.MaxPooling2D((2, 2), padding='same')(x)
x = layers.Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = layers.MaxPooling2D((2, 2), padding='same')(x)
x = layers.Conv2D(8, (3, 3), activation='relu', padding='same')(x)
encoded = layers.MaxPooling2D((2, 2), padding='same')(x)
# at this point the representation is (4, 4, 8) i.e. 128-dimensional
x = layers.Conv2D(8, (3, 3), activation='relu', padding='same')(encoded)
x = layers.UpSampling2D((2, 2))(x)
x = layers.Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = layers.UpSampling2D((2, 2))(x)
x = layers.Conv2D(16, (3, 3), activation='relu')(x)
x = layers.UpSampling2D((2, 2))(x)
decoded = layers.Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)
autoencoder = keras.Model(input_img, decoded)
autoencoder.compile(optimizer='adam', loss='mse') # binary_crossentropy
from keras.datasets import mnist
from keras.datasets import fashion_mnist
import numpy as np
(x_train, _), (x_test, _) = mnist.load_data() # fashion_mnist.load_data()
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = np.reshape(x_train, (len(x_train), 28, 28, 1))
x_test = np.reshape(x_test, (len(x_test), 28, 28, 1))
history = autoencoder.fit(x_train, x_train,
epochs=50,
batch_size=128,
shuffle=True,
validation_data=(x_test, x_test))
【问题讨论】:
-
MSE对错误分类的惩罚不够,但却是 regression 的正确损失。对于分类,cross-entropy往往比MSE更合适。谈到您的问题,当我尝试预测时,我没有看到任何黑色图像。您能否尝试并分享您在 Google Colab 中的尝试,以便我们尽力为您提供最好的帮助。谢谢!
标签: python tensorflow keras deep-learning autoencoder