Skip to chapter content
navan✳THE BUILD LABMACHINE LEARNING / GUIDE
0/28 read
COOKBOOK 08 / 08

A model artifact with an input contract.

Save a fitted pipeline, load only a trusted local artifact, and validate the row sent to it.

BY NAVAN SAMICOMPLETE EXAMPLEPYTHON 3
01 / THE PURPOSE

Why this workflow exists.

A live predictor must reuse the fitted preprocessing and model together. This recipe fits one pipeline on a built-in dataset, saves it to a local file, then demonstrates a small input contract before prediction. The artifact contains learned state, so loading it is not the same as creating a fresh model object.

joblib files use Python serialization and must be treated as executable when loaded. Only trusted artifacts from a controlled build process should be opened. The code uses a temporary directory and loads the file it just wrote itself. That makes the boundary explicit without suggesting that downloaded model files are safe.

Code context. Python 3 with joblib and scikit-learn installed. The artifact is created and loaded locally by this script.

02 / COMPLETE PYTHON

The whole example.

trusted-model-artifact.py
from pathlib import Path
from tempfile import TemporaryDirectory
import joblib
import numpy as np
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_iris(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(X, y)

def valid_row(values):
    row = np.asarray(values, dtype=float)
    if row.shape != (4,) or not np.isfinite(row).all():
        raise ValueError("expected four finite measurements")
    return row.reshape(1, 4)

with TemporaryDirectory() as directory:
    path = Path(directory) / "trusted-model.joblib"
    joblib.dump(model, path)
    trusted_model = joblib.load(path)  # Only load artifacts you created and trust.
    print(trusted_model.predict(valid_row([5.1, 3.5, 1.4, 0.2])))
03 / READ THE FLOW

What each stage does.

The model pipeline learns scaling and logistic-regression parameters from the built-in Iris rows. valid_row converts one incoming sequence to a numeric NumPy array, then checks for exactly four values and excludes NaN or infinity. reshape makes one row with four columns. The temporary directory exists only during the with block, and joblib.dump writes the fitted pipeline inside it.

joblib.load reconstructs the saved fitted object; predict then uses its learned state on the validated row. The example fits on the entire bundled dataset because it is illustrating serialization and input shape, not evaluating generalisation. A real artifact would be chosen after an independent development and evaluation process and stored with versioned metadata.

04 / THE RESULT

What the output means.

One predicted class ID is printed. The temporary artifact is removed when the context manager exits.

05 / THE BOUNDARY

Where the example stops.

Never load an artifact from an untrusted source with joblib or pickle. A production input contract would also document units, feature order, allowed ranges, and the model version.

Built with curiosity. By Navan Sami. ↗Machine learning with Python · From examples to trustworthy models.