Keras二分类报错:期望输入形状(8,)却得到(5,),求技术帮助
Hey there, let's work through this shape mismatch error you're hitting. The error says your model expects an input shape of (8,) but received an array with shape (5,), even though you set input_dim=5 and your training data is shaped (116020, 5). Here are the most likely causes and fixes to check:
1. Confirm your model's actual input layer configuration
First, make sure your model's input layer is really set to accept 5 features—sometimes code can get overridden without you noticing. Add this line right after defining your model to verify:
print(model.summary())
Look at the first dense layer (dense_1) — its Input Shape should show (None, 5). If it displays (None, 8) instead, that means somewhere in your code, the input dimension got changed after you initially set input_dim=5. Maybe you redefined the model later, or copied code from a previous project that used 8 features?
2. Double-check the data you're passing to model.fit()
It's easy to accidentally feed the wrong dataset during training. Right before calling model.fit(), print the shape of your training data to confirm:
print("X_Train shape:", X_Train.shape) print("Y_Train shape:", Y_Train.shape)
Ensure X_Train is still (116020, 5). If it's not, check your preprocessing steps—did you run feature selection, PCA, or a scaling transformer that accidentally altered the number of features? For example, did you fit a SelectKBest with k=8 and apply it to X_Train without realizing?
3. Check for accidental loading of an old model
If you're using load_model() to bring in a previously saved model, that old model might have been built for 8 features. Even if you redefine the model with input_dim=5, loading an old model will overwrite your current architecture. Make sure you're not loading a saved model before training, or if you do, confirm the saved model's input shape matches your current data.
4. Rule out unintended reshaping of your data
Did you reshape your input data anywhere in the code? A line like X_Train = X_Train.reshape(-1, 8) would silently change the feature count. Search your code for any reshape calls or operations that might modify the number of features in X_Train.
Once you spot which of these is causing the mismatch, adjusting the code to align the model's input shape with your data's shape should fix the error.
内容的提问来源于stack exchange,提问作者TigSh

