Deploy a machine learning model using flask
Tags: machinelearning, python, flask, datascience
Published: 2020-08-21 16:57:25

![Disease-Prediction](https://user-images.githubusercontent.com/45433443/90904255-a946d500-e3ec-11ea-9a53-d28d5d81de75.gif)
**As a beginner in machine learning, it might be easy for anyone to get enough resources about all the algorithms for machine learning and deep learning but when I started to look for references to deploy ML model to production I did not find really any good resources which could help me to deploy my model as I am very new to this field. So, when I succeeded to deploy my model using Flask on Heroku, I decided to write an article to help others to simply deploy their model. I hope it will help:)**

[Live Demo](https://dpredict.herokuapp.com/)
In this article, we are going to use simple logistic regression algorithm with scikit-learn for simplicity, we will use Flask as it is a very light web framework. We will create two files,

1. model.py
2. app.py

In a model.py file, we will develop and train our model, in an app.py, we will code to handle POST requests and return the results.
1. model.py

In this file, we will develop our ML model and train it. We will predict the heart disease of a person on the Basis of Symptoms. You can find the dataset [here](https://github.com/mjmaurya/heart-disease-predictor/blob/master/heart-data.csv).

```
import pandas as pd
import sys
import numpy as np
import pickle
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
```
Importing the libraries that we are going to use to develop our model. NumPy and pandas to manipulate the matrices and data respectively, sklearn.model_selection for splitting data into train and test set and sklearn.linear_model to train our model using LogisticRegression. pickle to save our trained model to the disk.
```
df=pd.read_csv('heart-data.csv')
x=df.drop('target', axis=1)
y=df['target']
```
We have imported the dataset using pandas and separated the features and label from the dataset.
```
train_x,valid_x,train_y,valid_y=train_test_split(x,y,test_size=0.3,random_state=35)
```
In this section, we have split our data into train and test size of 0.70 and 0.30 respectively using train_test_split from sklearn.
```
logr=LogisticRegression()
logr.fit(train_x,train_y)
result=logr.predict(valid_x)
```
The object is instantiated as a logr of the class LogisticRegression() and trained using tarin_x and train_y. Latter the predicted results are stored in the result.
```
pickle.dump(logr,open('model.pkl','wb'))
model=pickle.load(open('model.pkl','rb'))
```
We will save our trained model to the disk using the pickle library. Pickle is used to serializing and de-serializing a Python object structure. In which python object is converted into the byte stream.

In our case, we want to save our model so that it can be used by the server. So we will save our object logr to the file named model.pkl.

Here, our model.py is ready to train and save the model. The whole code of model.py is as follows.
```
# Importing the libraries
import pandas as pd
import sys
import numpy as np
import pickle
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression

# Importing the dataset
df=pd.read_csv('heart-data.csv')
df.rename(columns={"class":"target"},inplace=True)
df['target'].replace(['absent','present'],[0,1],inplace=True)
df=pd.get_dummies(df)
x=df.drop('target', axis=1)
y=df['target']
#Splitting the dataset into the Training set and Test set
train_x,valid_x,train_y,valid_y=train_test_split(x,y,test_size=0.3,random_state=35)

# Fitting Simple Linear Regression to the Training set
logr=LogisticRegression()
logr.fit(train_x,train_y)
pickle.dump(logr,open('model.pkl','wb'))
model=pickle.load(open('model.pkl','rb'))

# Predicting the Test set results
result=model.predict(valid_x)
print(result)
```
2.app.py

In this file, we will use the flask web framework to handle the POST requests that we will get from the UX.

Importing the methods and libraries that we are going to use in the code.
```
from flask import Flask
from flask import render_template,redirect,request
import pandas as pd
import sys
import numpy as np
import pickle
```
**In the following section of the code, we have created the instance of the Flask() and loaded the model into the model.**
```
app=Flask(__name__)
    
model=pickle.load(open('model.pkl','rb'))
```
Here, we have a method result(). In which resut method gets the data from the form passed by the users. model.predict() method takes input from the form and converts it into 2D numpy array the results are stored into the variable named result and we return this variable.
```
@app.route("/result", methods = ['POST', 'GET'])
def result():
    if request.method=='POST':
#geting data from html form
        age=request.form["age"]
        .
        .
# after geting data appending in a list
        lst=list()
        lst.append((age))
        lst.append((sex))
        lst.append((chest))
        lst.append((resting_blood_pressure))
        lst.append((serum_cholestoral))
        lst.append((fasting_blood_sugar))
        lst.append((resting_electrocardiographic_results))
        lst.append((maximum_heart_rate_achieved))
        lst.append((exercise_induced_angina))
        lst.append((oldpeak))
        lst.append((slope))
        lst.append((number_of_major_vessels))
        lst.append((thal))
# converting list into 2 D numpy array
        ans=model.predict([np.array(lst,dtype='int64')])
        result=ans[0]
        return render_template("result.html",result=result)

    else:
        return render_template("index.html")
```
Finally, we will run our app by the following code section. Here I have used port 5000 and have set debug=True since if we get any error we can debug it and solve it.
```

if __name__=='__main__':
    app.run(port=5000,debug=True)
```
You can find all the coding in my Github repository, [heart-disease-predictor](https://github.com/mjmaurya/heart-disease-predictor).
Don’t hesitate to flow your ideas in the comment section below.

Thank you :)