基于Softmax的AI模型测试报错:一维数组转二维数组失败
Hey there! Let's walk through the issues in your test code and get your model making predictions properly.
First: The Reshape Error (The Big One)
Your error happens because you're trying to reshape an 87-element array into a 2-column matrix. 87 is an odd number—you can't split 87 elements evenly into groups of 2!
Your model expects input with shape (number_of_samples, features) (since you set input_dim=features where features=87). For a single sample, that means you need a 2D array of shape (1, 87), not (-1, 2).
Other Key Issues in Your Test Code
Let's go through the other problems step by step:
- Wrong random data creation:
random.rand(features)isn't the right way to create a numpy array of random values—you wantnp.random.rand(features)instead. - Mismatched scaler: You used
MinMaxScalerduring training, butNormalizerin testing. Always use the same scaler, and never fit it on test data (use the scaler you fitted on your training data, or re-load it if you saved it). - Outdated prediction method:
predict_classes()was removed in newer Keras/TensorFlow versions. Usepredict()followed bynp.argmax()to get class labels.
Fixed Test Code
Here's the corrected version with explanations:
# Make sure you're using numpy for random data import numpy as np from keras.models import Sequential from keras.layers import Dense from sklearn import preprocessing # Recreate the model architecture (same as training) model2 = Sequential() model2.add(Dense(400, input_dim=87, activation='tanh')) model2.add(Dense(150, activation='tanh')) model2.add(Dense(80, activation='tanh')) model2.add(Dense(40, activation='tanh')) model2.add(Dense(5, activation='softmax')) model2.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # Load the trained weights model2.load_weights("testSave.hdf5") # 1. Create a single sample with 87 features (correct numpy syntax) newData = np.random.rand(87) # 2. Reshape to (1, 87) to match model input shape (samples, features) reshaped_data = newData.reshape(1, -1) # -1 lets numpy calculate the remaining dimension # 3. Use the SAME scaler as training (MinMaxScaler), don't fit on test data! # Note: You should save your training scaler during preprocessing, but if not, reinitialize it properly scaler = preprocessing.MinMaxScaler(feature_range=(0, 1)) # Important: If you have your original training X, use scaler.fit(X) here—don't fit on newData! # For example: scaler.fit(rescaledX) # from your training code # 4. Transform the test data newDataN = scaler.transform(reshaped_data) # 5. Make prediction (replace predict_classes with predict + argmax) predictions = model2.predict(newDataN) predicted_class = np.argmax(predictions, axis=1) print("Predicted Class: ", predicted_class[0])
Bonus Tip: Save the Entire Model Instead of Just Weights
Instead of saving only weights, save the full model architecture + weights together with model.save("my_model.h5"). Then loading is way simpler:
from keras.models import load_model model2 = load_model("my_model.h5")
This avoids having to redefine the model architecture manually, which reduces mistakes.
内容的提问来源于stack exchange,提问作者RonanD1807

