How to Deploy Machine Learning models in Azure Cloud with the help of Python and Flask?

This article was published as a part of the Data Science Blogathon.

Introduction

As a Machine learning engineer or a Data scientist, it is important to show your work to the intended public without any hassle. Although you might have created a very good model for the predictive analysis, if you fail to demonstrate the work that you have created to the public then your hard work is of no use. A person should be able to get the desired output when he/she is using your ML model for their purpose. Giving a bunch of codes to a naive person is an act of foolish and you don’t want to be one.

So, there should be a way out so that you get to display your work to the public. The answer to this problem is the deployment of your work in the form of web apps. This helps in displaying your work to the public and not getting deep down into the backend of the same. Once you deploy the code successfully then there is no need to access the backend and people can get their desired outcome by inputting values in the front end.

For deploying the Machine learning model we will be concentrating the things centered on Python programming language and the deployment tools for this will be Flask and Microsoft Azure. The main purpose is to create a web application that will run 24×7 hosted on a cloud-based server. So, without further wasting of time let’s start:

Note: Here we will be using the famous Iris flower dataset and we will be storing our work on Github and deploy the same to Azure via Github.

Creating an ML model

The first and foremost thing to do is to create a Machine learning model with the name model.py and then pickling the model in the local system using either Pickle or Joblib. So let’s see how to create a simple Machine learning model of the Iris flower dataset using Support Vector Machine Classification:

Model.py

#importing the necessary libraries
from pyforest import *
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
import joblib
from sklearn.datasets import load_iris
#loading the dataset into a pandas dataframe
data= load_iris()
data.feature_names
df= pd.DataFrame(data.data)
df.head()
#renaming the columns with the actual column names that is sepal and petal width and length
df.columns= data.feature_names
data.target_names
#inserting the target feature in the dataset
df["target"]= data.target
#getting our X and y to feed it into the ML model
X= df.drop("target, axis=1)
y= df.target

#splitting the dataset into train and test
X_train,X_test,y_train,y_test= train_test_split(X,y, test_size=0.2, random_state=42)

#loading the SVC model by creating an object of the class
model= SVC()
#training the model
model.fit(X_train,y_train)
#making predictions
y_pred= model.predict(X_test)
#pickling the model
joblib.dump(model, "model.pkl")
c= [2,3,3,4]
from_jb= joblib.load("model.pkl")
from_jb.predict([c])

Creating Flask App

After creating the model.py file and pickling the same the next step is to create a Flask web app with the name app.py and to create this we need to follow the below-mentioned steps. Also, note that the model.py, model.pkl, and app.py should be present in the same directory of the computer. The reason for selecting Flask is that it is a very light web framework that helps in creating web apps with minimal lines of code.

Although there are many frameworks for Python for creating web apps like Django, Web2py, Grok, TurboGears, etc, still Flask helps us in creating apps with less involvement of time and also is a good tool for beginners who want to learn building web applications. Also, the framework depends completely on Python for coding related stuff rather than relying on other dependent tools. To learn the insights of this amazing library one must have good knowledge related to Python, a bit of HTML and CSS, and a Database management system if any kind of data-related work is involved. So, if you have the knowledge of these three things then you are ready to code in Flask.

App.py

#importing the necessary libraries for deployment
from flask import Flask, request, jsonify, render_template
import joblib
from pyforest import *
#naming our app as app
app= Flask(__name__)
#loading the pickle file for creating the web app
model= joblib.load(open("model.pkl", "rb"))
#defining the different pages of html and specifying the features required to be filled in the html form
@app.route("/")
def home():
return render_template("index.html")
#creating a function for the prediction model by specifying the parameters and feeding it to the ML model
@app.route("/predict", methods=["POST"])
def predict():
#specifying our parameters as data type float
int_features= [float(x) for x in request.form.values()]
final_features= [np.array(int_features)]
prediction= model.predict(final_features)
output= round(prediction[0], 2)
return render_template("index.html", prediction_text= "flower is {}".format(output))
#running the flask app
if __name__= "__main__"
app.run(debug=True)

Note: Please note that use any IDE of your choice say Sublime, VS Code, Atom, Spyder, etc. But, don’t use any IPython notebook for creating the web app because these notebooks do not support Flask. Flask only supports .py files and not .ipynb files.

Creating the Frontend through HTML

Now, the next step is to create an HTML file as mentioned earlier that it is a prerequisite for creating a web app in Flask with the name index.html contained within folder templates under the same directory. To view this file just follow the below link:

Index.html

The HTML form details are in the following link:

https://raw.githubusercontent.com/Sagu12/Azure-deploy/main/templates/index.html

The HTML form we have created is a very simple one that contains only the feature names that are present in the dataset and the prediction output that we want the form to display. There is a primary button which when clicked gives the desired output. You can add various colors and background images also as per your desire to make the form more beautiful.

Once the 3 files are created the last step is to create a requirements.txt file that will contain all the necessary library details being used in the prediction. To create this we will be using Command Prompt and pipreqs library. Just open CMD under the same directory and type

pipreqs your path of the files

Once done your requirements.txt file is ready. Now you just need to upload the necessary files in Github under a fresh repository containing a README.md file, .gitignore file, and a license file. Upload your app.py, model.pkl, requirements.txt, and templates folder with index.html to the repository.

Note: If you don’t have certain libraries that are being used here then you can download the same using your Command Prompt or Anaconda Prompt with the help of pip.

pip install name of the library

Wait for the installation to finish. Once the installation finishes then you are good to go.

Deployment to Azure Cloud

After finishing off with this just open portal.azure.com and then log in to your Microsoft account if you have one or just create an account as it takes only a few minutes to do the same. Once you are in the Azure portal these are the following steps that you need to follow to deploy your Flask app contained in Github:

  1. Click on Create a resource option present at the extreme left-hand side and after that click on Web App present in the options section.
  2. Make sure that your subscription is a free version. Now create a new Resource Group with a unique name.
  3. After this give the name of your app and then click on the Code section if you have a raw code and Docker if you have containerized your app. Here I will be using the Code option. After this just select your runtime that is the Python version you worked on while creating the model.
  4. Click on any specific region of your choice and then make sure that you have selected the free F1 version from the sku and size option.
  5. Once all this is done you are good to go to the deployment stage by just clicking on the Review and Create option.
  6. After your web app is created the next step is to deploy your application in Azure through Github. Click on Go to Resource and then Deployment Center.
  7. Once done just select the Github option and click on Continue.
  8. Select App Service Build Service and hit Continue. The next thing is to select your repository name and then click on Continue and then Finish.
  9. Congratulations, your deployment is under process, and once finished you can view your app by just clicking on the Overview section and clicking on the link that got generated. You can check my simple app by clicking to this link- https://simpleirisapp.azurewebsites.net

Conclusion

So, this is how one can deploy any Machine learning and Deep learning app very easily to Azure and can share his/her work globally. Go try it yourself and create wonders.

You can also read this article on our Mobile APP Get it on Google Play

Related Articles

Author: admin

Leave a Reply

Your email address will not be published.