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

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 model is a trained classifier instance, not a numpy array. This means:
    • Load your saved trained model using joblib.load() or pickle.load() (e.g., model = joblib.load('trained_model.pkl')).
    • Or, if training in the same script, assign model to the result of fitting a classifier (e.g., model = LogisticRegression().fit(X_train, y_train)).
  • Double-check where model is defined before this function—if it's assigned to a numpy array (like model = 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 of cv.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 model variable 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 16:42:11