使用 tensorflow 的 keras 时出现 ValueError

ValueError showing up while using tensorflow's keras

我是机器学习的新手,正在尝试使用 keras 编写一个简单的程序。当我 运行 以下代码时,我收到一条错误消息 "ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 784 but received input with shape [32, 28, 28]"。有人可以帮我吗?我正在尝试跟随这个视频:https://www.youtube.com/watch?v=tjsHSIG8I08,但它似乎不起作用。提前致谢!

import tensorflow as tf
import numpy as np

(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()

model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(512, activation=tf.nn.relu, input_shape=(784,)))
model.add(tf.keras.layers.Dense(256, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))

model.compile(loss='categorical_crossentropy', optimizer='rmsprop')

model.fit(train_images, train_labels, epochs=5)

loss, accuracy = model.evaluate(test_images, test_labels)
print('Accuracy', accuracy)

scores = model.predict(test_images[0:1])
print(np.argmax(scores))

问题来自input_shape=(784,)。首先,您需要了解输入维度的工作原理。输入数据必须遵循此维度(样本数,输入维度),因此在您使用 (32, 28, 28) 的情况下,它是 (28 X 28) 的 mnist 数据集维度,样本数等于 32。因此,您必须更改为 input_shape=(28,28),你可以开始了。