Save a model and deploy it for inference

scikit-learn 1.9.1

Package a fitted pipeline with an input contract and verify predictions in its serving environment.

On this page

Save and reload a fitted pipeline

Save preprocessing and the estimator together. Record feature names, dependency versions, model version, and test metrics. joblib uses pickle-based loading, so load only a trusted artifact you created or verified. Use matching package versions for scikit-learn model persistence.

from pathlib import Path
from tempfile import TemporaryDirectory
import joblib
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

model = make_pipeline(StandardScaler(), LinearRegression())
model.fit([[1], [2], [3]], [2, 4, 6])
with TemporaryDirectory() as folder:
    artifact = Path(folder) / "trusted-model.joblib"
    joblib.dump(model, artifact)
    restored = joblib.load(artifact)
    print(round(float(restored.predict([[4]])[0]), 2))
Example output
8.0

Start with an input contract and a smoke test

Choose batch predictions for scheduled jobs or an HTTP endpoint for interactive calls. Load the trusted model at startup, validate feature names and types, and include a model version in the response or output. Run a known test input against the deployed service or job before switching traffic.

import json
import math
from sklearn.linear_model import LinearRegression

model = LinearRegression().fit([[1], [2], [3]], [2, 4, 6])

def predict_record(payload):
    if not isinstance(payload, dict) or set(payload) != {"area_m2"}:
        raise ValueError("Expected an area_m2 field")
    area = payload["area_m2"]
    if type(area) not in (int, float) or not math.isfinite(area) or area <= 0:
        raise ValueError("Area must be a finite positive number")
    return {"model_version": "area-v1", "predicted_price": round(float(model.predict([[area]])[0]), 2)}

print(json.dumps(predict_record({"area_m2": 4})))
Example output
{"model_version": "area-v1", "predicted_price": 8.0}

Monitor inputs and outcomes

Track latency, errors, missing-feature rates, and input distribution changes. When labels arrive, measure model performance on recent data and compare it to the baseline. Keep the previous model version available in case a rollout needs to be reversed.

Official references