Wednesday, April 22, 2020

Deploy machine learning model API II

Sources
https://github.com/abhinavsagar/Machine-Learning-Deployment
https://towardsdatascience.com/how-to-easily-deploy-machine-learning-models-using-flask-b95af8fe34d4





Project Structure

This project has four parts :


  1. app.py — This contains Flask APIs that receives sales details through GUI or API calls, computes the predicted value based on our model and returns it.
  2. request.py — This uses requests module to call APIs defined in app.py and displays the returned value.
  3. HTML/CSS — This contains the HTML template and CSS styling to allow user to enter sales detail and displays the predicted sales in the third month.




app.py


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():
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='Sales should be $ {}'.format(output))
@app.route('/results',methods=['POST'])
def results():
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)

request.py

import requests
url = 'http://localhost:5000/results'
r = requests.post(url,json={'rate':5, 'sales_in_first_month':200, 'sales_in_second_month':400})
print(r.json())





Results

Run the web application using this command.
$ python app.py
Graphical user interface





















Deploy machine learning API

Based on
https://medium.com/analytics-vidhya/deploying-a-machine-learning-model-on-web-using-flask-and-python-54b86c44e14a


TL;DR


  • Have a .pkl model saved
  • Request comes with 'area' in the json request


from flask import Flask,jsonify,request
from sklearn.externals import joblib
app = Flask(__name__)
@app.route("/", methods=['POST','GET'])
def index():
if(request.method == 'POST'):
data = request.get_json()
house_price = float(data["area"])
lin_reg = joblib.load("./linear_reg.pkl")
return jsonify(lin_reg.predict([[house_price]]).tolist())
else:
return jsonify({"about":"Hello World"})
if __name__ == '__main__':
app.run(debug=True)
Creating a machine learning model and doing predictions for real-world problems sounds cool. But, that’s not very useful for anyone other than the creator of the model since it’s only available on their machine.
In this post, we’ll go over how to use Flask, a microframework for building websites and APIs in Python, to build our Web API
Let’s start the process by building a simple Linear Regression model in Python
Step1. Importing all the necessary Libraries required for building a Linear Regression Model using Scikit Learn
Here I am using homeprices.csv file for training our model which has two features, area and house price.
Step2. Reading the data using pandas and defining our variables for training
Step3. Training our model
Step4. Calculating the score along with coefficients and doing prediction on a certain value of the area variable.
Now our simple linear regression model is ready, let’s go towards model persistence and save the above as .pkl file
Now our model is saved and can be reused by loading the same again anytime.
Let’s build a Web API using Flask and understand the process to achieve the same in a simple manner.

A Very Brief Introduction to Flask

If you downloaded the Anaconda distribution, you already have Flask installed, otherwise, you will have to install it yourself with — pip install flask.
Flask is very minimal since you only bring in the parts as you need them. To demonstrate this, here’s the Flask code to create a very simple web server.
from flask import Flaskapp = Flask(__name__)@app.route("/")
def hello():
    return "Hello World!"if __name__ == '__main__':
    app.run(debug=True)
Once executed, you can navigate to the web address, which is shown the terminal, and observe the expected result.
Let’s review what the executed code is doing.
After importing, we create an instance of the Flask class and pass in the __name__ variable that Python fills in for us. This variable will be "__main__", if this file is being directly run through Python as a script. If we import the file instead, the value of __name__ will be the name of the file where we did the import. For instance, if we had test.py and run.py, and we imported test.py into run.py the __name__ value of test.py will be test.
Above our hello method definition, there’s the @app.route("/") line. The @ denotes a decorator, which allows the function, property, or class it’s precedes to be dynamically altered.
The hello method is where we put the code to run whenever the route of our app or API hits the top level route: /.
If our __name__ variable is __main__, indicating that we ran the file directly instead of importing it, then it will start the Flask app which will run and wait for web requests until the process ends.

Creating the API

Prediction API

The prediction API is quite simple. We give it our data, the area of the house, and pass that into our predict method of our model.
There are quite a few things going on here, so let’s break it down.
Similar to the code above that introduced Flask, we’re calling the @app.route decorator.
In our route method definition, we restrict the request methods to be GET/POST and if so, we get the JSON of the request body so we can access its data. With that variable, we access the key of the data we want — area and parse it into a float. We also load our model into memory from the persisted file.
If there were no errors parsing the data then we pass the parsed variable into the predict method of our linear regression model; the variable was pulled into memory when we loaded our Flask app at startup. Next, we have to change the output of the predict method to a list since, without it, we’d get an error: Object of type 'ndarray' is not JSON serializable. We then call the [jsonify](http://flask.pocoo.org/docs/0.12/api/#flask.json.jsonify) method of Flask to send the response data as JSON.
Now we can run our API (in PyCharm you can just right-click anywhere in the script and click “Run”). With our API running we can execute thecode to call it.
Finally, we can see the output on our terminal.
In this post, we learned what Flask is, how to use it to create APIs, and most importantly how to apply this knowledge to create APIs for interacting with machine learning models.
I hope you found this tutorial useful, Thank you for reading till here. I’m curious about what you think so hit me with some comments.
You can also get in touch with me directly through email.

Loud fan of desktop

 Upon restart the fan of the desktop got loud again. I cleaned the desktop from the dust but it was still loud (Lower than the first sound) ...