单个flask框架中的多个pickl模型,并预测web API中的输出



我制作了一个flask web框架,它读取单个pickl模型并预测html文件中的输出。但是现在我想在我的Web API中加载多个预测和显示结果的pickl文件。

import numpy as np
from flask import Flask, request, jsonify, render_template
import pickle
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():
int_features = [int(x) for x in request.form.values()]
final_features = [np.array(int_features)]
prediction = model.predict(final_features)
output = round(prediction[0], 2)
return render_template('index.html', prediction_text='Water prediction should be {} litres'.format(output))

if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)

你已经完成了所有的艰苦工作!
您可以将现有代码扩展为多个pickle文件,如下所示:

list_of_model_pickles = ['model1.pkl', 'model2.pkl', 'model3.pkl', 'model4.pkl'] # add any model pickle file here
prediction_text_all_pickles = 'Water prediction should be:n'
for model_file in list_of_model_pickles:
f_pickle = open(model_file, 'rb')
model = pickle.load(f_pickle)
prediction = model.predict(final_features)
output = round(prediction[0], 2)
f_pickle.close()
prediction_text_all_pickles += f' {output} litres according to model in file {model_file}. n'
# At this point (when the entire loop finishes processing all your pickle files) your prediction_text_all_pickles is correctly populated with required information.
return render_template('index.html', prediction_text=prediction_text_all_pickles)

最新更新