1. Model Serialization
Understanding Model Serialization
Model serialization is the process of converting an in-memory machine learning object (the trained model state) into a byte stream. This stream can then be stored in a file or transmitted across a network.
In Scikit-learn, training a model often involves iterative optimization of thousands of coefficients. Once training finishes, we want to save these coefficients, hyperparameters, and the preprocessing pipeline so we do not have to retrain from scratch every time the script restarts.
snapshot of the model's brain to be revived later.
import numpy as np from sklearn.linear_model import LogisticRegression # Simulating a trained model state X = np.array([[0, 0], [1, 1]]) y = np.array([0, 1]) model = LogisticRegression().fit(X, y) print(f'Model trained with coefficients: {model.coef_}')
Saving and Loading with Joblib and Pickle
Pickle is the standard Python serialization module. It converts Python objects into a byte stream. Joblib is a set of tools that improves performance for large NumPy arrays, which are common in ML models.
To save a model, use 'joblib.dump(model, filename)'. To restore it, use 'joblib.load(filename)'. Below is a comparison of common serialization formats.
import joblib from sklearn.linear_model import LinearRegression # Save model = LinearRegression().fit([[0],[1]], [0,1]) joblib.dump(model, 'model.joblib') # Load loaded_model = joblib.load('model.joblib') print(f'Loaded model intercept: {loaded_model.intercept_}')
Versioning Serialized Models
Versioning is critical because serialized files do not contain the original source code. If you change your feature engineering logic in your code but load an old, serialized model, your predictions will be garbage.
Best practice: Always encode the model version in the filename (e.g., model_v1.2.joblib) or save a metadata dictionary alongside the model object containing the commit hash or timestamp.
model.joblib file without clear versioning documentation.
import joblib
model_data = {
'model': model,
'version': '1.0.1',
'timestamp': '2023-10-27'
}
joblib.dump(model_data, 'model_bundle_v1.0.1.joblib')
Security Risks of Untrusted Serialization
The most critical risk with Pickle and Joblib is arbitrary code execution. Because these libraries de-serialize objects by executing code to reconstruct the state, a malicious file can contain instructions to delete your filesystem or steal environment variables.
Never load model files from untrusted sources. If you must accept files from users, implement cryptographic signatures to verify the file's origin.
| Format | Security Profile |
|---|---|
| Pickle/Joblib | High risk (Code Execution) |
| JSON/ONNX | Safe (Data only) |
Knowledge Check
Ready to test your understanding of 1. Model Serialization?