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
regressor.fit(X, 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]]))
[53290.89255945]

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'))
@app.route('/')
def home():
return render_template('index.html')
@app.route('/predict',methods=['POST'])
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__":
app.run(debug=True)
<!DOCTYPE html>
<html >
<!--From https://codepen.io/frytyler/pen/EGdtg-->
<head>
<meta charset="UTF-8">
<title>ML API</title>
<link href='https://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Arimo' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Hind:300' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css'>

</head>
<body>
<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>
</form>
<br>
<br>
{{ prediction_text }}
</div></body>
</html>

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 http://127.0.0.1:5000/ (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
/home/ec2-user
[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__":
app.run(debug=True)
if __name__ == "__main__":
app.run(host="0.0.0.0", port="8080")
> scp -i "..\EC2\sample-ec2-instance.pem" -r .\app.py .\model.pkl .\requirements.txt .\templates\ ec2-user@13.59.123.239:/home/ec2-
user/flask-app
> ssh -i "..\EC2\sample-ec2-instance.pem" ec2-user@13.59.123.239
pip3 install requirements.txt
python3 app.py

--

--

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