from sklearn.datasets import load_iris
x,y=load_iris(return_X_y=True,as_frame=True)
x.shape,y.shape
>>> ((150, 4), (150,))
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2)
x_train.shape,y_train.shape,x_test.shape,y_test.shape
>>> ((120, 4), (120,), (30, 4), (30,))
from sklearn.neighbors import KNeighborsClassifier
model1=KNeighborsClassifier()
model1.fit(x_train,y_train)
model1.score(x_test,y_test)
>>> 0.9666666666666667
import pickle
path=r'savemodel.sav'
pickle.dump(model,open(path,'wb'))
from flask import Flask, render_template, request
import pickle
app = Flask(__name__)
model = pickle.load(open('savemodel.sav', 'rb'))
@app.route('/')
def home():
result = ''
return render_template('index.html', **locals())
@app.route('/predict', methods=['POST', 'GET'])
def predict():
s_length = float(request.form['s_length'])
s_width = float(request.form['s_width'])
p_length = float(request.form['p_length'])
p_width = float(request.form['p_width'])
result = model.predict([[s_length, s_width, p_length, p_width]])[0]
return render_template('index.html', **locals())
if __name__ == '__main__':
app.run(debug=True, host='127.0.0.1', port=9090)
以字典类型返回当前位置的全部局部变量。
def fun(a,b):
c=1
print(locals())
fun(22,33)
>>> {'a': 22, 'b': 33, 'c': 1}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/predict" method="POST">
s_length:<input type="text" name="s_length"/><br>
s_width:<input type="text" name="s_width"/><br>
p_length:<input type="text" name="p_length"/><br>
p_width:<input type="text" name="p_width"/><br>
class:{{result}}<br>
<input type="submit" value="predict"/>
</form>
</body>
</html>
总结:本案例参考youtube上一个博主的视频,很简单的一个案例,代码足够简洁,但是实现了模型部署的基本功能,后续可以在此基础上部署更加复杂的模型,优化方向有以下几点:css渲染、交互功能等