'Error in LinearRegression Model while using Flask

I am developing a simple linear regression model for car price prediction. In Jupyter Notebook model works fine but when called from Flask gives an error. I am using pickle library to store trained model and the same to load it in Flask

Code that I have tried:

model = pickle.load(open('CarPricePredictorModel.pkl','rb'))#read binary 

Route function:

@app.route("/predict",methods=['post'])
def predict():
    company = request.form.get('company')
    model = request.form.get('model')
    year = int(request.form.get('year'))
    fuel_type = request.form.get('fuel_type')
    kms_driven = int(request.form.get('kms_driven'))
    prediction = model.predict(pd.DataFrame([[model,company,year,kms_driven,fuel_type]],columns=['name','company','year','kms_driven','fuel_type']))
    print(prediction)
    
    print(prediction)
    return prediction

Error: AttributeError: 'str' object has no attribute 'predict'

This is my Jupyter Notebook structure

Can anybody tell where am I going wrong ?



Solution 1:[1]

Accidently I have overwritten the variable model with car model in the code.

Improvised version of code

predictionmodel = pickle.load(open('CarPricePredictorModel.pkl','rb'))#read binary 
@app.route("/predict",methods=['post'])
def predict():
    try:
        company = request.form.get('company')
        model = request.form.get('model')
        year = int(request.form.get('year'))
        fuel_type = request.form.get('fuel_type')
        kms_driven = int(request.form.get('kms_driven'))
        prediction = predictionmodel.predict(pd.DataFrame([[model,company,year,kms_driven,fuel_type]],columns=['name','company','year','kms_driven','fuel_type']))
        return str(round(prediction[0],2))

    except ValueError:
        return "Every field is mandatory" 
   
        

Thank you :).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Makarand