Bird
Raised Fist0
ML Pythonml~20 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of using Flask in model serving for machine learning?
easy
A. To train machine learning models faster
B. To create a web API that allows clients to send data and get predictions
C. To visualize data in charts and graphs
D. To store large datasets efficiently

Solution

  1. Step 1: Understand Flask's role

    Flask is a lightweight web framework used to build web applications and APIs.
  2. Step 2: Connect Flask to model serving

    In machine learning, Flask is used to create an API endpoint where clients can send input data and receive model predictions.
  3. Final Answer:

    To create a web API that allows clients to send data and get predictions -> Option B
  4. Quick Check:

    Flask for API = Create prediction endpoint [OK]
Hint: Flask makes your model accessible via web requests [OK]
Common Mistakes:
  • Thinking Flask trains models
  • Confusing Flask with data storage tools
  • Assuming Flask is for data visualization
2. Which of the following is the correct way to define a Flask route for a POST request to serve a model prediction?
easy
A. @app.route('/predict', methods=['GET'])
B. @app.route('/predict')
C. @app.route('/predict', methods=['POST'])
D. @app.route('/predict', method='POST')

Solution

  1. Step 1: Recall Flask route syntax

    Flask routes use @app.route decorator with a path and a list of HTTP methods.
  2. Step 2: Identify correct method for sending data

    POST method is used to send data to the server for processing, suitable for model prediction.
  3. Final Answer:

    @app.route('/predict', methods=['POST']) -> Option C
  4. Quick Check:

    POST method for data sending = Correct route [OK]
Hint: Use methods=['POST'] to accept data in Flask route [OK]
Common Mistakes:
  • Using GET instead of POST for sending data
  • Missing 'methods' keyword or using wrong syntax
  • Assuming default route accepts POST
3. Given the Flask code snippet below, what will be the output when a POST request with JSON {"input": [1, 2, 3]} is sent?
from flask import Flask, request, jsonify
app = Flask(__name__)

@app.route('/predict', methods=['POST'])
def predict():
    data = request.get_json()
    result = sum(data['input'])
    return jsonify({'prediction': result})
medium
A. {"prediction": 6}
B. {"prediction": [1, 2, 3]}
C. {"prediction": 123}
D. Error: KeyError

Solution

  1. Step 1: Extract input data from JSON

    The code uses request.get_json() to get {'input': [1, 2, 3]} and accesses data['input'] which is [1, 2, 3].
  2. Step 2: Calculate sum of input list

    sum([1, 2, 3]) equals 6, which is stored in result and returned as JSON.
  3. Final Answer:

    {"prediction": 6} -> Option A
  4. Quick Check:

    Sum of [1,2,3] = 6 [OK]
Hint: Sum list input to get prediction value [OK]
Common Mistakes:
  • Returning the list instead of sum
  • Concatenating numbers as string
  • Missing JSON key causing KeyError
4. Identify the error in the following Flask API code for model serving and select the fix:
from flask import Flask, request, jsonify
app = Flask(__name__)

@app.route('/predict', methods=['POST'])
def predict():
    data = request.json()
    prediction = model.predict(data['input'])
    return jsonify({'prediction': prediction.tolist()})
medium
A. Change request.json() to request.get_json()
B. Change methods=['POST'] to methods=['GET']
C. Remove .tolist() from prediction
D. Add @app.run() after function

Solution

  1. Step 1: Check how JSON data is accessed

    request.json() is incorrect; Flask uses request.get_json() to parse JSON body.
  2. Step 2: Confirm other parts are correct

    methods=['POST'] is correct for sending data; .tolist() is valid if prediction is numpy array; @app.run() is not a decorator.
  3. Final Answer:

    Change request.json() to request.get_json() -> Option A
  4. Quick Check:

    Use request.get_json() to parse JSON [OK]
Hint: Use request.get_json() to read JSON body [OK]
Common Mistakes:
  • Using request.json() instead of get_json()
  • Confusing HTTP methods for data sending
  • Misusing Flask decorators
5. You want to serve a scikit-learn model using Flask. The model expects input features as a 2D list. Which approach correctly prepares the input inside the Flask route before prediction?
@app.route('/predict', methods=['POST'])
def predict():
    data = request.get_json()
    # Prepare input for model
    input_features = ???
    prediction = model.predict(input_features)
    return jsonify({'prediction': prediction.tolist()})
hard
A. input_features = data['features'].tolist() # Convert to list
B. input_features = data['features'] # Use list directly
C. input_features = data['features'][0] # Use first element only
D. input_features = [data['features']] # Wrap list inside another list

Solution

  1. Step 1: Understand model input shape

    Scikit-learn models expect 2D arrays: shape (n_samples, n_features). A single sample must be wrapped in an outer list.
  2. Step 2: Prepare input accordingly

    Wrapping data['features'] (a list of features) inside another list creates a 2D list suitable for prediction.
  3. Final Answer:

    input_features = [data['features']] # Wrap list inside another list -> Option D
  4. Quick Check:

    Wrap features in list for 2D input [OK]
Hint: Wrap single feature list in another list for 2D input [OK]
Common Mistakes:
  • Passing 1D list directly causing shape errors
  • Using only first element losing features
  • Calling .tolist() on a list (already a list)
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard