如何匹配深度自动编码器的编码器解码器尺寸?



我正在使用具有三个潜在空间层的MNIST数据集编写非常简单的深度自动编码器。 但是,编码器和解码器尺寸存在问题。

确切的错误消息是:ValueError:检查输入时出错:预期input_2具有形状 (128,(,但在第 60 行得到形状为 (32,( 的数组。

(第 60 行:decoded_imgs = decoder.predict(encoded_imgs((

我不知道如何解决它。我将在下面附上我的完整代码。 请帮忙。谢谢。

from keras.layers import Input, Dense
from keras.models import Model
import cv2
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import mlab
from matplotlib import pyplot as plt
import sys
np.set_printoptions(threshold=sys.maxsize)

# encoding_dimensions
encoding_dim = 128
encoding_dim2 = 64
encoding_dim3 = 32
# input placeholder
input_img = Input(shape=(784,))
encoded = Dense(128, activation='relu')(input_img)
encoded = Dense(64, activation='relu')(encoded)
encoded = Dense(32, activation='relu')(encoded)
decoded = Dense(64, activation='relu')(encoded)
decoded = Dense(128, activation='relu')(decoded)
decoded = Dense(784, activation='sigmoid')(decoded)
print(encoded.shape)
print(decoded.shape)
autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')

encoder = Model(input_img, encoded)
encoded_input = Input(shape=(encoding_dim,))

decoder_layer = autoencoder.layers[-1]
decoder = Model(encoded_input, decoder_layer(encoded_input))
from keras.datasets import mnist
(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:])))
print(x_test.shape)
print(x_train.shape)
autoencoder.fit(x_train, x_train,
epochs=1,
batch_size=256,
shuffle=True,
validation_data=(x_test, x_test))
encoded_imgs = encoder.predict(x_test)
decoded_imgs = decoder.predict(encoded_imgs)
n=10
plt.figure(num=2, figsize=(20, 3))
for i in range(n):
# input data
ax = plt.subplot(2, n, i + 1)
plt.imshow(x_test[i].reshape(28, 28))
plt.gray()
ax.get_yaxis().set_visible(False)
ax.get_xaxis().set_visible(False)
# recnstructed data
ax = plt.subplot(2, n, i + 1 + n)
plt.imshow(decoded_imgs[i].reshape(28, 28))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()

问题出在decoder模型的输入定义上。将解码器模型的输入设置为:encoded_input = Input(shape=(encoding_dim,))encoding_dim=128的位置。但是,解码器的实际输入是编码器输出,其大小为 32(编码器最后Dense层的神经元数量(。您需要在解码器模型中修复输入形状的声明,例如:

encoded_input = Input(shape=(32,))

或模式一般:

encoded_input = Input(shape=encoded.shape)

相关内容

  • 没有找到相关文章

最新更新