TExcelTAD
Home › Machine Learning › Saving & Loading Models

Saving & Loading Models

Training can take minutes, hours or days. Once you have a good model you want to save it and load it later — in a web service, a nightly batch job, or simply tomorrow — without retraining. Saving a trained object to bytes is called serialisation (or persistence).

In a normal Python environment you write the bytes to a file such as model.pkl. The playground has no file system to keep, so the examples below write to an in-memory file, io.BytesIO, which behaves exactly like a real binary file.

pickle: Python's built-in serialiser

python · try it yourself
import io
import pickle
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier

X, y = load_iris(return_X_y=True)
model = DecisionTreeClassifier(max_depth=3, random_state=0).fit(X, y)

buffer = io.BytesIO()                 # in a real project: open("model.pkl", "wb")
pickle.dump(model, buffer)
print("saved", buffer.tell(), "bytes")

buffer.seek(0)                        # rewind, like reopening the file
loaded = pickle.load(buffer)          # in a real project: open("model.pkl", "rb")

print("same predictions:", (loaded.predict(X) == model.predict(X)).all())
print("loaded model:", loaded)
saved 1850 bytes
same predictions: True
loaded model: DecisionTreeClassifier(max_depth=3, random_state=0)

On disk the same code looks like this:

python
with open("model.pkl", "wb") as f:
    pickle.dump(model, f)

with open("model.pkl", "rb") as f:
    model = pickle.load(f)

joblib: efficient for big NumPy arrays

scikit-learn's documentation recommends joblib, which works like pickle but stores large NumPy arrays (common inside models such as random forests) more efficiently and can compress them:

python · try it yourself
import io
import joblib
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier

X, y = load_breast_cancer(return_X_y=True)
forest = RandomForestClassifier(n_estimators=50, random_state=0).fit(X, y)

for compress in [0, 3]:
    buffer = io.BytesIO()
    joblib.dump(forest, buffer, compress=compress)
    print(f"compress={compress}: {buffer.tell():>8} bytes")

buffer.seek(0)
restored = joblib.load(buffer)
print("accuracy of restored model:", round(restored.score(X, y), 3))
compress=0:   173337 bytes
compress=3:    39251 bytes
accuracy of restored model: 1.0

On disk: joblib.dump(forest, "forest.joblib") and forest = joblib.load("forest.joblib").

Save the whole pipeline

Always save the complete pipeline, not just the final estimator. The scaler's means, the encoder's categories and the imputer's fill values are part of the model — without them, new data can't be preprocessed the same way:

python · try it yourself
import io
import pickle
import pandas as pd
from sklearn.compose import make_column_transformer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression

train = pd.DataFrame({
    "minutes": [5, 40, 12, 55, 3, 30, 48, 8],
    "device":  ["phone", "laptop", "phone", "laptop", "tablet", "laptop", "tablet", "phone"],
    "bought":  [0, 1, 0, 1, 0, 1, 1, 0],
})
pipe = make_pipeline(
    make_column_transformer((StandardScaler(), ["minutes"]),
                            (OneHotEncoder(handle_unknown="ignore"), ["device"])),
    LogisticRegression(),
).fit(train[["minutes", "device"]], train["bought"])

blob = pickle.dumps(pipe)                     # bytes in memory (dumps with an s)
restored = pickle.loads(blob)

visitors = pd.DataFrame({"minutes": [10, 45], "device": ["phone", "laptop"]})
print("size:", len(blob), "bytes")
print("predictions from restored pipeline:", restored.predict(visitors))
print("P(buy):", restored.predict_proba(visitors)[:, 1].round(3))
size: 2289 bytes
predictions from restored pipeline: [0 1]
P(buy): [0.191 0.863]

The restored pipeline accepts raw DataFrames, exactly like the original.

Store metadata with the model

A model file alone doesn't tell you what it is. Save a small dictionary alongside it: library versions, feature names, training date, metrics. Loading a model with a different scikit-learn version than it was saved with may fail or behave subtly differently, so the version check matters:

python · try it yourself
import io
import pickle
import sklearn
from sklearn.datasets import load_wine
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import RandomForestClassifier

data = load_wine()
model = RandomForestClassifier(n_estimators=50, random_state=0)
cv = cross_val_score(model, data.data, data.target, cv=5).mean()
model.fit(data.data, data.target)

bundle = {
    "model": model,
    "sklearn_version": sklearn.__version__,
    "features": list(data.feature_names),
    "cv_accuracy": round(cv, 3),
    "trained_on": "2025-01-15",               # use the real date in a project
}
buffer = io.BytesIO()
pickle.dump(bundle, buffer)
buffer.seek(0)

loaded = pickle.load(buffer)
if loaded["sklearn_version"] != sklearn.__version__:
    print("warning: model was trained with a different scikit-learn version")
print("trained with scikit-learn", loaded["sklearn_version"])
print("expects", len(loaded["features"]), "features, first:", loaded["features"][:2])
print("cv accuracy at training time:", loaded["cv_accuracy"])
trained with scikit-learn 1.7.0
expects 13 features, first: ['alcohol', 'malic_acid']
cv accuracy at training time: 0.978

Security warning

Warning: pickle.load and joblib.load can execute arbitrary code hidden in the file. Only load model files you created yourself or that come from a source you fully trust. Never load a pickle uploaded by a user.

Safer alternatives exist:

Format Notes
skops (skops.io) scikit-learn-specific format that refuses unknown, untrusted types
ONNX (skl2onnx) language-neutral format; serve models from C#, Java, JavaScript and more
Framework formats PyTorch state_dict with safetensors, Keras .keras files

Go further: Saving Models: pickle and joblib shows what a pickle does and does not store and adds a hash that makes the file checkable.

Test yourself

Why should you save the whole pipeline instead of only the final model?

  1. Pipelines compress better
  2. The preprocessing steps (scalers, encoders) hold learned state that new data needs
  3. Models can't be pickled alone
  4. It's faster to train

What is the main danger of pickle.load on an untrusted file?

  1. It may be slow
  2. It can execute arbitrary code
  3. It deletes the file
  4. It changes the model's accuracy

After writing to an io.BytesIO buffer, what must you do before reading it back?

  1. Close it
  2. Call buffer.seek(0) to rewind
  3. Call pickle.dumps
  4. Nothing