'ML model EOFError while reading pickled file in spyder

So i have made a RandomForest model in jupyter notebook and as to deploy it i was using flask in spyder. However it turns out that i am getting the EOF error ie file is empty. can someone please help i am sharing the code below

jupyter model building and pickle:

x = df[['AgeCategory','BMI','SleepTime','MentalHealth','PhysicalHealth','GenHealth','Smoking']]
y = df['HeartDisease']
x_train, x_test, y_train, y_test =train_test_split(x,y,test_size=0.2, random_state=42)

clf = RandomForestClassifier(n_estimators = 100)
clf.fit(x_train, y_train)
clf_y_predict = clf.predict(x_test)

This image shows me building the model

After that i move on to the pickle writing:

import pickle

file = open('random_forest_classification_model.pkl','wb')

pickle.dump(clf,file)

enter image description here

the code on spyder to read where i am getting an eof error on line 18 is:

# -*- coding: utf-8 -*-
"""
Created on Fri May  6 19:31:28 2022

@author: ADWAIT SAWANT
"""

from flask import Flask, render_template, request
import pandas
import jsonify
import requests
import pickle
import numpy as np
import sklearn
from sklearn.preprocessing import StandardScaler
app = Flask(__name__)
model = pickle.load(open('random_forest_classification_model.pkl', 'rb'))

@app.route('/',methods=['GET'])

@app.route("/predict", methods=['POST'])
def predict():
    if request.method=='POST':
        BMI = int(request.form['BMI'])
        AgeCategory = int(request.form['AgeCategory'])
        SleepTime = int(request.form['SleepTime'])
        PhysicalHealth = int(request.form['PhysicalHealth'])
        MentalHealth = int(request.form['MentalHealth'])
        GenHealth = int(request.form['GenHealth'])
        Smoking = int(request.form['smoking'])
    
    














`prediction=model.predict([[BMI,AgeCategory,SleepTime,PhysicalHealth,MentalHealth,GenHealth,Smoking]])`

    output=round(prediction[0],2)
    
    if output<0:
        return render_template('index2.html',prediction_texts="Sorry couldn't predict")
    else:
        return render_template('index2.html',prediction_text="{}".format(output))
else:
    return render_template('index2.html')

if name=="main": app.run(debug=True)

or the image is: enter image description here



Sources

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

Source: Stack Overflow

Solution Source