GLOBAL RESEARCH SYNDICATE
No Result
View All Result
  • Login
  • Latest News
  • Consumer Research
  • Survey Research
  • Marketing Research
  • Industry Research
  • Data Collection
  • More
    • Data Analysis
    • Market Insights
  • Latest News
  • Consumer Research
  • Survey Research
  • Marketing Research
  • Industry Research
  • Data Collection
  • More
    • Data Analysis
    • Market Insights
No Result
View All Result
globalresearchsyndicate
No Result
View All Result
Home Data Analysis

Complete Guide To Model Deployment Using Flask in Google Cloud Platform

globalresearchsyndicate by globalresearchsyndicate
October 20, 2020
in Data Analysis
0
Complete Guide To Model Deployment Using Flask in Google Cloud Platform
0
SHARES
8
VIEWS
Share on FacebookShare on Twitter

W3Schools


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()
Model Deployment Using Flask

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.

Model Deployment Using Flask

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. 

See Also

Google Expanded Features In Anthos — Now Running & Managing Applications On AWS

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.

Model Deployment Using Flask

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.

Model Deployment Using Flask
Model Deployment Using Flask

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.

Model Deployment Using Flask

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.


If you loved this story, do join our Telegram Community.


Also, you can write for us and be one of the 500+ experts who have contributed stories at AIM. Share your nominations here.

Related Posts

How Machine Learning has impacted Consumer Behaviour and Analysis
Consumer Research

How Machine Learning has impacted Consumer Behaviour and Analysis

January 4, 2024
Market Research The Ultimate Weapon for Business Success
Consumer Research

Market Research: The Ultimate Weapon for Business Success

June 22, 2023
Unveiling the Hidden Power of Market Research A Game Changer
Consumer Research

Unveiling the Hidden Power of Market Research: A Game Changer

June 2, 2023
7 Secrets of Market Research Gurus That Will Blow Your Mind
Consumer Research

7 Secrets of Market Research Gurus That Will Blow Your Mind

May 8, 2023
The Shocking Truth About Market Research Revealed!
Consumer Research

The Shocking Truth About Market Research: Revealed!

April 25, 2023
market research, primary research, secondary research, market research trends, market research news,
Consumer Research

Quantitative vs. Qualitative Research. How to choose the Right Research Method for Your Business Needs

March 14, 2023
Next Post
Toxic Gas Detectors Market (Impact Of Covid-19) Segmentation, Swot Analysis, Opportunities And Forecast To 2026 | Sierra Monitor Corporation, Det-Tronics, Industrial Scientific, ATI, Simtronics, Honeywell

Covid-19 Impact On Hair Straighteners & Flat Irons Market : Growth Trends And Strategies With Forecast Till 2026

Categories

  • Consumer Research
  • Data Analysis
  • Data Collection
  • Industry Research
  • Latest News
  • Market Insights
  • Marketing Research
  • Survey Research
  • Uncategorized

Recent Posts

  • Ipsos Revolutionizes the Global Market Research Landscape
  • How Machine Learning has impacted Consumer Behaviour and Analysis
  • Market Research: The Ultimate Weapon for Business Success
  • Privacy Policy
  • Terms of Use
  • Antispam
  • DMCA

Copyright © 2024 Globalresearchsyndicate.com

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In
This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Cookie settingsACCEPT
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT
No Result
View All Result
  • Latest News
  • Consumer Research
  • Survey Research
  • Marketing Research
  • Industry Research
  • Data Collection
  • More
    • Data Analysis
    • Market Insights

Copyright © 2024 Globalresearchsyndicate.com