Sub topic 6
Compressing Model Files
This chapter assumes you can fit a scikit-learn estimator, save it with joblib, and load it back. You should also know that a saved model is a file on disk. Here you will shrink that file and see what the shrinking costs.
Why file size matters
A fitted model stores its learned state, not only its settings. A logistic regression on four features stores a few numbers. A random forest stores every tree, and a k-nearest-neighbors model stores the whole training set. Files for these models can reach hundreds of megabytes.
Large files slow down uploads, container builds, and downloads at deploy time. They also cost storage. Compression reduces the size at the price of extra CPU time when you save and load.
The compress argument
joblib.dump takes a compress argument. It accepts an integer from 0 to 9, a method name, or a tuple of method name and level.
from joblib import dump
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=200))
model.fit(X, y)
dump(model, "iris_model_compressed.joblib", compress=3)The integer is the compression level. A higher level gives a smaller file but takes longer to write. Level 0 means no compression, which is the default. Level 3 is a common middle choice.
You do not need to say how a file was compressed when you load it. joblib.load detects the format.
from joblib import load
loaded = load("iris_model_compressed.joblib")
print(loaded.predict(X[:3]))Choosing a method
The integer form uses zlib. You can pick another method by name. This table lists the common ones.
| Value | Method | Typical trade-off |
|---|---|---|
| `compress=3` | zlib, level 3 | Good default, widely available |
| `compress=("lz4", 3)` | LZ4 | Fast, smaller savings. Needs the `lz4` package |
| `compress=("lzma", 3)` | LZMA | Smallest files, slowest. Standard library |
| `compress=("bz2", 3)` | bzip2 | Between zlib and LZMA in size |
You can also let the file extension choose. If the name ends in .gz, .bz2, .xz, or .lzma, joblib uses the matching method.
from joblib import dump
dump(model, "iris_model.joblib.gz", compress=3)Measuring the effect
Do not guess. Measure size and time on your own model. The iris pipeline is too small to show much, so this example uses a random forest.
import os
import time
from joblib import dump, load
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
X, y = make_classification(n_samples=5000, n_features=20, random_state=0)
forest = RandomForestClassifier(n_estimators=100, random_state=0).fit(X, y)
for level in (0, 3, 9):
path = f"forest_{level}.joblib"
start = time.perf_counter()
dump(forest, path, compress=level)
save_seconds = time.perf_counter() - start
start = time.perf_counter()
load(path)
load_seconds = time.perf_counter() - start
size_mb = os.path.getsize(path) / 1_000_000
print(f"compress={level}: {size_mb:.1f} MB, "
f"save {save_seconds:.2f}s, load {load_seconds:.2f}s")Exact numbers depend on your machine and data. The pattern is usually the same. The file shrinks sharply from level 0 to level 3. Level 9 saves little more but takes much longer to write.
Common errors
- Compressing without measuring. For a tiny model the saving is a few kilobytes, and the extra time is not worth thinking about. For a large forest the saving can be large.
- Using a high level by default. Level 9 rarely pays off. Try 3 first.
- Missing optional packages.
lz4is not installed with joblib. If you choose it without the package,dumpraises an error. - Expecting compression to fix memory use. Compression shrinks the file. The loaded model takes the same memory as before.
- Expecting memory mapping to work. With
mmap_modeonload, joblib can map large NumPy arrays from an uncompressed file. This does not work with compressed files, which must be decompressed fully into memory.
Summary
Pass compress=3 to joblib.dump for a smaller file at a modest cost in time. Choose another method only after you measure size and speed on your own model. Use no compression when you want fast loading or memory mapping.
Exercise
You save a large random forest with compress=9 and find that saving takes much longer than expected, while the file is only slightly smaller than with compress=3. You also plan to load the file with mmap_mode="r" to share memory between worker processes. What do you change, and why?
Show answer
Switch to compress=3, since level 9 costs a lot of save time for little size gain. For memory mapping, save without compression (compress=0). Joblib cannot memory-map arrays from a compressed file, because it must decompress the data into memory first. Memory mapping needs the arrays stored as plain bytes on disk, so choose between the smaller file and shared memory.
Exercise
A colleague says that compressing a model file with LZMA makes it safe to receive from an unknown source. Is that correct?
Show answer
No. Compression only changes how the bytes are stored. The file is still a pickle-based joblib file, and loading it can still execute arbitrary code. Only load files from sources you trust, or use a format such as skops that checks types before loading.