Flask(Python2.7)加载RandomForestClassifier遇ValueError问题求助
Hey there, I’ve run into this exact pickle/Numpy issue before with scikit-learn models on Python 2.7—let’s break down what’s going on and fix it step by step.
Why This Error Happens
The non-string names in Numpy dtype unpickling error almost always stems from version mismatches between the Numpy version used to save your iris_rfc.pkl model and the one running in your Flask environment. Python 2.7’s string handling (ASCII vs Unicode) combined with older Numpy versions can also create unpickling conflicts, especially with scikit-learn models that rely heavily on Numpy dtypes.
Step-by-Step Fixes
1. Use joblib Instead of pickle for Scikit-Learn Models
Scikit-learn explicitly recommends using joblib for saving/loading models because it’s optimized for objects with large NumPy arrays (like RandomForestClassifier). You already imported joblib—let’s put it to use:
# Replace your pickle.load line with this my_random_forest = joblib.load("iris_rfc.pkl")
2. Ensure Numpy Version Consistency
If you saved the model with a newer Numpy version but are running an older one in your Flask environment, this can trigger the dtype error. For Python 2.7, the last supported Numpy version is 1.16.6. Install it with:
pip install numpy==1.16.6
Double-check that you used this same version when training/saving your iris_rfc.pkl model.
3. Fix the Syntax Error in Your Code
You have a missing closing bracket in your predict_request line—this will throw an error before you even get to the unpickling issue. Here’s the corrected line:
predict_request = [[data['sl'], data['sw'], data['pl'], data['pw']]] # Added closing ]
Full Corrected Code
Here’s your updated Flask script with all fixes applied:
import numpy as np from flask import Flask, jsonify, abort, request import pickle from sklearn.externals import joblib # Use joblib to load the model instead of pickle my_random_forest = joblib.load("iris_rfc.pkl") app = Flask(__name__) @app.route('/api', methods=['POST']) def make_predict(): data = request.get_json(force=True) # Fixed missing closing bracket predict_request = [[data['sl'], data['sw'], data['pl'], data['pw']]] predict_request = np.array(predict_request) y_hat = my_random_forest.predict(predict_request) output = [y_hat[0]] return jsonify(results=output) if __name__ == '__main__': app.run(debug=True)
Extra Troubleshooting Tip
If you still get the error after these steps, try re-saving your RandomForestClassifier model using joblib in the same Python 2.7 environment you’re running Flask in:
# Run this in your training script (Python 2.7 with numpy 1.16.6) from sklearn.ensemble import RandomForestClassifier import joblib # ... (your training code here) rfc = RandomForestClassifier() rfc.fit(X_train, y_train) # Save with joblib joblib.dump(rfc, "iris_rfc.pkl")
This ensures the model is saved in a format fully compatible with your Flask environment.
内容的提问来源于stack exchange,提问作者Agam

