我是一名正在与keras学习自动编码器的学生。我使用mnist数据集作为输入(784个节点),并制作了8个节点作为隐藏层。我想做的是任意调整隐藏层的值。但是,当我在隐藏层中任意输入shape(8,)的输入时,
ValueError:检查输入时出错:预期input_2的形状为(8,),但数组的形状为(1,)
发生错误。我输入的矩阵是np.array([0,0,0,0,0,0,0,0,0])的形式,显然是(8,)而不是(1,0)的形式。
下面是代码的全文。请帮忙。谢谢。
from keras.layers import Input, Dense
from keras.models import Model
import matplotlib.pyplot as plt
import numpy as np
import sys
# size of hidden layer
encoding_dim = 8
# input place holder
input_img = Input(shape=(784,))
# "encoded"
encoded = Dense(encoding_dim, activation='relu')(input_img)
# "decoded" (lossy reconstruction)
decoded = Dense(784, activation='sigmoid')(encoded)
# input -> recomstructed model
autoencoder = Model(input_img, decoded)
# encoder model
encoder = Model(input_img, encoded)
encoded_input = Input(shape=(encoding_dim,))
decoder_layer = autoencoder.layers[-1]
# decoder model
decoder = Model(encoded_input, decoder_layer(encoded_input))
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
from keras.datasets import mnist
np.set_printoptions(threshold=sys.maxsize)
(x_train, train_labels), (x_test, test_labels) = 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:])))
autoencoder.fit(x_train, x_train,
epochs=30,
batch_size=256,
shuffle=True,
validation_data=(x_test, x_test))
# encoding, decodeing
encoded_imgs = encoder.predict(x_test)
decoded_imgs = decoder.predict(encoded_imgs)
# I want to change this as decoded_imgs = decoder.predict([0,0,0,0,0,0,0,0])
n = 10
plt.figure(num=1, figsize=(20, 3))
for i in range(n):
ax = plt.subplot(2, n, i + 1)
plt.imshow(encoded_imgs[i].reshape(2, 4).T)
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
plt.figure(num=2, figsize=(20, 3))
for i in range(n):
# original data plot
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)
# reconstructed data plot
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()
调试代码时,我发现“ encoded_imgs”的形状为(10000,8)。数组[0, 0, 0, 0, 0, 0, 0, 0]
的形状确实为,(8,)
但它只是一维数组,而您的解码器.predict方法期望的形状为(10000,8)。如果您只想用零尝试一下,请改用它:
decoded_imgs = decoder.predict(np.zeros(shape=(10000, 8)))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句