Machine Learning Β· Chapter 36 of 40

Saving & Loading Models

Save trained models with `joblib` (scikit-learn) or the framework's native format (Keras `.keras`, PyTorch `state_dict`).

Always save the pipeline (preprocessing + model), not just the model.

Example 1 (python)
import joblib
joblib.dump(pipeline, 'model.pkl')
loaded = joblib.load('model.pkl')
print(loaded.predict(X_test[:5]))
Output
[0 1 1 0 1]

Serialize/deserialize scikit-learn models.

Example 2 (python)
# Keras
# model.save('my_model.keras')
# tf.keras.models.load_model('my_model.keras')

Native Keras format.

Key points

  • Use joblib for scikit-learn.
  • Save the pipeline, not just the model.
  • Frameworks have native formats.
  • Version your models with your code.
πŸ’‘ Note: Pickle/joblib files are UNSAFE to load from untrusted sources β€” they can execute arbitrary code.

πŸ“ Quick Quiz

1. Common tool to save scikit-learn models:

2. You should save:

3. Pickle files are: