我在尝试实现自编码器。使用 MNIST 数据集,我首先对图像进行编码,然后解码它们。当我使用 Keras 2.3.1 版本时,解码后的图像与原始图像非常接近,但当我使用 Keras 2.4.3 版本且代码未做任何更改时,解码后的图像输出完全不同,接近于垃圾。我尝试找出原因,但没有找到任何线索,也没有找到任何关于如何从 2.3.1 迁移到 2.4.3 的文档或文章。
这是使用 Keras 2.3.1 的输出
您可以在 Google Colab 或下方找到代码,请注意 Google Colab 使用的是 Keras 2.3.1
import kerasfrom keras.layers import Input, Dense from keras.models import Modelimport numpy as npinput_img = Input(shape=(784,)) #input layerencoded = Dense(32, activation="relu")(input_img) # encoder decoded = Dense(784, activation='sigmoid')(encoded) # decocer, output# defining autoenoder modelautoencoder = Model(input_img, decoded) # autoencoder = encoder+decoder# defining encoder modelencoder = Model(input_img, encoded) # takes input images and encoded_img# defining decoder modelencoded_input = Input(shape=(32,))decoded_layer = autoencoder.layers[-1](encoded_input)decoder = Model(encoded_input, decoded_layer)autoencoder.compile(optimizer = 'adadelta', loss='binary_crossentropy')# Test on imagesfrom keras.datasets import mnist(x_train, _), (x_test, _) = mnist.load_data()# Normalize the value between 0 and 1 and flatten 28x28 images in to vector of 784x_train = x_train.astype('float32')/255x_test = x_test.astype('float32')/255# reshaping (60000, 28,28) -> (60000, 784)x_train = x_train.reshape(len(x_train), np.prod(x_train.shape[1:]))x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))autoencoder.fit(x_train, x_train, epochs=50, batch_size=200 )encoded_img = encoder.predict(x_test)decoded_img = decoder.predict(encoded_img)encoded_img.shape, decoded_img.shape# Performing Visualizationimport matplotlib.pyplot as pltn = 10plt.figure(figsize=(40, 8))for i in range(n): plt.subplot(2, n, i+1) plt.imshow(x_test[i].reshape(28, 28)) # Recontructed Imgae plt.subplot(2, n, n+i+1) plt.imshow(decoded_img[i].reshape(28, 28)) plt.show()
有什么建议吗?
回答:
看起来 Keras 中 Adadelta 优化器的默认学习率是 1.0,而在 tf.keras 中是 0.001。当你切换到 tf.keras 时,Adadelta 的学习率太小,以至于网络无法学习任何东西。你可以在编译模型之前更改学习率,如下所示,这样在 tf.keras 中你将得到与 Keras 中相同的行为。
opt = tf.keras.optimizers.Adadelta(learning_rate=1.0)autoencoder.compile(optimizer = opt, loss='binary_crossentropy')