Keras分类模型输入形状不匹配问题求助
Hey there, let's work through this input shape issue you're facing! The core problem here is how Keras expects input data to be structured—especially when using predict().
Why You're Getting the Error
Your model defines input_shape=(4,40), which means it expects each individual sample to be a 2D array of shape (4,40). But Keras always processes data in batches, so the full input shape it looks for is (batch_size, 4, 40) (3 dimensions total).
When you pass a single sample with shape (4,40) directly to predict(), Keras misinterprets it: it thinks you're feeding a batch of 4 samples, each with shape (40,), which doesn't match what the model expects. That's why you see the error about expecting 3 dimensions but getting 2.
Solution 1: Keep the 2D Sample Shape (Recommended)
Just add a batch dimension to your single input sample using np.expand_dims():
import numpy as np # Your original input: shape (4,40) config_repr = listVecteursStackBuffer # Add a batch dimension at axis 0: new shape becomes (1,4,40) config_repr_with_batch = np.expand_dims(config_repr, axis=0) # Now predict should work predictions = self.model.predict(config_repr_with_batch)
You can verify the model's expected input shape by running:
print(self.model.input_shape) # Should output (None, 4, 40) — None means batch size is variable
Solution 2: Flatten the Input to 1D
If you want to stick with merging the 4 arrays into a single 160-length vector, you need to make sure both the model and input data align:
Update the model definition to expect a 1D input:
self.model = Sequential() self.model.add(Dense(32, input_shape=(160,))) # Or use input_dim=160 self.model.add(Dense(5, activation='softmax'))Flatten your input and add the batch dimension:
# Flatten the (4,40) array to (160,) config_repr_flattened = config_repr.flatten() # Add batch dimension: shape becomes (1,160) config_repr_flattened_with_batch = np.expand_dims(config_repr_flattened, axis=0) # Predict now works with the flattened input predictions = self.model.predict(config_repr_flattened_with_batch)
Key Takeaway
Keras models always expect input data to have a batch dimension as the first axis—even when you're predicting on a single sample. That extra dimension tells Keras "this is one sample in a batch" instead of interpreting the first axis as part of the sample's shape.
内容的提问来源于stack exchange,提问作者Johanna Simoens

