【问题标题】:ValueError: Input 0 of layer sequential_12 is incompatible with the layerValueError: 层序贯_12 的输入 0 与层不兼容
【发布时间】:2021-11-08 23:04:54
【问题描述】:

我正在研究 mnist 分类代码。 下面的代码中不断出现此类错误。

model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(units=10, input_dim=784, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer=tf.optimizers.Adam(learning_rate=0.001), metrics=['accuracy'])
model.summary()

model.fit(x_train, y_train, batch_size=100, epochs=10, validation_data=(x_test, y_test))

ValueError: 层序数_12 的输入 0 与层不兼容:输入形状的预期轴 -1 具有值 784,但接收到形状为 (100, 28, 28) 的输入

我应该说“调整大小”吗?我试图修复这个数字,但我无法解决它。如果您能帮助我,我将不胜感激。

【问题讨论】:

标签: tensorflow keras


【解决方案1】:

在使用模型之前,您必须重塑 mnist 数据集,如下所示:

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

train_labels = train_labels[:1000]  # to take only 1000 rows of dataset
test_labels = test_labels[:1000]

train_images = train_images[:1000].reshape(-1, 28 * 28) / 255.0
test_images = test_images[:1000].reshape(-1, 28 * 28) / 255.0

然后定义模型并将训练和测试数据集拟合到模型中。

model = tf.keras.models.Sequential([
    keras.layers.Dense(512, activation='relu', input_shape=(784,)),
    keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
             loss=tf.losses.SparseCategoricalCrossentropy(),
              metrics=['Accuracy'])


# Display the model's architecture
model.summary()

model.fit(train_images,train_labels, epochs=10, validation_data=(test_images, test_labels))

详情请参考this

【讨论】:

    猜你喜欢
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 2021-05-31
    • 2020-11-28
    • 2021-09-13
    • 1970-01-01
    相关资源
    最近更新 更多