Mar 8, 2022

How to deploy ML model using flask

Updated: May 11, 2022

In this blog we will discuss how to build the machine learning classification model using the historical data. If we build the machine learning model after that we will see how to deploy it using flask. Lets See

Machine learning is the technique that is widely used for prediction. There are a lot of machine learning algorithms available in various libraries which can be used for prediction.

We have to import required libraries which will be used in this model.

#import libraries
 
import pandas as pd
 
from sklearn.tree import DecisionTreeClassifier
 
from sklearn.metrics import
 
accuracy_score,classification_report,confusion_matrix
 
from sklearn.metrics import r2_score
 
from sklearn.metrics import mean_squared_error

Get the data

Code :

def read_data(data):
 
df = pd.read_csv(data)
 
return df
 

 
file_loc = "diabetes.zip"
 
df_diabetes = read_data(file_loc)

Preprocess data

The dataset contains 8 attributes and the target column is Outcome which shows whether the patient is diabetic or not. Firstly we remove the missing values if they are present in the dataset.

#drop all na value from the data set
 
df_diabetes.dropna(inplace=True)

Build the ML model

After cleaning the data, the data is ready to feed into the machine learning algorithm. First, separate the attributes and label data, then we split the dataset into a training set and testing set.

Code :


 
# Split the data set into train and test data
 
from sklearn.model_selection import train_test_split
 

 
X = df_diabetes.drop("Outcome",axis=1)
 
y = df_diabetes["Outcome"]
 

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

We used a Logistic regression machine learning algorithm to build the prediction model. We fed the training data to train the model. Once we trained the model mode, test data was used to check the accuracy of rate of the model. We achieve the accuracy rate of this model is 82 %

Code :

from sklearn.linear_model import LogisticRegression
 
reg = LogisticRegression()
 
reg.fit(X_train,y_train)
 
y_pred=reg.predict(X_test)
 

 
print(accuracy_score(y_test,y_pred)*100)

Output :

Now we save the model using the following code

code :

# Creating a pickle file for the classifier
 
filename = 'model.pkl'
 
pickle.dump(reg, open(filename, 'wb'))

Now flask, flask is the python framework which is used for developing the website. It is very easy to make a REST API using python.