0
0
ML Pythonml~7 mins

Flask API for model serving in ML Python

Choose your learning style9 modes available
Introduction

We use a Flask API to let other programs ask our machine learning model for predictions easily. It acts like a friendly waiter taking requests and giving answers.

You want to share your trained model so others can use it over the internet.
You need a simple way to get predictions from your model without running code locally.
You want to build a web or mobile app that uses your machine learning model.
You want to test your model with real data from different sources.
You want to automate predictions by sending data to your model programmatically.
Syntax
ML Python
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/predict', methods=['POST'])
def predict():
    data = request.get_json()
    # process data and get prediction
    prediction = model.predict(data['input'])
    return jsonify({'prediction': prediction.tolist()})

if __name__ == '__main__':
    app.run(debug=True)

Use @app.route to define the URL path and HTTP method.

Use request.get_json() to get input data sent as JSON.

Examples
A simple Flask app that returns a greeting when you visit /hello.
ML Python
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/hello')
def hello():
    return 'Hello, world!'

if __name__ == '__main__':
    app.run()
This example doubles a number sent in JSON and returns the result.
ML Python
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/predict', methods=['POST'])
def predict():
    data = request.get_json()
    number = data['number']
    result = number * 2
    return jsonify({'result': result})

if __name__ == '__main__':
    app.run()
Sample Model

This Flask app trains a model on iris flower data. It listens for POST requests at /predict with flower features and returns the predicted species name.

ML Python
from flask import Flask, request, jsonify
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
import numpy as np

# Train a simple model
iris = load_iris()
X, y = iris.data, iris.target
model = RandomForestClassifier()
model.fit(X, y)

app = Flask(__name__)

@app.route('/predict', methods=['POST'])
def predict():
    data = request.get_json()
    features = np.array(data['features']).reshape(1, -1)
    prediction = model.predict(features)[0]
    species = iris.target_names[prediction]
    return jsonify({'prediction': species})

if __name__ == '__main__':
    app.run(debug=False)
OutputSuccess
Important Notes

Flask runs a simple web server that listens for requests on your computer.

Use JSON format to send and receive data easily between client and server.

For production, use a more robust server like Gunicorn and secure your API.

Summary

Flask API lets you share your ML model so others can get predictions over the web.

Define routes with @app.route and handle data with JSON.

Test your API by sending POST requests with input data and reading the JSON response.