Flask调用AI模型时出现numpy.ndarray无predict属性问题
Solution to AttributeError: 'numpy.ndarray' has no attribute 'predict'
The error occurs because your model variable is a numpy array, not a trained machine learning model object (e.g., scikit-learn's LogisticRegression, RandomForestClassifier, etc.). Numpy arrays don't have a predict() method—only trained model instances do. Additionally, your CountVectorizer usage has a critical mistake that will break predictions even if the model issue is fixed.
Key Fixes
1. Correct the model variable
- Ensure
modelis a trained classifier instance, not a numpy array. This means:- Load your saved trained model using
joblib.load()orpickle.load()(e.g.,model = joblib.load('trained_model.pkl')). - Or, if training in the same script, assign
modelto the result of fitting a classifier (e.g.,model = LogisticRegression().fit(X_train, y_train)).
- Load your saved trained model using
- Double-check where
modelis defined before this function—if it's assigned to a numpy array (likemodel = some_array), that's the root cause of the AttributeError.
2. Fix CountVectorizer usage
- Using
cv.fit_transform()on new input creates a fresh vocabulary that doesn't match the one used to train your model. This will produce feature arrays incompatible with the model. Instead:- Reuse the same CountVectorizer instance that was used during training (load it if saved, or pass it to the predict function).
- Call
cv.transform()instead ofcv.fit_transform()for new data points.
Corrected Code Example
import joblib def predict(): # Load trained model and vectorizer (replace paths with your actual files) model = joblib.load('trained_phishing_model.pkl') cv = joblib.load('count_vectorizer.pkl') email_text = "hello world" # Use transform() to apply the existing vocabulary email_features_array = cv.transform([email_text]) prediction = model.predict(email_features_array) probability = model.predict_proba(email_features_array) if prediction[0] == 1: result = 'Phishing' probability_score = probability[0][1] * 100 else: result = 'Legitimate' probability_score = probability[0][0] * 100 print(f"{result} ({probability_score:.2f}%)")
Notes
- The decoding issue you suspected is not related to this error. The problem is entirely about the
modelvariable type and incorrect vectorizer usage. - If you didn't save the vectorizer, ensure you reuse the exact instance from training (don't initialize a new CountVectorizer inside the predict function).
内容的提问来源于stack exchange,提问作者Azizener
相关产品推荐
相关产品推荐

