【发布时间】:2020-05-03 06:49:43
【问题描述】:
这是我第一次尝试部署机器学习应用程序,也是我第一次使用flask。本质上,用户将在 html 页面上填写表单,表单的输入将用作机器学习模型的输入,该模型保存在下面代码中的 pickle 文件 model.pkl 中.我遇到了一个我似乎无法克服的障碍..
每次我从 index.html 提交并发布到 result.html 时,我都会收到 404 错误。
script.py:
#importing libraries
import os
import numpy as np
import flask
import pickle
from flask import Flask, render_template, request
app=Flask(__name__)
@app.route('/')
@app.route('/index')
def index():
return flask.render_template('index.html')
def ValuePredictor(to_predict_list):
to_predict = np.array(to_predict_list).reshape(1,12)
loaded_model = pickle.load(open("model.pkl","rb"))
result = loaded_model.predict(to_predict)
return result[0]
@app.route('/result',methods = ['POST'])
def result():
if request.method == 'POST':
to_predict_list = request.form.to_dict()
to_predict_list=list(to_predict_list.values())
to_predict_list = list(map(int, to_predict_list))
result = ValuePredictor(to_predict_list)
if int(result)==1:
prediction='Income more than 50K'
else:
prediction='Income less that 50K'
return render_template("result.html",prediction=prediction)
index.html:
<html>
<body>
<h3>Income Prediction Form</h3>
<div>
<form action="/result.html" method="POST">
<label for="age">Age</label>
<input type="text" id="age" name="age">
<br>
<label for="edu">Education</label>
<select id="edu" name="edu">
<option value="0">High School</option>
<option value="1">College Degree</option>
</select>
<br>
<label for="martial_stat">Marital Status</label>
<select id="martial_stat" name="martial_stat">
<option value="0">not married</option>
<option value="1">married</option>
</select>
<br>
<label for="gender">Gender</label>
<select id="gender" name="gender">
<option value="0">Female</option>
<option value="1">Male</option>
</select>
<br>
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>
result.html:
<html>
<body>
<h1> {{ prediction }}</h1>
</body>
</html>
我似乎无法弄清楚这一点。我的代码似乎从未到达result() 函数的第一行。一旦我从index.html http://127.0.0.1:5000/result.html 提交,就会抛出 404 错误。有什么建议吗?
【问题讨论】:
-
尝试提交到
/result而不是/result.html