Saving and Loading Scikit-Learn Models With Joblib in Python
Learn how to save and load scikit-learn models with joblib, including dump/load syntax, compression, version compatibility, and when joblib is a better choice than pickle.

When you train a scikit-learn model, you usually need to save it to disk so you can use it later for inference or retraining. The standard tool for this is joblib, which is included as a dependency of scikit-learn. The core pattern is joblib.dump to write the model to disk and joblib.load to read it back. This article covers the syntax, the parameters that matter, and the practical considerations that affect production use.
Why joblib for scikit-learn Models
Scikit-learn models often contain large NumPy arrays, such as the coefficients of a linear model or the trained trees in a random forest. Python's built-in pickle can serialize these objects, but joblib is optimized for objects that hold NumPy arrays. Instead of pickling every array as a generic Python object, joblib stores the arrays efficiently and can memory-map them on load, which is useful when a model is too large to fit comfortably in RAM.
Joblib also preserves Python object graphs, including references to custom classes and functions, as long as those definitions are importable at load time. For most scikit-learn estimators, joblib is the recommended serialization method.
Saving a Model with joblib.dump
The joblib.dump function writes an object to a file. Basic usage:
import joblib
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=100)
# Assume model.fit(X_train, y_train) has been called
joblib.dump(model, 'model.joblib')The first argument is the object to save, and the second is the file path. The file extension is arbitrary, but .joblib is conventional. You can also pass a file-like object, such as a BytesIO stream, if you want to keep the serialized data in memory.
joblib.dump returns a list of file names it wrote. In most cases you can ignore this return value.
Loading a Model with joblib.load
Loading is symmetric:
import joblib
model = joblib.load('model.joblib')The load function reads the object from disk and returns it. The object is reconstructed with the same class and state it had when saved. You can then call predict or transform on it directly:
predictions = model.predict(X_new)Make sure the environment where you load the model has the same version of scikit-learn, or at least a compatible one, and any custom classes the model depends on.
Compression and File Size
Models can be large, especially ensemble methods with many trees. joblib.dump accepts a compress parameter that reduces the file size at the cost of slower save and load times.
joblib.dump(model, 'model_compressed.joblib', compress=3)The value can be an integer from 0 to 9, where 0 disables compression and higher values give better compression at the cost of speed. You can also pass a tuple such as ('zlib', 3) to choose a specific compression method. The default is 0 (no compression).
Compression is useful when you need to store models on disk or transfer them over a network. However, for frequently loaded models, the extra decompression time may not be worth it. Test with your actual model to find a balance.
Handling Versions and Compatibility
Serialized models depend on the class definitions and the version of scikit-learn used to create them. Loading a model with a different scikit-learn version can fail or, worse, produce silently incorrect results.
Joblib itself is relatively stable, but estimator classes can change between scikit-learn releases. If possible, retrain and re-save models after upgrading scikit-learn rather than relying on old files. If you must load an old model, verify its predictions against a known baseline.
Similarly, if your model uses custom transformers or estimators defined in your own code, those classes must be importable in the loading environment. joblib.load will raise an ImportError if a required class cannot be found.
Common Pitfalls and Errors
One frequent mistake is saving a model before it has been fitted, or saving a model that references a large dataset unnecessarily. For example, a k-nearest neighbors estimator keeps the training data in the fitted object, and a support vector classifier keeps support vectors. These can bloat the saved file. Consider whether you need those attributes for inference.
Another issue is using a file path with a parent directory that does not exist. joblib.dump will raise a FileNotFoundError in that case. Create the directory before saving.
When loading, a common error is a missing module. If you see ModuleNotFoundError: No module named 'my_custom_transformer', it means the class is not importable in the current environment. Ensure your custom code is on sys.path or installed as a package.
Performance and Memory Considerations
For very large models, joblib supports memory mapping via the mmap_mode parameter in load. This allows you to load a model without copying all its arrays into RAM, which is useful when multiple processes share the same model file.
model = joblib.load('large_model.joblib', mmap_mode='r')The 'r' mode memory-maps the arrays as read-only. This reduces load time and memory usage, but you must not modify the model in place. If you need to retrain, load with mmap_mode=None (the default) to get a writable copy.
Memory mapping works best on local filesystems. Network filesystems may not support it reliably. For memory mapping, save the model without compression; compressed dumps cannot be memory-mapped.
When to Use joblib vs pickle
Python's pickle can serialize many objects, but joblib is specifically optimized for objects with large NumPy arrays and is the recommended choice for scikit-learn models. Use pickle only if you have a special reason, such as integrating with a system that already uses pickle and cannot add joblib as a dependency.
Joblib also offers compression and memory mapping out of the box, which are not available in the standard pickle module without extra code. For production deployments, joblib is the safer and more efficient option.
If you are saving multiple related objects, such as a model and its preprocessing pipeline, you can save them as a tuple or dictionary in one dump call. This keeps the related objects together and simplifies versioning.
pipeline = {'scaler': scaler, 'model': model}
joblib.dump(pipeline, 'full_pipeline.joblib')Loading returns the same dictionary, so you can access both components. This pattern is common in real projects and avoids coordinating multiple separate dump calls.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.