0
0
ML Pythonml~20 mins

Flask API for model serving in ML Python - ML Experiment: Train & Evaluate

Choose your learning style9 modes available
Experiment - Flask API for model serving
Problem:You have trained a simple machine learning model to predict if a flower is Iris Setosa based on petal length and width. Now you want to create a Flask API to serve this model so that users can send data and get predictions.
Current Metrics:Model accuracy on test data: 95%. No API yet.
Issue:No way to serve the model for real-time predictions. Need a simple, reliable API.
Your Task
Build a Flask API that loads the trained model and returns predictions for input features sent via POST requests. The API should return JSON responses with the predicted class.
Use Flask only (no other web frameworks).
Load the model from a saved file.
Accept JSON input with 'petal_length' and 'petal_width'.
Return JSON output with predicted class label.
Hint 1
Hint 2
Hint 3
Hint 4
Solution
ML Python
from flask import Flask, request, jsonify
import joblib
import numpy as np

app = Flask(__name__)

# Load the trained model
model = joblib.load('iris_model.joblib')

@app.route('/predict', methods=['POST'])
def predict():
    data = request.get_json()
    if not data or 'petal_length' not in data or 'petal_width' not in data:
        return jsonify({'error': 'Invalid input, please provide petal_length and petal_width'}), 400
    try:
        petal_length = float(data['petal_length'])
        petal_width = float(data['petal_width'])
    except (ValueError, TypeError):
        return jsonify({'error': 'petal_length and petal_width must be numbers'}), 400

    features = np.array([[petal_length, petal_width]])
    prediction = model.predict(features)[0]

    # Map numeric prediction to class name
    class_map = {0: 'setosa', 1: 'versicolor', 2: 'virginica'}
    predicted_class = class_map.get(prediction, 'unknown')

    return jsonify({'predicted_class': predicted_class})

if __name__ == '__main__':
    app.run(debug=True)
Saved the trained model using joblib to 'iris_model.joblib'.
Created a Flask app with a POST endpoint '/predict'.
Added input validation for JSON data and feature types.
Loaded the model inside the Flask app to make predictions.
Returned prediction results as JSON with class labels.
Results Interpretation

Before: Model trained with 95% accuracy but no way to serve predictions.

After: Flask API serves model predictions in real-time with JSON input/output, enabling easy integration.

This experiment shows how to deploy a machine learning model as a simple web service using Flask, making it accessible for real-world applications.
Bonus Experiment
Extend the Flask API to accept batch predictions by allowing a list of feature sets in the input JSON.
💡 Hint
Modify the input parsing to handle a list of feature dictionaries, predict on all, and return a list of predicted classes.