ama*_*yal 1 python machine-learning deep-learning keras tensorflow
我正在尝试实现自动编码器。使用 mnsit 数据集,我首先对图像进行编码,然后对其进行解码。当我使用 keras 2.3.1 版时,我得到的解码图像非常接近原始图像,但是在使用 Keras 2.4.3 并且没有更改代码时,我得到了完全不同的输出,解码后的图像接近垃圾。我试图寻找原因,但找不到任何原因,也没有任何关于如何从 2.3.1 迁移到 2.4.3 的文档或文章。
这是 keras 2.3.1 的输出 
您可以在google colab或 down 中找到代码here ,请注意,google collab 使用的是 Keras 2.3.1
import keras
from keras.layers import Input, Dense
from keras.models import Model
import numpy as np
input_img = Input(shape=(784,)) #input layer
encoded = Dense(32, activation="relu")(input_img) # encoder
decoded = Dense(784, activation='sigmoid')(encoded) # decocer, output
# defining autoenoder model
autoencoder = Model(input_img, decoded) # autoencoder = encoder+decoder
# defining encoder model
encoder = Model(input_img, encoded) # takes input images and encoded_img
# defining decoder model
encoded_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 images
from 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 784
x_train = x_train.astype('float32')/255
x_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 Visualization
import matplotlib.pyplot as plt
n = 10
plt.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()
Run Code Online (Sandbox Code Playgroud)
有什么建议吗?
看起来 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')
Run Code Online (Sandbox Code Playgroud)