【发布时间】: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 的输出
你可以在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