【问题标题】:Flask application not returning the predicted valueFlask 应用程序未返回预测值
【发布时间】:2020-06-09 19:55:54
【问题描述】:

我创建了一个 Flask 应用程序来部署一个简单的机器学习算法。我已经创建了 app.py 文件,model.py 文件。从命令提示符运行时,我的 model.py 文件正在编译并返回正确的结果。但是当我执行 app.py 文件时,它确实提供了 html 页面作为输出。但是当我输入输入值并单击“预测”按钮时,我无法在 html 页面上看到最终输出或预测。我在这里做错了什么?

model.py file:

import numpy as np
import pandas as pd
import pickle

dataset = pd.read_csv('hiring.csv')

X = dataset.iloc[:, :3]
print(X.columns)

y = dataset.iloc[:, -1]

from sklearn.linear_model import LinearRegression
regressor = LinearRegression()

regressor.fit(X, y)

pickle.dump(regressor, open('model1.pkl','wb'))

model = pickle.load(open('model1.pkl','rb'))
print(model.predict([[2, 8, 9]]))

app.py file:

import numpy as np
from flask import Flask, request, jsonify, render_template
import pickle

app = Flask(__name__)

model = pickle.load(open('model1.pkl','rb'))

@app.route('/',methods=["GET","POST"])
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='Employee Salary should be $ 
    {}'.format(output))

    if __name__ == "__main__":
            app.run(debug=True)

【问题讨论】:

  • if name == "main" - 此语句不应缩进。这会导致烧瓶服务无法运行。

标签: python-3.x machine-learning flask


【解决方案1】:

你已经缩进了

    if __name__ == "__main__":
        app.run(debug=True)

进入您的predict 函数

您将能够通过修复此缩进问题来​​解决您的问题。

你的代码应该是这样的:

model.py file:

import numpy as np
import pandas as pd
import pickle

dataset = pd.read_csv('hiring.csv')

X = dataset.iloc[:, :3]
print(X.columns)

y = dataset.iloc[:, -1]

from sklearn.linear_model import LinearRegression
regressor = LinearRegression()

regressor.fit(X, y)

pickle.dump(regressor, open('model1.pkl','wb'))

model = pickle.load(open('model1.pkl','rb'))
print(model.predict([[2, 8, 9]]))

app.py file:

import numpy as np
from flask import Flask, request, jsonify, render_template
import pickle

app = Flask(__name__)

model = pickle.load(open('model1.pkl','rb'))

@app.route('/',methods=["GET","POST"])
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='Employee Salary should be $ 
    {}'.format(output))

if __name__ == "__main__":
    app.run(debug=True)

【讨论】:

    猜你喜欢
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    相关资源
    最近更新 更多