Complete Guide To Model Deployment Using Flask in Google Cloud Platform
In real-world, training and model prediction is one phase of the machine learning life-cycle. But it won’t be helpful to anyone other than the developer as no one will understand it. So, we need to create a front end graphical tool that users can see on their machine. The easiest way of doing it is by deploying the model using Flask. In this article, we will discuss how to use Flask for the development of our web applications. Further, we will deploy the model on google platform environment. What is Flask? Flask is an API of Python that allows us to build up web-applications. It is designed for quick and easy initiation, with the ability to scale up to complex applications. Getting the dataset The dataset is taken from Kaggle, you can find it from this link . It has four attributes, describing a profile of a candidate and offering a salary to the candidate. Code Implementation Install all the packages required for this project. #Importing Train Dataset import pandas as pd import numpy as np data = pd.read_csv("hiring.csv") data.head() From the dataset, we can see some of the values are missing. Replace those with median and mean value. data['experience'].fillna(data['test_score'].median(), inplace=True) data['test_score'].fillna(data['test_score'].mean(), inplace=True) The independent and dependent variable is stored by iloc method. X = data.iloc[:, :-1] y = data.iloc[:,-1] X We will convert the string value to an integer by defining it in a dictionary and calling the function. def convert(word): word_dict = {'one':1, 'two':2, 'three':3, 'four':4, 'five':5, 'six':6, 'seven':7, 'eight':8, 'nine':9, 'ten':10, 'eleven':11, 'twelve':12, 'zero':0,8:8} return word_dict[word] X['experience'] = X['experience'].apply(lambda x : convert(x)) Linear Regression is one of the simplest and most common supervised machine learning algorithms that data scientists use for predictive modeling. In this post, we’ll use linear regression to build a model that predicts the salary of an employee. from sklearn.linear_model import LinearRegression import pickle regressor = LinearRegression() #Fitting model with training data regressor.fit(X, y) # Saving model to disk pickle.dump(regressor, open('model.pkl','wb')) Flask Application The first step is to create the folder structure. • The design is done using the template folder that contains the HTML file. • Static folder contains the CSS file that gives look and feels to the website. • Python code is written in the app.py file. • For deployment of models in google cloud environment, requiremets.txt file and app.yaml are required. • This project is built on Spyder IDE. Python File: import numpy as np from flask import Flask, request, jsonify, render_template import pickle app = Flask(__name__) model = pickle.load(open('model.pkl', 'rb')) @app.route('/') def home(): return render_template('index.html') @app.route('/predict',methods=['POST']) def predict(): ''' For rendering results on HTML GUI ''' request_form = [int(x) for x in request.form.values()] features = [np.array(request_form)] prediction = model.predict(features) output = round(prediction[0], 2) return render_template('index.html', prediction_text='Employee Salary should be $ {}'.format(output)) @app.route('/predict_api',methods=['POST']) def predict_api(): ''' For direct API calls through request ''' data = request.get_json(force=True) prediction = model.predict([np.array(list(data.values()))]) output = prediction[0] return jsonify(output) if __name__ == "__main__": app.run(debug=True) This code is stored in app.py file. Here we are importing the Flask module and creating a Flask web server from the Flask module. We are creating an instance of the Flask class and calling the web application. The POST request method is used for handling data between the client and the server. Local Model Deployment Open the command prompt. We need to give the location of the file and type python app.py on the terminal. The Screen should appear as below. Copy the URL and paste in the new tab to see the HTML page. Google Cloud Platform Model Deployment The first step is to create an account in google cloud. After signing in, the screen will appear as below. Select the Manage Resources tab in the app engine section. Here we can create a new project. We need to open the command prompt terminal. Set the project directory. Pick the configuration option. It will set up the network. The user must log-in with its credentials. Projects will be displayed on the screen. Since our current project is employeesalary we need to select that option. For deployment of the model type the keyword “gloud app deploy app.yaml –project employeesalary” as shown below. Now it will ask to set up the location. Here the option 4 is selected. Our model is ready for deployment. We need to paste the target URL in the new screen. The HTML page will appear as below. Enter the valid credential and hit the button predict. We should be able to see the predicted salary value on the page. The final step is to disable the application button in the app engine setting so that you won’t be charged enough. Final Thoughts In this article, we learned to create APIs for interacting with machine learning models. Further, we discussed how to deploy our model on both computer and google cloud platform. I hope you found this tutorial useful. Thank you for reading this article.The complete code of the above implementation is available at the AIM’s GitHub repository. Please visit this link to find the complete code.
In real-world, training and model prediction is one phase of the machine learning life-cycle. But it won’t be helpful to anyone other than the developer as no one will understand it. So, we need to create a frontend graphical tool that users can see on their machine. The easiest way of doing it is by deploying the model using Flask. In this article, we will discuss how to use flask for the development of our web applications. Further, we will deploy the model on google platform environment.
This article discusses Deploying the model using Flask. Further, it demonstrates how to deploy a machine learning model using google cloud
["Machine Learning", "model deployment"]
["NumPy", "machine learning", "TPU", "AI", "ML", "model deployment", "Machine Learning", "Python", "Ray", "Aim", "R", "Pandas"]
["AI", "machine learning", "ML", "Aim", "Ray", "Pandas", "NumPy", "TPU", "Python", "R"]
A data analyst with expertise in statistical analysis, data visualization ready to serve the industry using various analytical platforms. I look forward to having in-depth knowledge of machine learning and data science. Outside work, you can find me as a fun-loving person with hobbies such as sports and music.