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

Keras分类模型输入形状不匹配问题求助

Fixing Keras Input Shape Mismatch for Classification

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.

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:

  1. 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'))
    
  2. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:42:18