【发布时间】:2020-06-12 16:41:31
【问题描述】:
我正在基于我在网上找到的一个简单的自动编码器示例在 python 中构建一个模型。该示例是为 keras 编写的。通过推荐的到 tensorflow.keras 的转换,我修改了程序的导入,预计不需要其他更改。
使用 keras 导入
from keras.layers import Input, Dense
from keras.models import Model
from keras.datasets import mnist
自动编码器工作正常,您可以看到它在标准输出中收敛,并且恢复的图像是有意义的。当我使用 tensorflow 输入时
from tensorflow.python.keras.layers import Input, Dense
from tensorflow.python.keras.models import Model
from tensorflow.python.keras.datasets import mnist
结果不再收敛,恢复的图像看起来像噪声。
以下是我的问题的最小工作示例。只需在上述两个导入之间进行更改即可重现行为差异。
import numpy as np
import matplotlib.pyplot as plt
def prepModel(inputShape, outputShape, numNeurons):
input_image = Input(shape=(inputShape,))
#encoded representation of input
encoded = Dense(numNeurons, activation='relu')(input_image)
#decoded lossy reconstruction
decoded = Dense(outputShape, activation='sigmoid')(encoded)
#model to encoded data
autoencoder = Model(input_image, decoded)
encoder = Model(input_image, encoded)
encoded_input = Input(shape=(numNeurons,)) #placeholder
decoder_layer = autoencoder.layers[-1] #last layer of model
decoder = Model(encoded_input, decoder_layer(encoded_input)) #decoder model
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
return autoencoder, encoder, decoder
def prepData():
#import / set data
(x_train, _), (x_test, _) = mnist.load_data()
x_train = x_train.astype('float32')/255
x_test = x_test.astype('float32')/255
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:])))
return x_train, x_test
def runModel(autoencoder, encoder, decoder, x_train, x_test):
#train encoder
autoencoder.fit(x_train, x_train,
epochs=50,
batch_size=256,
shuffle=True,
validation_data=(x_test, x_test))
encoded_images = encoder.predict(x_test)
decoded_images = decoder.predict(encoded_images)
return encoded_images, decoded_images
def plotComparison(x_test, decoded_images):
#Plot original image
n = 10
plt.figure(figsize=(20,4))
for i in range(n):
ax = plt.subplot(2,n,i+1)
plt.imshow(x_test[i].reshape(28,28))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
#plot decompressed image
ax = plt.subplot(2, n, i+1+n)
plt.imshow(decoded_images[i].reshape(28,28))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
x_train, x_test = prepData()
autoencoder, encoder, decoder = prepModel(784, 784, 16)
encoded_images, decoded_images = runModel(autoencoder, encoder, decoder, x_train, x_test)
plotComparison(x_test, decoded_images)
我正在运行 python 3.8.3、keras 版本 2.3.1 和 tensorflow 版本 2.2.0。我已经愚弄了重新调整输入数据和其他天真的技巧,但无济于事。我已经验证了另外两台计算机上的行为。什么可以解释为什么两组进口之间的表现如此不同?
【问题讨论】:
标签: python python-3.x tensorflow keras deep-learning