Deploy a Machine Learning application on AWS EC2 server !

1. Build an ML model and save the pickle file.

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pickle
dataset = pd.read_csv('hiring.csv')dataset['experience'].fillna(0, inplace=True)dataset['test_score'].fillna(dataset['test_score'].mean(), inplace=True)X = dataset.iloc[:, :3]#Converting words to integer values
def convert_to_int(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, 0: 0}
return word_dict[word]
X['experience'] = X['experience'].apply(lambda x : convert_to_int(x))y = dataset.iloc[:, -1]#Splitting Training and Test Set
#Since we have a very small dataset, we will train our model with all available data.
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
#Fitting model with trainig data, y)
# Saving model to disk
pickle.dump(regressor, open('model.pkl','wb'))
model = pickle.load(open('model.pkl','rb'))
print(model.predict([[2, 9, 6]]))

2. Build a flask application and load the pickled file for the prediction.

import numpy as np
from flask import Flask, request, jsonify, render_template
import pickle
app = Flask(__name__)
model = pickle.load(open('model.pkl', 'rb'))
def home():
return render_template('index.html')
def predict():
For rendering results on HTML GUI
int_features = [int(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='Employee Salary should be $ {}'.format(output))if __name__ == "__main__":
<!DOCTYPE html>
<html >
<meta charset="UTF-8">
<title>ML API</title>
<link href='' rel='stylesheet' type='text/css'>
<link href='' rel='stylesheet' type='text/css'>
<link href='' rel='stylesheet' type='text/css'>
<link href='' rel='stylesheet' type='text/css'>

<div class="login">
<h1>Predict Salary Analysis</h1>
<!-- Main Input For Receiving Query to our ML -->
<form action="{{ url_for('predict')}}"method="post">
<input type="text" name="experience" placeholder="Experience" required="required" />
<input type="text" name="test_score" placeholder="Test Score" required="required" />
<input type="text" name="interview_score" placeholder="Interview Score" required="required" />
<button type="submit" class="btn btn-primary btn-block btn-large">Predict</button>
{{ prediction_text }}

3. Deploy the flask application locally and test the model prediction.

> flask run
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on (Press CTRL+C to quit)

4. Provision an AWS EC2 instance.

5. Deploy the flask application on EC2 instance and test the application.

[ec2-user@ip-172-31-44-84 ~]$ sudo yum update && yum install python3-pip
[ec2-user@ip-172-31-44-84 ~]$ pwd
[ec2-user@ip-172-31-44-84 ~]$ mkdir flask-app
[ec2-user@ip-172-31-44-84 ~]$ ll
total 0
drwxrwxr-x 2 ec2-user ec2-user 6 Jan 16 13:22 flask-app
[ec2-user@ip-172-31-44-84 ~]$ cd flask-app
[ec2-user@ip-172-31-44-84 flask-app]$
if __name__ == "__main__":
if __name__ == "__main__":"", port="8080")
> scp -i "..\EC2\sample-ec2-instance.pem" -r .\ .\model.pkl .\requirements.txt .\templates\ ec2-user@
> ssh -i "..\EC2\sample-ec2-instance.pem" ec2-user@
pip3 install requirements.txt



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store