Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Flask中的机器学习Web应用程序错误_Python_Flask_Heroku - Fatal编程技术网

Python Flask中的机器学习Web应用程序错误

Python Flask中的机器学习Web应用程序错误,python,flask,heroku,Python,Flask,Heroku,我是机器学习模型部署的新手,一直试图在Flask和Heroku中部署一个简单的汽车价格预测机器学习模型。使用sklearn管道和变压器制作了模型。该代码在Jupyter笔记本上运行良好。 通过Github在Heroku中部署它,显示构建成功。但是,在启动应用程序时,它会显示应用程序错误。 Flask的app.py文件代码似乎有问题。任何帮助或见解都会非常有用。多谢各位 Jupyter笔记本代码: import numpy as np import pandas as pd import matp

我是机器学习模型部署的新手,一直试图在Flask和Heroku中部署一个简单的汽车价格预测机器学习模型。使用sklearn管道和变压器制作了模型。该代码在Jupyter笔记本上运行良好。 通过Github在Heroku中部署它,显示构建成功。但是,在启动应用程序时,它会显示应用程序错误。 Flask的app.py文件代码似乎有问题。任何帮助或见解都会非常有用。多谢各位

Jupyter笔记本代码:

import numpy as np
import pandas as pd
import matplotlib as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import StandardScaler

data = pd.read_csv('car data.csv')
data['current_year'] = 2020
data['car_age'] = data['current_year'] - data['Year']

num_features = [col for col in data.columns if data[col].dtype != 'O' and col != 'Selling_Price']
cat_features = [col for col in data.columns if data[col].dtype == 'O']

X= data.drop(['Selling_Price'], axis=1)
y = data['Selling_Price']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=42)

num_transformer = Pipeline(steps = [('scaler', StandardScaler())])
cat_transformer = Pipeline(steps =[('OneHot', OneHotEncoder(handle_unknown='ignore'))])

preprocessor = ColumnTransformer(transformers = [('numerical_transformer', num_transformer, num_features),
                                                ('categorical_transformer', cat_transformer, cat_features)])

from sklearn.ensemble import RandomForestRegressor
rf = RandomForestRegressor()

grid_param = {'n_estimators' :[100, 200, 500, 800, 1000]}

grid = GridSearchCV(estimator = rf, param_grid= grid_param)

model = Pipeline(steps= [('preprocessor',preprocessor), ('grid_regressor', grid)])
model.fit(X_train, y_train)

y_predict = model.predict(X_test)

from sklearn.metrics import mean_absolute_error, mean_squared_error

MAE = mean_absolute_error(y_test, y_predict)
MSE = mean_squared_error(y_test, y_predict)
RMSE = np.sqrt(MSE)

import pickle
file = open('regression_model.pkl', 'wb')
pickle.dump(model, file)
烧瓶的app.py文件代码:

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

model = pickle.load(open('regression_model.pkl', 'rb'))   
app = Flask(__name__)
@app.route('/', methods=['GET'])
def Home():
    return render_template('index.html')

@app.route("/predict", methods= ['POST']   
def predict(): 
    if request.method == 'POST':
        Year = int(request.form['Year'])
        Selling_Price = float(request.form['Selling_Price'])
        Present_Price = float(request.form['Present_Price'])
        Kms_Driven = int(request.form['Kms_Driven'])
        Owner = int(request.form['Owner'])
        car_age = 2020 - Year
        
        Fuel_Type_Petrol = request.form['Fuel_Type_Petrol']
        if(Fuel_Type_Petrol=='Petrol'):
                Fuel_Type_Petrol=1
                Fuel_Type_Diesel=0
        elif (Fuel_Type_Petrol =='Diesel'):
            Fuel_Type_Petrol=0
            Fuel_Type_Diesel=1
        else:
            Fuel_Type_Petrol=0
            Fuel_Type_Diesel=0
            
        Seller_Type_Individual = request.form['Seller_Type_Individual']
        if(Seller_Type_Individual =='Individual'):
            Seller_Type_Individual=1
        else:
            Seller_Type_Individual=0
            
            
        Transmission_Mannual=request.form['Transmission_Mannual']
        if(Transmission_Mannual=='Mannual'):
            Transmission_Mannual=1
        else:
            Transmission_Mannual=0
            
        data = [Selling_Price, Present_Price, Kms_Driven, Owner, Fuel_Type_Petrol, Fuel_Type_Diesel, Seller_Type_Individual, Transmission_Mannual, car_age]
                    
        prediction = model.predict([data])          
        output = round(prediction[0], 2)
        
        if output <0:
            return render_template('index.html', prediction_texts="Sorry you cannot sell this car")
        else:
            return render_template('index.html', prediction_texts= "You can sell the car at {}".format(output))
        
    else:
        render_template('index.html')
    
if __name__ == '__main__':
    app.run(debug=True)
从烧瓶导入烧瓶,呈现模板,请求
导入jsonify
进口泡菜
将numpy作为np导入
导入sklearn
model=pickle.load(打开('regression_model.pkl','rb'))
app=烧瓶(名称)
@app.route('/',方法=['GET'])
def Home():
返回渲染模板('index.html')
@app.route(“/predict”,方法=['POST']
def predict():
如果request.method==“POST”:
年份=整数(请求表['Year'])
销售价格=浮动(申请表['销售价格])
当前价格=浮动(申请表[‘当前价格’])
Kms_驱动=int(request.form['Kms_驱动']))
Owner=int(request.form['Owner'])
车龄=2020年-年
燃料类型汽油=申请表[“燃料类型汽油”]
如果(燃油类型汽油==‘汽油’):
燃油类型汽油=1
燃料类型柴油=0
elif(燃油类型汽油=‘柴油’):
燃油类型汽油=0
燃料类型柴油=1
其他:
燃油类型汽油=0
燃料类型柴油=0
卖方类型个人=请求。表格['卖方类型个人']
如果(卖方类型个人==‘个人’):
卖方\类型\个人=1
其他:
卖方\类型\个人=0
传输方式=请求。表单['Transmission\u Mannual']
如果(传输方式=='Mannual'):
变速箱手动=1
其他:
变速箱手动=0
数据=[销售价格、当前价格、公里数、车主、燃油型汽油、燃油型柴油、卖方型个人、变速箱手动、车龄]
预测=模型。预测([数据])
输出=四舍五入(预测[0],2)

如果输出,您能否提供接收到的错误代码?错误代码=H10 desc=“App crash”method=GET path=“/”不是那样,请显示实际错误。您在cli run
heroku restart
中尝试过的堆栈溢出是否有帮助?