1

我知道有类似的问题。尽管我已经检查过它们,但我没有解决我的问题。

我试图在时尚 Mnist 数据集上实现小批量。因此,我将数据集从 np.array 转换为张量,tf.data.Dataset.from_tensor_slices但我无法解决数据形状不兼容的问题。这是我的代码:

加载数据中

(train_images, train_labels) , (test_images, test_labels) = fashion_mnist.load_data()

转换为 tf.Dataset:

 train_ds = tf.data.Dataset.from_tensor_slices((train_images, train_labels))
 test_ds = tf.data.Dataset.from_tensor_slices((test_images, test_labels))

我的模型

model_1 = tf.keras.Sequential([
    
    tf.keras.layers.Flatten(input_shape = [28,28]),
    tf.keras.layers.Dense(50, activation = "relu"),
    tf.keras.layers.Dense(30, activation = "relu"),
    tf.keras.layers.Dense(10, activation = "softmax"),
    
])

model_1.compile( loss = tf.keras.losses.SparseCategoricalCrossentropy(),
               optimizer = tf.keras.optimizers.Adam(),
               metrics = ["accuracy"])

info = model_1.fit(train_ds,
                  epochs = 10,
                  validation_data = (test_images, test_labels))

但这给了我这个错误:

ValueError: Input 0 of layer dense_1 is incompatible with the layer: expected axis -1 of input shape to have value 784 but received input with shape [28, 28]

我使用以下代码检查了输入形状:(输出为 [28, 28])

list(train_ds.as_numpy_iterator().next()[0].shape)

我该如何解决这个问题,如果你能帮助我,我将不胜感激。

谢谢!

4

1 回答 1

0

由于您使用tf.data.DatasetAPI 来提供模型,因此您应该从数据集中定义 batch_size。

train_ds = tf.data.Dataset.from_tensor_slices((train_images, train_labels)).batch(256)
test_ds = tf.data.Dataset.from_tensor_slices((test_images, test_labels)).batch(256)

现在您可以使用这两个数据集来训练您的模型,例如:

info = model_1.fit(x=train_ds, epochs = 10, validation_data=test_ds)
于 2021-08-17T20:17:11.023 回答