无法从"X:\\Software\\anaconda\\Scripts\\flask-script.py"获取<模块"__main__"上的属性"



我创建了一个flask应用程序,它引用了一个用于预测的pickle文件。在pickle文件中,管道如下所示:

pipeline = Pipeline([
('bow', CountVectorizer(analyzer=text_process)),  # strings to token integer counts
('tfidf', TfidfTransformer()),  # integer counts to weighted TF-IDF scores
('classifier', MultinomialNB()),  # train on TF-IDF vectors w/ Naive Bayes classifier])
pickle.dump(pipeline, open('model.pkl', 'wb'))
model= pickle.load(open('model.pkl', 'rb'))

然后我将烧瓶定义如下:

import numpy as np
def text_process(mess):
nopunc = [char for char in mess if char not in string.punctuation]
nopunc = ''.join(nopunc)    
return [word for word in nopunc.split() if word.lower() not in stopwords.words('english')]
import pickle
from nltk.corpus import stopwords
import string
from flask import Flask, request, jsonify, render_template
app = Flask(__name__)
model = pickle.load(open('model.pkl', 'rb'))
@app.route('/')
def home():
return render_template('index.html')
@app.route('/predict',methods=['POST'])
def predict():
'''
For rendering results on HTML GUI
'''
int_features = [ request.form.values()]
prediction = model.predict(int_features)
return render_template('index.html', prediction_text='Classification is {}'.format(prediction))
@app.route('/predict_api',methods=['POST'])
def predict_api():
'''
For direct API calls throught request
'''
data = request.get_json(force=True)
prediction = model.predict([np.array(list(data.values()))])
output = prediction[0]
return jsonify(output)
if __name__ == "__main__":
app.run(debug=True)

但是,当我使用flask run命令执行flask时,或者当我使用azure应用程序服务部署它时,"text_process"函数不会进入内存,我得到以下错误

"Can't get attribute 'text_process' on <module '__main__' from 'X:\Software\anaconda\Scripts\flask-script.py'>"

但同时,如果我使用命令";python app.py";,它运行良好。你能帮我处理这个吗

创建一个自定义的unpickler将解决问题

class MyCustomUnpickler(pickle.Unpickler):
def find_class(self, module, name):
if module == "__main__":
module = "app"
return super().find_class(module, name)
with open('model/model.pkl', 'rb') as f:
unpickler = MyCustomUnpickler(f)
model = unpickler.load()

相关内容

最新更新