Persist trained models to disk, and export them to other runtimes.
save_model / load_model for a quick round trip, ModelSerializer when you want to reuse one format/protocol configuration across many saves, ModelCheckpoint to snapshot a model periodically during a training loop, or export_to_onnx to hand the model to a non-Python runtime.Overview
-
Formats: every format ultimately stores a
pickle-serialized
{model, metadata, saved_at, model_class, model_module, params}. "pickle" writes it directly; "compressed" gzips the pickle stream; "joblib" defers to the optional joblib package, which is more efficient for models holding large NumPy arrays.
-
Metadata tracking:
save(and
save_model) automatically capture the save timestamp, the model's class/module, and its constructor parameters (via get_params() if available) alongside any caller-supplied metadata dict. load_model_info gives convenient access to this record; note it still unpickles the whole saved bundle (model included) internally, it just returns a lighter dict.
-
Checkpointing:
ModelCheckpointwrapssave_modelto
Security
pickle-based (joblib also pickles under the hood). Unpickling executes arbitrary code embedded in the file. Only load files you created yourself or otherwise trust — never call load_model, load, or load_latest/load_best on a file from an untrusted source.Classes
Unified interface for machine learning model serialization.
__init__( self, format: str = 'pickle', protocol: int = 4, )
Overview
The serializer supports the following backend formats:
- pickle: Python's native serialization format. Best for general use.
- joblib: Optimized for models containing large NumPy arrays.
- compressed: Gzip-compressed pickle for significant disk space savings.
Parameters
format
protocol
Attributes
format
protocol
Raises
ValueError
format is not one of SUPPORTED_FORMATS.
Notes
joblib also pickles). Only call load on files you trust — see the module-level "Security" note.Save and reload a fitted model together with custom metadata:
>>> import numpy as np
>>> from tuiml.algorithms.bayesian import NaiveBayesClassifier
>>> from tuiml.utils.serialization import ModelSerializer
>>> X = np.array([[0, 0], [1, 1], [2, 2], [3, 3]])
>>> y = np.array([0, 0, 1, 1])
>>> my_model = NaiveBayesClassifier().fit(X, y)
>>> serializer = ModelSerializer(format="compressed")
>>> meta = {"accuracy": 0.98, "dataset": "iris_v1"}
>>> serializer.save(my_model, "model.pkl.gz", metadata=meta) # doctest: +SKIP
'model.pkl.gz'
>>> loaded_model = serializer.load("model.pkl.gz") # doctest: +SKIP
Methods
save
(self, model: Any, filepath: Union[str, Path], metadata: Optional[Dict]=None) -> str
save
(self, model: Any, filepath: Union[str, Path], metadata: Optional[Dict]=None) -> str
Save a trained model to disk in this instance's format.
Parameters
model
filepath
format="compressed", a .gz suffix is appended to the file actually written on disk if filepath doesn't already end in .gz.
metadata
Returns
filepath
filepath argument, unchanged, as a string.
Raises
ImportError
format="joblib" and the optional joblib package is not installed.
load
(self, filepath: Union[str, Path]) -> Any
load
(self, filepath: Union[str, Path]) -> Any
Load a model from disk, ignoring any stored metadata.
Parameters
filepath
Returns
model
Raises
FileNotFoundError
filepath does not exist.
ImportError
joblib and it is not installed.
load_with_metadata
(self, filepath: Union[str, Path]) -> Dict[str, Any]
load_with_metadata
(self, filepath: Union[str, Path]) -> Dict[str, Any]
Load a model together with everything save recorded about it.
Parameters
filepath
Returns
data
"model", "metadata", "params", "saved_at", "format", "model_class", and "model_module".
Raises
FileNotFoundError
filepath does not exist (raised by the underlying file open, unlike load this method does not pre-check existence).
ImportError
joblib and it is not installed.
Manage model persistence during iterative training processes.
__init__( self, directory: Union[str, Path], prefix: str = 'checkpoint', max_to_keep: int = 5, save_best_only: bool = False, monitor: str = 'loss', mode: str = 'min', )
Parameters
directory
prefix
max_to_keep
save_best_only
True, a new checkpoint is only committed if the monitored metric improves.
monitor
save).
mode
Attributes
best_value
inf / -inf until the first checkpoint when save_best_only=True).
checkpoints
Notes
save_model's default format="pickle". Unpickling runs arbitrary code embedded in the file — only call load_latest/load_best on a directory you trust.Keep only the 3 best checkpoints by F1-score:
>>> import tempfile
>>> import numpy as np
>>> from tuiml.algorithms.bayesian import NaiveBayesClassifier
>>> from tuiml.utils.serialization import ModelCheckpoint
>>> X = np.array([[0, 0], [1, 1], [2, 2], [3, 3]])
>>> y = np.array([0, 0, 1, 1])
>>> my_model = NaiveBayesClassifier().fit(X, y)
>>> checkpoint = ModelCheckpoint(
... directory=tempfile.mkdtemp(),
... save_best_only=True,
... monitor="f1",
... mode="max",
... max_to_keep=3,
... ) # doctest: +SKIP
>>> for i, score in enumerate([0.5, 0.6, 0.55, 0.7, 0.65]):
... checkpoint.save(my_model, epoch=i, f1=score) # doctest: +SKIP
>>> round(checkpoint.best_value, 2) # doctest: +SKIP
0.7
>>> len(checkpoint.checkpoints) # doctest: +SKIP
3
Methods
save
(self, model: Any, epoch: int=None, **metrics) -> Optional[str]
save
(self, model: Any, epoch: int=None, **metrics) -> Optional[str]
Save a checkpoint, unless save_best_only says to skip it.
Parameters
model
epoch
**metrics
accuracy=0.95, loss=0.1), stored in the checkpoint's metadata. Must include the key named by self.monitor when save_best_only=True.
Returns
filepath
None if save_best_only=True and self.monitor's value did not improve on best_value (so nothing was written).
Raises
ValueError
save_best_only=True and metrics does not contain the key named by self.monitor.
Functions
Save a trained model to disk with automatic metadata tracking.
ModelSerializer: builds one with the resolved format and delegates to save.Parameters
model
filepath
format
compress=True (which forces "compressed").
metadata
compress
True, applies gzip compression to the output file (shorthand for format="compressed").
Returns
str
filepath argument, unchanged, as a string. Note: if compress=True (or format="compressed") and filepath does not already end in .gz, the file written to disk has .gz appended, but this return value does not reflect that — pass a path already ending in .gz to avoid the mismatch.
Raises
ImportError
format="joblib" and the optional joblib package is not installed.
See Also
Save a fitted model with gzip compression:
>>> import numpy as np
>>> from tuiml.algorithms.bayesian import NaiveBayesClassifier
>>> from tuiml.utils.serialization import save_model
>>> X = np.array([[0, 0], [1, 1], [2, 2], [3, 3]])
>>> y = np.array([0, 0, 1, 1])
>>> my_clf = NaiveBayesClassifier().fit(X, y)
>>> save_model(my_clf, "classifier.pkl.gz", compress=True) # doctest: +SKIP
'classifier.pkl.gz'
Load a model from disk, discarding any stored metadata.
filepath's extension: .gz is loaded as gzip-compressed pickle, .joblib/.jbl via joblib, and anything else as a plain pickle.Parameters
filepath
Returns
model
Raises
FileNotFoundError
filepath does not exist.
ImportError
joblib and it is not installed.
Notes
>>> import numpy as np
>>> from tuiml.algorithms.bayesian import NaiveBayesClassifier
>>> from tuiml.utils.serialization import save_model, load_model
>>> X = np.array([[0, 0], [1, 1], [2, 2], [3, 3]])
>>> y = np.array([0, 0, 1, 1])
>>> save_model(NaiveBayesClassifier().fit(X, y), "classifier.pkl") # doctest: +SKIP
>>> model = load_model("classifier.pkl") # doctest: +SKIP
>>> model.predict(X[:1]) # doctest: +SKIP
array([0])
Load a saved model's metadata and hyper-parameters, without the model itself.
load_with_metadata's dict by hand.Parameters
filepath
Returns
dict
A dictionary with keys:
- •
"model_class": Name of the Python class. - •
"model_module": Fully-qualified module the class lives in. - •
"params": Configuration parameters/hyper-parameters (from
model.get_params() if available, else public __dict__ attributes).
- •
"metadata": The custom metadata dict provided during save. - •
"saved_at": ISO timestamp of the save operation. - •
"format": The serialization format used ("pickle",
"joblib", or "compressed").
Raises
FileNotFoundError
filepath does not exist.
ImportError
joblib and it is not installed.
Notes
load_model, but is convenient when metadata and the model object are both wanted, or when only the metadata is of interest and reading it is simpler this way.Check the accuracy of a saved model:
>>> import numpy as np
>>> from tuiml.algorithms.bayesian import NaiveBayesClassifier
>>> from tuiml.utils.serialization import save_model, load_model_info
>>> X = np.array([[0, 0], [1, 1], [2, 2], [3, 3]])
>>> y = np.array([0, 0, 1, 1])
>>> save_model(NaiveBayesClassifier().fit(X, y), "model.pkl",
... metadata={"accuracy": 0.98}) # doctest: +SKIP
>>> info = load_model_info("model.pkl") # doctest: +SKIP
>>> print(f"Model: {info['model_class']} | Acc: {info['metadata']['accuracy']}") # doctest: +SKIP
Model: NaiveBayesClassifier | Acc: 0.98
Export a trained model to ONNX format for cross-platform interoperability.
Overview
Parameters
model
filepath
.onnx file.
input_shape
(None, 20) for a batch size of 20 features). Only the last element (the feature count) is currently used.
input_names
"input" regardless of this argument; see Notes.
output_names
Returns
str
.onnx suffix appended if filepath didn't already have one.
Raises
ImportError
skl2onnx package is not installed.
Notes
This utility requires the skl2onnx package. Install via: pip install skl2onnx
input_names renames the single input node of the exported graph. output_names is not supported yet and raises NotImplementedError rather than being silently ignored, so a caller never ends up with a graph whose node names differ from what it asked for.