我正在尝试构建一个mnist自动编码器,以学习如何处理整形和编码。
当我运行代码时,会抛出以下错误:
ValueError: total size of new array must be unchanged, input_shape = [748], output_shape = [28, 28]
代码如下:
import tensorflow as tf
import tensorflow.keras as keras
from tensorflow.keras import layers
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255., x_test / 255.
enc_in = tf.keras.Input(shape=(28, 28))
x = layers.Flatten()(enc_in)
x = layers.Dense(128, activation='relu', name='enc_dense_1')(x)
enc_out = layers.Dense(10, activation='softmax', name='enc_out')(x)
x = layers.Dense(128, activation='relu', name='dec_dense_1')(enc_out)
x = layers.Dense(748, activation='relu', name='dec_dense_2')(x)
dec_out = layers.Reshape(target_shape=(28, 28))(x)
autoencoder = keras.Model(inputs=enc_in, outputs=dec_out)
autoencoder.compile(
optimizer='adam',
loss=keras.losses.CategoricalCrossentropy(),
metrics=['accuracy']
)
print(autoencoder.summary())
autoencoder.fit(x_train, x_train, batch_size=64, epochs=10, validation_split=0.2)
为什么tensorflow在我的keras时抱怨输出形状。输入形状是(28,28(?
这个错误不言自明,你犯了一个小错误。
#28 * 28 = 784
x = layers.Dense(748, activation='relu', name='dec_dense_2')(x)
dec_out = layers.Reshape(target_shape=(28, 28))(x)
您意外地写入了748
而不是784
,当然,由于此错误,无法进行整形。