更新时间:2023-11-22 12:36:52
Pickles 不一定跨 scikit-learn 版本兼容,因此这种行为是预期的(并且不支持用例).有关更多详细信息,请参阅 https://scikit-learn.org/dev/modules/model_persistence.html#model-persistence.用 joblib 替换 pickle.举例:
>>>从 sklearn 导入 svm>>>从 sklearn 导入数据集>>>clf = svm.SVC()>>>X, y= datasets.load_iris(return_X_y=True)>>>clf.fit(X, y)SVC()>>>从 joblib 导入转储,加载>>>转储(clf,打开('文件名.joblib','wb'))>>>clf2 = load(open('filename.joblib','rb'))>>>clf2.predict(X[0:1])数组([0])>>>y[0]0I'm trying to learn how to create a machine learning API with Flask, however, following this tutorial, the following error appears when I type the command python app.py
:
Traceback (most recent call last):
File "C:\Users\Breno\Desktop\flask-api\app.py", line 24, in <module>
model = p.load(open(modelfile, 'rb'))
ModuleNotFoundError: No module named 'sklearn.tree.tree'
My code:
from flask import Flask, request, redirect, url_for, flash, jsonify
import numpy as np
import pickle as p
import pandas as pd
import json
#from sklearn.tree import DecisionTreeClassifier
app = Flask(__name__)
@app.route('/api/', methods=['POST'])
def makecalc():
j_data = request.get_json()
prediction = np.array2string(model.predict(j_data))
return jsonify(prediction)
if __name__ == '__main__':
modelfile = 'models/final_prediction.pickle'
model = p.load(open(modelfile, 'rb'))
app.run(debug=True,host='0.0.0.0')
Could someone help me please?
Pickles are not necessarily compatible across scikit-learn versions so this behavior is expected (and the use case is not supported). For more details, see https://scikit-learn.org/dev/modules/model_persistence.html#model-persistence. Replace pickle by joblib. by example :
>>> from sklearn import svm
>>> from sklearn import datasets
>>> clf = svm.SVC()
>>> X, y= datasets.load_iris(return_X_y=True)
>>> clf.fit(X, y)
SVC()
>>> from joblib import dump, load
>>> dump(clf, open('filename.joblib','wb'))
>>> clf2 = load(open('filename.joblib','rb'))
>>> clf2.predict(X[0:1])
array([0])
>>> y[0]
0