Sub topic 1
From a Trained Model to a Service
Prerequisites
Assume you know basic Python, functions, classes, JSON, HTTP requests, and scikit-learn model usage. The examples use FastAPI, Pydantic, and joblib.
From a trained model to a service
Training finds model parameters from example data. Serving uses those parameters to make predictions for new input. These are separate jobs:
- A training program reads data and produces a model.
- A service receives HTTP requests and applies the saved model.
- A client sends features and receives a prediction.
A model artifact is a saved file containing the trained model and its configuration. The service should load the artifact rather than retrain every time it starts.
Saving and loading the model
Save the artifact in the training environment, then load it in the serving environment.
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
import joblib
X, y = load_iris(return_X_y=True)
model = RandomForestClassifier(n_estimators=100, random_state=0)
model.fit(X, y)
joblib.dump(model, "model.joblib")The serving process can load model.joblib with joblib.load. Treat model files as trusted inputs. Loading an untrusted serialized file can execute arbitrary code.
Designing the request and response contract
An API contract defines the JSON shape that clients must send and the shape they receive. Stable names and types prevent clients from guessing how to call the service.
from pydantic import BaseModel, Field
class IrisFeatures(BaseModel):
sepal_length: float = Field(gt=0)
sepal_width: float = Field(gt=0)
petal_length: float = Field(gt=0)
petal_width: float = Field(gt=0)
class Prediction(BaseModel):
class_index: intValidating input before it reaches the model
Pydantic validates and converts incoming JSON against IrisFeatures. A missing field, non-numeric value, or value that is not greater than zero should produce a client error instead of reaching the model.
Validation belongs at the API boundary. The prediction function can then build one model row from the validated fields and return a typed Prediction.
Exercise
Why should a service load a saved model instead of training during each request?
Show answer
Loading is faster and gives requests consistent behavior from the same trained artifact.