You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MNIST分类任务中Keras Sequential模型输入形状不兼容问题求助

Fixing Input Shape Mismatch in MNIST Classification

Hey there! Let's break down why you're hitting that error and how to fix it quickly.

The Root Cause

Your error message spells out the core issue clearly:

ValueError: Input 0 of layer sequential_12 is incompatible with the layer: expected axis -1 of input shape to have value 784 but received input with shape (100, 28, 28)

The Dense layer you defined expects each input sample to be a 1D array of 784 features (thanks to input_dim=784). But your MNIST data is in the shape of (batch_size, 28, 28) — these are 28x28 2D images, not flattened 1D vectors. That's the mismatch causing the error!

You Don't Need Resize — Here's What to Do

Resize is for changing image dimensions (like turning a 28x28 image into 32x32), which isn't what you need here. Instead, you need to flatten the 2D image into a 1D vector. There are two straightforward ways to do this:

Option 1: Add a Flatten Layer to Your Model

This is the cleaner, more Keras-idiomatic approach. The Flatten layer will automatically convert your 28x28 images into 784-length vectors:

model = tf.keras.Sequential()
# Add Flatten to convert (28,28) images into (784,) vectors
model.add(tf.keras.layers.Flatten(input_shape=(28, 28)))
model.add(tf.keras.layers.Dense(units=10, 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))

We removed input_dim=784 from the Dense layer and instead set input_shape=(28,28) on the Flatten layer — this tells Keras exactly what input shape to expect from your raw image data.

Option 2: Manually Flatten Your Data

If you prefer to preprocess your data before feeding it to the model, you can use reshape to flatten the arrays:

# Flatten the training and test data
# -1 tells NumPy to automatically calculate the number of samples
x_train = x_train.reshape(-1, 28 * 28)
x_test = x_test.reshape(-1, 28 * 28)

# Now your original model code will work as expected
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))

Quick Bonus Tip

If your y_train and y_test are integer labels (e.g., 0, 1, ..., 9) instead of one-hot encoded vectors, switch to loss='sparse_categorical_crossentropy' — this saves you from having to convert labels to one-hot format manually.

内容的提问来源于stack exchange,提问作者tureehh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 22:02:32