【问题标题】:keras 2.4. producing completely different output than 2.3.1喀拉拉邦 2.4。产生与 2.3.1 完全不同的输出
【发布时间】:2021-03-20 06:06:55
【问题描述】:

我正在尝试实现自动编码器。使用 mnsit 数据集,我首先对图像进行编码,然后对其进行解码。当我使用 keras 2.3.1 版时,我得到的解码图像非常接近原始图像,但是在使用 Keras 2.4.3 并且没有更改代码时,我得到完全不同的输出,解码图像接近垃圾。我尝试寻找原因,但找不到任何原因,也没有任何关于如何从 2.3.1 迁移到 2.4.3 的文档或文章。

这是 keras 2.3.1 的输出

使用 keras 2.4.3 输出

你可以在google colab或下面找到代码,请注意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()    

有什么建议吗?

【问题讨论】:

    标签: python tensorflow machine-learning keras deep-learning


    【解决方案1】:

    看起来 Adadelta 优化器在 Keras 中的默认学习率为 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')
    

    【讨论】:

    • 这行得通。有什么官方文件或资料可以参考吗?从Keras 2.3.1 更改为tf.keras?
    【解决方案2】:

    发生这种情况是因为 Keras 2.4 实际上只是 tf.keras 的一个包装器,因此您的代码有效地使用了 tf.keras,并包含它所带来的所有错误。

    如果您想要“经典 keras”行为(特别是如果您使用 keras 而不是 tf.keras 开发所有代码),那么您应该使用 Keras 2.3.1 而不是升级到新版本。

    【讨论】:

    • 有没有办法知道从Kerastf.keras 的变化,比如完整的更新日志?从@NIma answer 可以看出,学习率从1.0 更改为0.001,我认为这是一个重大变化。
    猜你喜欢
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    • 2018-01-22
    • 1970-01-01
    相关资源
    最近更新 更多