openmodels 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1248 @@
1
+ """
2
+ Scikit-learn model serializer for the OpenModels library.
3
+
4
+ This module provides a serializer for scikit-learn models, allowing them to be
5
+ converted to and from dictionary representations.
6
+ """
7
+
8
+ from typing import Any, Callable, Dict, List, Tuple, Type, Optional, Union
9
+ from importlib.metadata import version as _package_version, PackageNotFoundError
10
+ import numpy as np
11
+ import inspect
12
+ from scipy.sparse import issparse # type: ignore
13
+
14
+ from ._custom_estimator import load_custom_estimators
15
+
16
+ import sklearn
17
+ from sklearn.calibration import _CalibratedClassifier, _SigmoidCalibration
18
+ from sklearn.cluster._birch import _CFNode, _CFSubcluster
19
+ from sklearn.cluster._bisect_k_means import _BisectingTree
20
+ from sklearn.ensemble._hist_gradient_boosting.predictor import TreePredictor
21
+ from sklearn.ensemble._hist_gradient_boosting.binning import _BinMapper
22
+ from sklearn.gaussian_process.kernels import Kernel
23
+ from sklearn.gaussian_process._gpc import _BinaryGaussianProcessClassifierLaplace
24
+ from sklearn._loss.loss import (
25
+ AbsoluteError,
26
+ HalfBinomialLoss,
27
+ HalfGammaLoss,
28
+ HalfMultinomialLoss,
29
+ HalfPoissonLoss,
30
+ HalfSquaredError,
31
+ HalfTweedieLoss,
32
+ HalfTweedieLossIdentity,
33
+ PinballLoss,
34
+ BaseLoss,
35
+ )
36
+ from sklearn.metrics._scorer import _CurveScorer
37
+ from sklearn.metrics import get_scorer_names, get_scorer
38
+ from sklearn.multiclass import _ConstantPredictor
39
+ from sklearn.tree._tree import Tree
40
+ from sklearn.base import BaseEstimator, check_is_fitted
41
+ from sklearn.exceptions import NotFittedError
42
+ from sklearn.utils.discovery import all_estimators
43
+ from sklearn.neighbors import KDTree
44
+
45
+ from openmodels.exceptions import UnsupportedEstimatorError
46
+ from openmodels.protocols import ModelSerializer
47
+ from openmodels.serializers.base import (
48
+ NumpySerializerMixin,
49
+ ScipySerializerMixin,
50
+ )
51
+ import warnings
52
+
53
+ ConverterFunc = Callable[[Any], Any]
54
+
55
+ LOSS_CLASS_REGISTRY = {
56
+ "AbsoluteError": AbsoluteError,
57
+ "HalfBinomialLoss": HalfBinomialLoss,
58
+ "HalfGammaLoss": HalfGammaLoss,
59
+ "HalfMultinomialLoss": HalfMultinomialLoss,
60
+ "HalfPoissonLoss": HalfPoissonLoss,
61
+ "HalfSquaredError": HalfSquaredError,
62
+ "HalfTweedieLoss": HalfTweedieLoss,
63
+ "HalfTweedieLossIdentity": HalfTweedieLossIdentity,
64
+ "PinballLoss": PinballLoss,
65
+ }
66
+
67
+ KERNEL_REGISTRY = [
68
+ "RBF",
69
+ "WhiteKernel",
70
+ "Sum",
71
+ "Product",
72
+ "ConstantKernel",
73
+ "DotProduct",
74
+ ]
75
+
76
+ ALL_ESTIMATORS = {
77
+ name: cls for name, cls in all_estimators() if issubclass(cls, BaseEstimator)
78
+ }
79
+ # add extra private estimators to ALL_ESTIMATORS
80
+ ALL_ESTIMATORS["_BinMapper"] = _BinMapper
81
+ ALL_ESTIMATORS["_SigmoidCalibration"] = _SigmoidCalibration
82
+ ALL_ESTIMATORS["_BinaryGaussianProcessClassifierLaplace"] = (
83
+ _BinaryGaussianProcessClassifierLaplace
84
+ )
85
+ ALL_ESTIMATORS["_ConstantPredictor"] = _ConstantPredictor
86
+
87
+ TESTED_VERSIONS = ["1.6.1", "1.7.2", "1.8.0"]
88
+
89
+ # Version of openmodels's own wire format (the shape of the serialized dict), independent of
90
+ # scikit-learn's version (producer_version) and of openmodels's own release version
91
+ # (openmodels_version, informational only). Bump this only when the structure itself changes.
92
+ OPENMODELS_FORMAT_VERSION = 1
93
+
94
+
95
+ def _openmodels_version() -> str:
96
+ """Installed openmodels release version, read from package metadata so pyproject.toml
97
+ stays the single source of truth. Falls back to "unknown" for editable/from-source
98
+ installs without proper metadata."""
99
+ try:
100
+ return _package_version("openmodels")
101
+ except PackageNotFoundError:
102
+ return "unknown"
103
+
104
+
105
+ NOT_SUPPORTED_ESTIMATORS: list[str] = [
106
+ # Regressors: all regressors work!! Hurray!
107
+ # Classifiers: all classifiers work!! Hurray!
108
+ # Clusters: all clusters work!! Hurray!
109
+ # Transformers: all transformers work!! Hurray!
110
+ # Others: all others work!! Hurray!
111
+ ]
112
+
113
+
114
+ # Dictionary of attribute exceptions
115
+ ATTRIBUTE_EXCEPTIONS: Dict[str, List] = {
116
+ # Regressors:
117
+ "PLSRegression": ["_x_mean", "_x_std", "_y_mean", "_y_std", "_predict_1d"],
118
+ "SVR": [
119
+ "_sparse",
120
+ "_n_support",
121
+ "_dual_coef_",
122
+ "_intercept_",
123
+ "_probA",
124
+ "_probB",
125
+ "_gamma",
126
+ "_effective_probability",
127
+ ],
128
+ "KNeighborsRegressor": ["_fit_method", "_fit_X", "_y"],
129
+ "NuSVR": [
130
+ "_sparse",
131
+ "_gamma",
132
+ "_n_support",
133
+ "_probA",
134
+ "_probB",
135
+ "_dual_coef_",
136
+ "_intercept_",
137
+ "_effective_probability",
138
+ ],
139
+ "TweedieRegressor": ["_base_loss"],
140
+ "GaussianProcessRegressor": ["kernel_", "_y_train_std", "_y_train_mean"],
141
+ "GradientBoostingRegressor": ["_loss"],
142
+ "HistGradientBoostingRegressor": [
143
+ "_loss",
144
+ "_preprocessor",
145
+ "_baseline_prediction",
146
+ "_predictors",
147
+ "_bin_mapper",
148
+ ],
149
+ "RadiusNeighborsRegressor": ["_fit_method", "_fit_X", "_y"],
150
+ "CCA": ["_x_mean", "_x_std", "_y_mean", "_y_std", "_predict_1d"],
151
+ "GammaRegressor": ["_base_loss"],
152
+ "PoissonRegressor": ["_base_loss"],
153
+ "PLSCanonical": ["_x_mean", "_x_std", "_y_mean", "_y_std", "_predict_1d"],
154
+ "IsotonicRegression": ["f_"],
155
+ "TransformedTargetRegressor": ["_training_dim"],
156
+ # Clusters:
157
+ "BisectingKMeans": ["_bisecting_tree", "_n_threads", "_X_mean"],
158
+ "Birch": ["_subcluster_norms"],
159
+ "KMeans": ["_n_threads"],
160
+ "MiniBatchKMeans": ["_n_threads"],
161
+ # Classifiers:
162
+ "_BinaryGaussianProcessClassifierLaplace": ["kernel_"],
163
+ "DummyClassifier": ["_strategy"],
164
+ "HistGradientBoostingClassifier": [
165
+ "_preprocessor",
166
+ "_baseline_prediction",
167
+ "_predictors",
168
+ "_bin_mapper",
169
+ ],
170
+ "GradientBoostingClassifier": ["_loss"],
171
+ "MLPClassifier": ["_label_binarizer"],
172
+ "NuSVC": [
173
+ "_sparse",
174
+ "_n_support",
175
+ "_probA",
176
+ "_probB",
177
+ "_gamma",
178
+ "_dual_coef_",
179
+ "_intercept_",
180
+ "_effective_probability",
181
+ ],
182
+ "KNeighborsClassifier": ["_fit_method", "_fit_X", "_y", "_tree"],
183
+ "RadiusNeighborsClassifier": ["_fit_method", "_fit_X", "_y", "_tree"],
184
+ "RidgeClassifier": ["_label_binarizer"],
185
+ "RidgeClassifierCV": ["_label_binarizer"],
186
+ "StackingClassifier": ["_label_encoder"],
187
+ "SVC": [
188
+ "_sparse",
189
+ "_n_support",
190
+ "_dual_coef_",
191
+ "_intercept_",
192
+ "_probA",
193
+ "_probB",
194
+ "_gamma",
195
+ "_effective_probability",
196
+ ],
197
+ "TunedThresholdClassifierCV": ["_curve_scorer"],
198
+ # Transformers:
199
+ "ColumnTransformer": ["_columns", "_remainder"],
200
+ "OneHotEncoder": [
201
+ "_infrequent_enabled",
202
+ "_drop_idx_after_grouping",
203
+ "_n_features_outs",
204
+ ],
205
+ "OrdinalEncoder": ["_missing_indices", "_infrequent_enabled"],
206
+ "KBinsDiscretizer": ["_encoder"],
207
+ "KernelPCA": ["_centerer"],
208
+ "KNNImputer": ["_mask_fit_X", "_valid_mask"],
209
+ "KNeighborsTransformer": ["_fit_method", "_tree", "_fit_X"],
210
+ "PowerTransformer": ["_scaler"],
211
+ "RadiusNeighborsTransformer": ["_fit_method", "_tree"],
212
+ "SimpleImputer": ["_fit_dtype", "_fill_dtype"],
213
+ "MiniBatchNMF": ["_n_components", "_transform_max_iter", "_beta_loss", "_gamma"],
214
+ "MissingIndicator": ["_n_features", "_precomputed"],
215
+ "MultiLabelBinarizer": ["_cached_dict"],
216
+ "PolynomialFeatures": ["_max_degree", "_n_out_full", "_min_degree"],
217
+ "PLSSVD": ["_x_mean", "_x_std", "_y_mean", "_y_std"],
218
+ "TargetEncoder": ["_infrequent_enabled"],
219
+ # Others:
220
+ "IsolationForest": [
221
+ "_max_features",
222
+ "_max_samples",
223
+ "_decision_path_lengths",
224
+ "_average_path_length_per_tree",
225
+ ],
226
+ "OneClassSVM": [
227
+ "_sparse",
228
+ "_n_support",
229
+ "_probA",
230
+ "_probB",
231
+ "_gamma",
232
+ "_dual_coef_",
233
+ "_intercept_",
234
+ ],
235
+ "NearestNeighbors": ["_fit_method", "_tree", "_fit_X"],
236
+ "LocalOutlierFactor": [
237
+ "_fit_method",
238
+ "_tree",
239
+ "_fit_X",
240
+ "_distances_fit_X_",
241
+ "_lrd",
242
+ ],
243
+ "TfidfVectorizer": ["_tfidf"],
244
+ }
245
+
246
+
247
+ class SklearnSerializer(
248
+ ModelSerializer,
249
+ NumpySerializerMixin,
250
+ ScipySerializerMixin,
251
+ ):
252
+ """
253
+ Serializer for scikit-learn estimators.
254
+
255
+ This class provides methods to convert scikit-learn estimators to and from
256
+ dictionary representations, which can then be used with various format converters.
257
+
258
+ The serializer supports a wide range of scikit-learn estimators and handles
259
+ the conversion of numpy arrays and other non-JSON-serializable types.
260
+
261
+ Parameters
262
+ ----------
263
+ custom_estimators : callable, list, tuple, or dict, optional
264
+ Optional collection of third-party or custom estimator classes to support during
265
+ serialization and deserialization. This can be:
266
+
267
+ - A callable returning an iterable or dict of (name, class) pairs (e.g., a function like ``all_estimators``).
268
+ - A list or tuple of (name, class) pairs.
269
+ - A dict mapping estimator names to their classes.
270
+
271
+ These estimators are merged into the serializer's internal registry for this instance only,
272
+ allowing support for custom or external estimators without affecting the global registry.
273
+
274
+ References
275
+ ----------
276
+ .. [1] scikit-learn developer guide:
277
+ https://scikit-learn.org/stable/developers/develop.html
278
+
279
+ .. [2] ``sklearn.utils.discovery.all_estimators``:
280
+ https://scikit-learn.org/stable/modules/generated/sklearn.utils.discovery.all_estimators.html
281
+
282
+ .. [3] ``skltemplate.utils.discovery.all_estimators`` (project template):
283
+ https://contrib.scikit-learn.org/project-template/generated/skltemplate.utils.discovery.all_estimators.html
284
+
285
+ Notes
286
+ -----
287
+ For third-party packages compatible with scikit-learn, it is recommended to implement
288
+ an ``all_estimators()`` utility following the scikit-learn API and template above.
289
+ This enables automatic discovery and integration of custom estimators for serialization.
290
+
291
+ If you are maintaining a scikit-learn compatible package, let us know!
292
+ We are happy to extend our testing to include your estimators, ensuring everything works
293
+ smoothly and that we cover any unique types or patterns used in your library.
294
+
295
+ To request official support for your package, please open an issue at:
296
+ https://github.com/Gnpd/openmodels/issues
297
+
298
+ """
299
+
300
+ def __init__(
301
+ self,
302
+ custom_estimators: Optional[
303
+ Union[
304
+ Callable[..., Any],
305
+ List[Any],
306
+ Tuple[Any, ...],
307
+ Dict[str, Type[BaseEstimator]],
308
+ ]
309
+ ] = None,
310
+ ):
311
+ extra = (
312
+ load_custom_estimators(custom_estimators, ALL_ESTIMATORS)
313
+ if custom_estimators
314
+ else {}
315
+ )
316
+ self._all_estimators: Dict[str, Type] = {**ALL_ESTIMATORS, **extra}
317
+ # Scratch state for one deserialize() call: (node, "prev_leaf_"|"next_leaf_") pairs
318
+ # a Birch _CFNode's leaf-chain pointer couldn't resolve within its own subtree (root_
319
+ # and dummy_leaf_ are independently-deserialized top-level attributes; the pointer
320
+ # crossing between them is fixed up once both are set, see _resolve_birch_leaf_links).
321
+ self._birch_pending_leaf_links: List[Tuple[Any, str]] = []
322
+
323
+ # --- Helpers ---
324
+ def _check_version(self, stored_version: Optional[str]) -> None:
325
+ """
326
+ Check compatibility between stored scikit-learn version and the current environment.
327
+
328
+ Parameters
329
+ ----------
330
+ stored_version : str
331
+ The scikit-learn version recorded during serialization.
332
+
333
+ Notes
334
+ -----
335
+ - Issues a warning if the stored version does not match the current version.
336
+ - Mentions the baseline supported version (1.7.1).
337
+ - Does nothing if no version is stored (for backward compatibility).
338
+ """
339
+ if not stored_version:
340
+ return # No version info available
341
+
342
+ current_version = sklearn.__version__
343
+ if stored_version != current_version:
344
+ warnings.warn(
345
+ f"Version mismatch detected in sklearn deserialization:\n"
346
+ f"- Model serialized with scikit-learn {stored_version}\n"
347
+ f"- Current environment: scikit-learn {current_version}\n\n"
348
+ f"OpenModels has been tested under {TESTED_VERSIONS}. ",
349
+ UserWarning,
350
+ )
351
+
352
+ def _check_format_version(self, stored_version: Optional[int]) -> None:
353
+ """
354
+ Check compatibility between the stored openmodels wire-format version and the version
355
+ this installed openmodels understands.
356
+
357
+ Parameters
358
+ ----------
359
+ stored_version : int
360
+ The openmodels wire-format version recorded during serialization.
361
+
362
+ Notes
363
+ -----
364
+ - Issues a warning if the stored version is newer than what this installation
365
+ understands (the file may use a structure introduced after this release).
366
+ - Does nothing if no version is stored - true for every file written before this field
367
+ existed, which are exactly today's (version-0, unversioned) shape.
368
+ """
369
+ if stored_version is None:
370
+ return # No format version info available - pre-versioning file.
371
+
372
+ if stored_version > OPENMODELS_FORMAT_VERSION:
373
+ warnings.warn(
374
+ f"This file was serialized with openmodels wire-format version "
375
+ f"{stored_version}, newer than the format version this installed openmodels "
376
+ f"understands ({OPENMODELS_FORMAT_VERSION}). Deserialization may fail or "
377
+ f"produce incorrect results - consider upgrading openmodels.",
378
+ UserWarning,
379
+ )
380
+
381
+ @staticmethod
382
+ def all_estimators(
383
+ type_filter: Optional[str] = None,
384
+ ) -> List[Tuple[str, Type[BaseEstimator]]]:
385
+ """
386
+ Get all scikit-learn supported estimators.
387
+
388
+ Parameters
389
+ ----------
390
+ type_filter : str, optional
391
+ If provided, filter estimators by type (e.g., 'classifier', 'regressor').
392
+
393
+ Returns
394
+ -------
395
+ list of tuple
396
+ List of (name, class) pairs for supported estimators.
397
+ """
398
+
399
+ return [
400
+ (name, cls)
401
+ for name, cls in all_estimators(type_filter=type_filter)
402
+ if name not in NOT_SUPPORTED_ESTIMATORS
403
+ ]
404
+
405
+ def _get_nested_types(self, item: Any) -> Any:
406
+ """
407
+ Recursively determine the type of elements within nested lists.
408
+
409
+ Parameters
410
+ ----------
411
+ item : Any
412
+ The item to inspect for nested types.
413
+
414
+ Returns
415
+ -------
416
+ Any
417
+ A nested list representing the types of elements in the input item.
418
+
419
+ Examples
420
+ ---------
421
+
422
+ [1, [1, 2, [1, 2, 3]], 2] -> ['int',['int','int','ndarray'],'int']
423
+
424
+ """
425
+ # Handle np.ndarray of estimators
426
+ if (
427
+ isinstance(item, np.ndarray)
428
+ and item.dtype == np.dtype("O")
429
+ and item.size > 0
430
+ and isinstance(item.ravel()[0], BaseEstimator)
431
+ ):
432
+ return "estimators_collection"
433
+
434
+ # Handle lists or tuple of estimators
435
+ if (
436
+ isinstance(item, (list, tuple))
437
+ and item
438
+ and isinstance(item[0], BaseEstimator)
439
+ ):
440
+ return "estimators_collection"
441
+
442
+ # Handle tuples explicitly
443
+ if isinstance(item, tuple):
444
+ return tuple(self._get_nested_types(subitem) for subitem in item)
445
+
446
+ # Handle lists
447
+ if isinstance(item, list):
448
+ return [self._get_nested_types(subitem) for subitem in item]
449
+
450
+ elif isinstance(item, BaseEstimator):
451
+ # For estimators, return their class name instead of just 'BaseEstimator'
452
+ return item.__class__.__name__
453
+ elif isinstance(item, np.dtype):
454
+ # Normalize to a single stable tag: concrete np.dtype instances are actually
455
+ # instances of numpy-internal per-dtype subclasses (Float64DType, Int64DType,
456
+ # BoolDType, ...), so type(item).__name__ is not a stable/registrable tag.
457
+ return "dtype"
458
+ elif issparse(item):
459
+ # Normalize every scipy sparse container (csr_matrix, csc_matrix, csr_array,
460
+ # csc_array, ...) to the one tag ScipySerializerMixin actually registers a
461
+ # deserializer for - _serialize_csr_matrix already converts any of them to csr_matrix
462
+ # via the csr_matrix(value) constructor, so type(item).__name__ (e.g. "csr_array")
463
+ # would tag a value the deserializer dispatch table has no matching entry for.
464
+ return "csr_matrix"
465
+ else:
466
+ # Return the type name if it's not a list or it's an empty list
467
+ return type(item).__name__
468
+
469
+ def _get_type_maps(self, values_dict: dict) -> tuple[dict, dict]:
470
+ """
471
+ Given a dict of raw values (e.g. model attributes or params),
472
+ builds the corresponding types/dtypes maps.
473
+ """
474
+ types_map = {
475
+ key: self._get_nested_types(value) for key, value in values_dict.items()
476
+ }
477
+ dtypes_map = {
478
+ key: self._get_dtype(value)
479
+ for key, value in values_dict.items()
480
+ if isinstance(value, np.ndarray)
481
+ or (isinstance(value, (list, tuple)) and value) # non-empty list/tuple
482
+ }
483
+
484
+ # Ensure tuples are not included in dtypes_map
485
+ for key, value in values_dict.items():
486
+ if isinstance(value, tuple):
487
+ dtypes_map.pop(key, None) # Remove tuples from dtypes_map
488
+
489
+ return types_map, dtypes_map
490
+
491
+ def _extract_estimator_attributes(self, estimator: BaseEstimator) -> Dict[str, Any]:
492
+ """
493
+ Extract fitted sklearn attributes,
494
+ """
495
+
496
+ def is_valid_attribute(key: str) -> bool:
497
+ return (
498
+ not key.startswith("__") # not private/internal
499
+ and not key.startswith("_") # not protected
500
+ and key.endswith("_") # sklearn convention
501
+ and not key.endswith("__") # not dunder
502
+ and not isinstance(
503
+ getattr(type(estimator), key, None), property
504
+ ) # not property
505
+ and not callable(getattr(estimator, key)) # not method
506
+ )
507
+
508
+ # Collect attributes
509
+ attribute_keys = [key for key in dir(estimator) if is_valid_attribute(key)]
510
+ attribute_keys += ATTRIBUTE_EXCEPTIONS.get(estimator.__class__.__name__, [])
511
+
512
+ # Prevents attribute exceptions introduced in newer scikit-learn versions from breaking older versions of the serializer
513
+ attributes = {
514
+ key: getattr(estimator, key)
515
+ for key in attribute_keys
516
+ if hasattr(estimator, key)
517
+ }
518
+
519
+ return attributes
520
+
521
+ # --- Handlers ---
522
+ def _get_serializer_handlers(self):
523
+ # important to run before super() to deal with possible np.ndarray of estimators
524
+ return [
525
+ (BaseEstimator, self.serialize),
526
+ (BaseLoss, self._serialize_loss),
527
+ (KDTree, self._serialize_kdtree),
528
+ (Kernel, self._serialize_kernel),
529
+ (Tree, self._serialize_tree),
530
+ (TreePredictor, self._serialize_tree_predictor),
531
+ (np.ndarray, self._serialize_estimators_collection),
532
+ (_CalibratedClassifier, self._serialize_calibrated_classifier),
533
+ (_BisectingTree, self._serialize_bisecting_tree),
534
+ (_CurveScorer, self._serialize_curve_scorer),
535
+ (_CFNode, self._serialize_cfnode),
536
+ ] + super()._get_serializer_handlers()
537
+
538
+ def _get_deserializer_handlers(self):
539
+ # Register losses
540
+ loss_handlers = [
541
+ (loss_name, (lambda v, ln=loss_name: self._deserialize_loss(v, ln)))
542
+ for loss_name in LOSS_CLASS_REGISTRY.keys()
543
+ ]
544
+ # Estimators
545
+ estimator_handlers = [
546
+ (est_name, self.deserialize) for est_name in self._all_estimators.keys()
547
+ ]
548
+
549
+ kernel_handlers = [
550
+ (kernel_name, self._deserialize_kernel) for kernel_name in KERNEL_REGISTRY
551
+ ]
552
+ return (
553
+ [
554
+ ("estimators_collection", self._deserialize_estimators_collection),
555
+ ("TreePredictor", self._deserialize_tree_predictor),
556
+ ("_BisectingTree", self._deserialize_bisecting_tree),
557
+ ("_CalibratedClassifier", self._deserialize_calibrated_classifier),
558
+ ("_CurveScorer", self._deserialize_curve_scorer),
559
+ ("_CFNode", self._deserialize_cfnode),
560
+ ]
561
+ + kernel_handlers
562
+ + loss_handlers
563
+ + estimator_handlers
564
+ + super()._get_deserializer_handlers()
565
+ )
566
+
567
+ # --- Sklearn specific serializers/deserializers ---
568
+ def _serialize_bisecting_tree(self, tree: _BisectingTree) -> dict:
569
+ # center/indices are serialized with an explicit dtype (rather than relying on the
570
+ # generic convert_to_serializable, which loses dtype via a plain .tolist()) so that
571
+ # e.g. a float32-fitted tree doesn't get silently widened to JSON's float64 on the
572
+ # way back - predict()'s Cython inner loop requires the exact original buffer dtype.
573
+ center = np.asarray(tree.center)
574
+ indices = np.asarray(tree.indices)
575
+ return {
576
+ "center": self.convert_to_serializable(center),
577
+ "center_dtype": str(center.dtype),
578
+ "indices": self.convert_to_serializable(indices),
579
+ "indices_dtype": str(indices.dtype),
580
+ "score": tree.score,
581
+ "label": getattr(tree, "label", None),
582
+ "left": self._serialize_bisecting_tree(tree.left) if tree.left else None,
583
+ "right": self._serialize_bisecting_tree(tree.right) if tree.right else None,
584
+ }
585
+
586
+ def _deserialize_bisecting_tree(self, data: dict) -> _BisectingTree:
587
+ if data is None:
588
+ return None
589
+ node = _BisectingTree(
590
+ center=np.array(data["center"], dtype=data.get("center_dtype")),
591
+ indices=np.array(data["indices"], dtype=data.get("indices_dtype")),
592
+ score=data["score"],
593
+ )
594
+ if data.get("label") is not None:
595
+ node.label = data["label"]
596
+ node.left = self._deserialize_bisecting_tree(data["left"])
597
+ node.right = self._deserialize_bisecting_tree(data["right"])
598
+ return node
599
+
600
+ def _serialize_calibrated_classifier(
601
+ self, obj: _CalibratedClassifier
602
+ ) -> Dict[str, Any]:
603
+ # Serialize estimator, calibrators (list), classes, and method
604
+ return {
605
+ "estimator": self.convert_to_serializable(obj.estimator),
606
+ "calibrators": self.convert_to_serializable(obj.calibrators),
607
+ "classes": self.convert_to_serializable(obj.classes),
608
+ "method": obj.method,
609
+ }
610
+
611
+ def _deserialize_calibrated_classifier(
612
+ self, data: Dict[str, Any]
613
+ ) -> _CalibratedClassifier:
614
+ estimator = self.deserialize(data["estimator"])
615
+ calibrators = [self.deserialize(c) for c in data["calibrators"]]
616
+ classes = np.array(data["classes"])
617
+ method = data["method"]
618
+ return _CalibratedClassifier(
619
+ estimator, calibrators, classes=classes, method=method
620
+ )
621
+
622
+ def _serialize_cfnode(self, node: _CFNode) -> Dict[str, Any]:
623
+ """
624
+ Recursively serialize a Birch _CFNode and its full subtree of _CFSubcluster/_CFNode
625
+ descendants (a _CFSubcluster's `child_` is where the tree actually recurses one level
626
+ down). Captures the real fitted state - not just the node's scalar config - so
627
+ predict()/partial_fit() keep working after a round-trip.
628
+
629
+ Also captures the doubly-linked prev_leaf_/next_leaf_ chain Birch threads across leaf
630
+ nodes only (used by Birch._get_leaves() for fast traversal). A leaf's neighbor can live
631
+ outside this node's own subtree - e.g. root_'s leftmost leaf's prev_leaf_ is
632
+ Birch.dummy_leaf_, a sibling top-level attribute serialized independently - such refs
633
+ are tagged "external" and cross-linked after deserialization by
634
+ _resolve_birch_leaf_links, since node_id namespaces are local to each top-level
635
+ _serialize_cfnode call.
636
+ """
637
+ node_ids: Dict[int, int] = {}
638
+
639
+ def get_id(n: _CFNode) -> int:
640
+ key = id(n)
641
+ if key not in node_ids:
642
+ node_ids[key] = len(node_ids)
643
+ return node_ids[key]
644
+
645
+ # Assign every reachable node an id up front so leaf_ref can resolve a ref to a node
646
+ # not yet visited by the (depth-first) serialize_node walk below.
647
+ def collect(n: _CFNode) -> None:
648
+ get_id(n)
649
+ for sub in n.subclusters_:
650
+ if sub.child_ is not None:
651
+ collect(sub.child_)
652
+
653
+ collect(node)
654
+
655
+ def leaf_ref(neighbor: Optional[_CFNode]) -> Union[int, str, None]:
656
+ if neighbor is None:
657
+ return None
658
+ return node_ids.get(id(neighbor), "external")
659
+
660
+ def serialize_subcluster(sub: _CFSubcluster) -> Dict[str, Any]:
661
+ centroid = np.asarray(sub.centroid_)
662
+ linear_sum = np.asarray(sub.linear_sum_)
663
+ return {
664
+ "n_samples_": sub.n_samples_,
665
+ # squared_sum_/sq_norm_ are np.dot(...) results - numpy scalars (e.g.
666
+ # np.float32), not plain Python floats - so they need convert_to_serializable's
667
+ # np.generic handling (.item()) to be JSON-safe.
668
+ "squared_sum_": self.convert_to_serializable(sub.squared_sum_),
669
+ "sq_norm_": self.convert_to_serializable(sub.sq_norm_),
670
+ "linear_sum_": self.convert_to_serializable(linear_sum),
671
+ "linear_sum_dtype": str(linear_sum.dtype),
672
+ "centroid_": self.convert_to_serializable(centroid),
673
+ "centroid_dtype": str(centroid.dtype),
674
+ "child": serialize_node(sub.child_) if sub.child_ is not None else None,
675
+ }
676
+
677
+ def serialize_node(n: _CFNode) -> Dict[str, Any]:
678
+ return {
679
+ "node_id": get_id(n),
680
+ "threshold": n.threshold,
681
+ "branching_factor": n.branching_factor,
682
+ "is_leaf": n.is_leaf,
683
+ "n_features": n.n_features,
684
+ "dtype": str(n.init_centroids_.dtype),
685
+ "subclusters": [serialize_subcluster(sub) for sub in n.subclusters_],
686
+ "prev_leaf_ref": leaf_ref(n.prev_leaf_) if n.is_leaf else None,
687
+ "next_leaf_ref": leaf_ref(n.next_leaf_) if n.is_leaf else None,
688
+ }
689
+
690
+ return serialize_node(node)
691
+
692
+ def _deserialize_cfnode(self, data: dict) -> Optional[_CFNode]:
693
+ """
694
+ Deserialize a Birch _CFNode subtree (inverse of _serialize_cfnode). Rebuilds each node
695
+ by replaying the real _CFNode.append_subcluster()/_CFSubcluster construction path
696
+ rather than hand-assembling the init_centroids_/centroids_ view relationship, for
697
+ structural parity with what Birch.fit() itself produces.
698
+
699
+ Old (pre-fix) serialized files only ever captured a node's scalar config (no
700
+ "subclusters"/"node_id"/leaf-ref keys) - those fields are read via .get() with the
701
+ same defaults the old stub used, so old files keep deserializing to the same
702
+ structure-less (broken-but-non-crashing) node as before, not retroactively fixed.
703
+ """
704
+ if data is None:
705
+ return None
706
+
707
+ nodes: Dict[int, _CFNode] = {}
708
+
709
+ def deserialize_subcluster(sub_data: dict) -> _CFSubcluster:
710
+ linear_sum = np.array(
711
+ self.convert_from_serializable(sub_data["linear_sum_"]),
712
+ dtype=sub_data.get("linear_sum_dtype"),
713
+ )
714
+ subcluster = _CFSubcluster(linear_sum=linear_sum)
715
+ subcluster.n_samples_ = sub_data["n_samples_"]
716
+ subcluster.squared_sum_ = sub_data["squared_sum_"]
717
+ subcluster.sq_norm_ = sub_data["sq_norm_"]
718
+ subcluster.centroid_ = np.array(
719
+ self.convert_from_serializable(sub_data["centroid_"]),
720
+ dtype=sub_data.get("centroid_dtype"),
721
+ )
722
+ if sub_data.get("child") is not None:
723
+ subcluster.child_ = deserialize_node(sub_data["child"])
724
+ return subcluster
725
+
726
+ def deserialize_node(node_data: dict) -> _CFNode:
727
+ node = _CFNode(
728
+ threshold=node_data["threshold"],
729
+ branching_factor=node_data["branching_factor"],
730
+ is_leaf=node_data["is_leaf"],
731
+ n_features=node_data["n_features"],
732
+ dtype=np.dtype(node_data.get("dtype") or np.float64),
733
+ )
734
+ node_id = node_data.get("node_id")
735
+ if node_id is not None:
736
+ nodes[node_id] = node
737
+ for sub_data in node_data.get("subclusters", []):
738
+ node.append_subcluster(deserialize_subcluster(sub_data))
739
+ return node
740
+
741
+ root = deserialize_node(data)
742
+
743
+ # Second pass: wire up leaf refs now that every node in this subtree has been built
744
+ # (and thus has an id in `nodes`, regardless of forward/backward reference order).
745
+ def link_leaves(node_data: dict) -> None:
746
+ if node_data["is_leaf"]:
747
+ node = nodes[node_data["node_id"]]
748
+ for ref_key, attr in (
749
+ ("prev_leaf_ref", "prev_leaf_"),
750
+ ("next_leaf_ref", "next_leaf_"),
751
+ ):
752
+ ref = node_data.get(ref_key)
753
+ if ref is None:
754
+ setattr(node, attr, None)
755
+ elif ref == "external":
756
+ self._birch_pending_leaf_links.append((node, attr))
757
+ else:
758
+ setattr(node, attr, nodes[ref])
759
+ for sub_data in node_data.get("subclusters", []):
760
+ if sub_data.get("child") is not None:
761
+ link_leaves(sub_data["child"])
762
+
763
+ if "node_id" in data:
764
+ link_leaves(data)
765
+
766
+ return root
767
+
768
+ def _resolve_birch_leaf_links(self, model: BaseEstimator) -> None:
769
+ """
770
+ Cross-link the two independently-deserialized Birch._CFNode graphs (root_ and
771
+ dummy_leaf_): dummy_leaf_.next_leaf_ always points at the current globally-leftmost
772
+ leaf inside root_'s tree, and that leaf's prev_leaf_ points back at dummy_leaf_. Since
773
+ root_ and dummy_leaf_ are deserialized as independent top-level attributes (in
774
+ whichever order they appear in the serialized data), _deserialize_cfnode can't resolve
775
+ this pointer itself - it queues each side on self._birch_pending_leaf_links, and this
776
+ is called once both attributes are guaranteed to be set.
777
+ """
778
+ pending = self._birch_pending_leaf_links
779
+ self._birch_pending_leaf_links = []
780
+ prev_pending = [node for node, attr in pending if attr == "prev_leaf_"]
781
+ next_pending = [node for node, attr in pending if attr == "next_leaf_"]
782
+ if len(prev_pending) == 1 and len(next_pending) == 1:
783
+ prev_pending[0].prev_leaf_ = next_pending[0]
784
+ next_pending[0].next_leaf_ = prev_pending[0]
785
+ elif pending:
786
+ warnings.warn(
787
+ "Could not resolve Birch's dummy_leaf_/root_ leaf-chain link after "
788
+ "deserialization (unexpected pending link shape); partial_fit()/predict() may "
789
+ "not walk the full leaf chain.",
790
+ UserWarning,
791
+ )
792
+
793
+ def _serialize_tree(self, tree: Tree) -> Dict[str, Any]:
794
+ """
795
+ Serializes a sklearn.tree._tree.Tree object to a dictionary.
796
+
797
+ Parameters:
798
+ tree (sklearn.tree._tree.Tree): The internal tree structure from a fitted tree-based model (e.g., model.tree_)
799
+
800
+ Returns:
801
+ dict: Serialized tree attributes
802
+ """
803
+ state = tree.__getstate__()
804
+
805
+ return {
806
+ "n_features": tree.n_features,
807
+ "n_outputs": tree.n_outputs,
808
+ "n_classes": tree.n_classes.tolist(),
809
+ "state": {
810
+ k: (v.tolist() if hasattr(v, "tolist") else v) for k, v in state.items()
811
+ },
812
+ "nodes_dtype": [list(t) for t in state["nodes"].dtype.descr], # for JSON
813
+ }
814
+
815
+ def _deserialize_tree(self, tree_data: Dict[str, Any]) -> Tree:
816
+ """
817
+ Deserializes a dictionary representation of a tree back to a sklearn.tree._tree.Tree object.
818
+
819
+ """
820
+ tree = Tree(
821
+ tree_data["n_features"],
822
+ np.array(tree_data["n_classes"], dtype=np.intp),
823
+ tree_data["n_outputs"],
824
+ )
825
+
826
+ state = {}
827
+ for key, value in tree_data["state"].items():
828
+ if key == "nodes":
829
+ # Restore dtype
830
+ nodes_dtype_descr = [
831
+ tuple(field) for field in tree_data["nodes_dtype"] if field[0] != ""
832
+ ]
833
+ nodes_dtype = np.dtype(nodes_dtype_descr)
834
+ if isinstance(value, list) and isinstance(value[0], list):
835
+ value = [tuple(row) for row in value]
836
+ state["nodes"] = np.array(value, dtype=nodes_dtype)
837
+ else:
838
+ state[key] = np.array(value)
839
+
840
+ tree.__setstate__(state)
841
+ return tree
842
+
843
+ def _serialize_tree_predictor(self, predictor: TreePredictor) -> Dict[str, Any]:
844
+ """
845
+ Serialize a sklearn.ensemble._hist_gradient_boosting.predictor.TreePredictor object.
846
+ """
847
+ return {
848
+ "nodes": self.convert_to_serializable(predictor.nodes),
849
+ "binned_left_cat_bitsets": self.convert_to_serializable(
850
+ predictor.binned_left_cat_bitsets
851
+ ),
852
+ "raw_left_cat_bitsets": self.convert_to_serializable(
853
+ predictor.raw_left_cat_bitsets
854
+ ),
855
+ }
856
+
857
+ def _deserialize_tree_predictor(self, data: Dict[str, Any]) -> TreePredictor:
858
+ node_dtype = np.dtype(
859
+ [
860
+ ("value", "<f8"),
861
+ ("count", "<u4"),
862
+ ("feature_idx", "<i8"),
863
+ ("num_threshold", "<f8"),
864
+ ("missing_go_to_left", "u1"),
865
+ ("left", "<u4"),
866
+ ("right", "<u4"),
867
+ ("gain", "<f8"),
868
+ ("depth", "<u4"),
869
+ ("is_leaf", "u1"),
870
+ ("bin_threshold", "u1"),
871
+ ("is_categorical", "u1"),
872
+ ("bitset_idx", "<u4"),
873
+ ]
874
+ )
875
+ nodes_list = [tuple(row) for row in data["nodes"]]
876
+ nodes = np.array(nodes_list, dtype=node_dtype)
877
+
878
+ def ensure_2d_uint32(arr):
879
+ arr = np.array(arr, dtype="uint32")
880
+ if arr.ndim == 1:
881
+ # If empty, shape should be (0, 8)
882
+ if arr.size == 0:
883
+ arr = arr.reshape((0, 8))
884
+ else:
885
+ arr = arr.reshape((-1, 8))
886
+ return arr
887
+
888
+ binned_left_cat_bitsets = ensure_2d_uint32(data["binned_left_cat_bitsets"])
889
+ raw_left_cat_bitsets = ensure_2d_uint32(data["raw_left_cat_bitsets"])
890
+
891
+ return TreePredictor(
892
+ nodes=nodes,
893
+ binned_left_cat_bitsets=binned_left_cat_bitsets,
894
+ raw_left_cat_bitsets=raw_left_cat_bitsets,
895
+ )
896
+
897
+ def _serialize_loss(self, value: BaseLoss) -> Dict[str, Any]:
898
+ """
899
+ Serialize a scikit-learn loss object using its constructor parameters.
900
+
901
+ Parameters:
902
+ obj: The loss object instance.
903
+
904
+ Returns:
905
+ dict: Serialized representation.
906
+ """
907
+ cls = type(value)
908
+ params = {
909
+ k: getattr(value, k, None)
910
+ for k in inspect.signature(cls.__init__).parameters
911
+ if k != "self"
912
+ }
913
+ # Fix for TweedieRegressor: ensure 'power' is not None
914
+ if "power" in params and params["power"] is None:
915
+ params["power"] = getattr(value, "power", 0.0)
916
+ return {"params": params}
917
+
918
+ def _deserialize_loss(self, value: Dict[str, Any], loss_name: str) -> BaseLoss:
919
+ loss_cls = LOSS_CLASS_REGISTRY[loss_name]
920
+ params = value.get("params", {})
921
+ return loss_cls(**params)
922
+
923
+ def _serialize_kdtree(self, value: KDTree) -> Dict[str, Any]:
924
+ """
925
+ Serializes a KDTree object to a dictionary.
926
+ """
927
+ # For KDTree, we'll use a simpler approach - just serialize the essential data
928
+ # and let the tree be reconstructed from the data. dtype is captured explicitly
929
+ # (same reasoning as _serialize_bisecting_tree) so non-float64 data isn't silently
930
+ # widened by the generic JSON round-trip.
931
+ data = np.array(value.data)
932
+ return {
933
+ "data": self.convert_to_serializable(data),
934
+ "data_dtype": str(data.dtype),
935
+ }
936
+
937
+ def _deserialize_kdtree(self, kdtree_data: Dict[str, Any]) -> KDTree:
938
+ """
939
+ Deserializes a dictionary representation of a KDTree back to a KDTree object.
940
+ """
941
+ data = np.array(kdtree_data["data"], dtype=kdtree_data.get("data_dtype"))
942
+
943
+ # Create KDTree with data - the tree will be rebuilt automatically
944
+ return KDTree(data)
945
+
946
+ def _serialize_estimators_collection(
947
+ self, value: Union[np.ndarray, List[BaseEstimator]]
948
+ ) -> List[Any]:
949
+ # Accept both numpy arrays and lists of estimators
950
+ if isinstance(value, np.ndarray):
951
+ if (
952
+ value.dtype == np.dtype("O")
953
+ and value.size > 0
954
+ and isinstance(value.ravel()[0], BaseEstimator)
955
+ ):
956
+ return [
957
+ [self.convert_to_serializable(est) for est in row] for row in value
958
+ ]
959
+ return self._serialize_ndarray(value)
960
+
961
+ if (
962
+ isinstance(value, (list, tuple))
963
+ and value
964
+ and isinstance(value[0], BaseEstimator)
965
+ ):
966
+ return [self.convert_to_serializable(est) for est in value]
967
+ return value
968
+
969
+ def _deserialize_estimators_collection(
970
+ self, value: List[Any]
971
+ ) -> Union[np.ndarray, List[BaseEstimator]]:
972
+ # Handle list of lists (array) or flat list (meta-estimator)
973
+ if isinstance(value, list) and value:
974
+ if isinstance(value[0], list):
975
+ # 2D array
976
+ arr = []
977
+ for row in value:
978
+ arr.append(
979
+ [
980
+ (
981
+ self.deserialize(est)
982
+ if isinstance(est, dict) and "estimator_class" in est
983
+ else est
984
+ )
985
+ for est in row
986
+ ]
987
+ )
988
+ return np.array(arr, dtype=object)
989
+ else:
990
+ # Flat list
991
+ return [
992
+ (
993
+ self.deserialize(est)
994
+ if isinstance(est, dict) and "estimator_class" in est
995
+ else est
996
+ )
997
+ for est in value
998
+ ]
999
+ return value
1000
+
1001
+ def _serialize_kernel(self, kernel: Kernel) -> Dict[str, Any]:
1002
+ """
1003
+ Recursively serialize a sklearn.gaussian_process.kernels.Kernel object.
1004
+ """
1005
+ kernel_type = type(kernel).__name__
1006
+ params = kernel.get_params(deep=False)
1007
+ # Recursively serialize kernel parameters that are also kernels
1008
+ serialized_params = {}
1009
+ for k, v in params.items():
1010
+ if isinstance(v, Kernel):
1011
+ serialized_params[k] = self._serialize_kernel(v)
1012
+ else:
1013
+ serialized_params[k] = v
1014
+ return {
1015
+ "kernel_type": kernel_type,
1016
+ "params": serialized_params,
1017
+ }
1018
+
1019
+ def _deserialize_kernel(self, data: Dict[str, Any]) -> Kernel:
1020
+ """
1021
+ Recursively deserialize a kernel dict back to a Kernel object.
1022
+ """
1023
+ kernel_type = data["kernel_type"]
1024
+ params = data["params"]
1025
+ kernel_cls = getattr(
1026
+ __import__("sklearn.gaussian_process.kernels", fromlist=[kernel_type]),
1027
+ kernel_type,
1028
+ )
1029
+ deserialized_params = {}
1030
+ for k, v in params.items():
1031
+ if isinstance(v, dict) and "kernel_type" in v:
1032
+ deserialized_params[k] = self._deserialize_kernel(v)
1033
+ else:
1034
+ deserialized_params[k] = v
1035
+ return kernel_cls(**deserialized_params)
1036
+
1037
+ def _serialize_curve_scorer(self, scorer: _CurveScorer) -> Dict[str, Any]:
1038
+ # Find the scorer name in sklearn.metrics.get_scorer_names()
1039
+ score_func = None
1040
+ for name in get_scorer_names():
1041
+ try:
1042
+ registered = get_scorer(name)
1043
+ # Compare function and kwargs
1044
+ if (
1045
+ hasattr(registered, "_score_func")
1046
+ and registered._score_func == scorer._score_func
1047
+ and getattr(registered, "_kwargs", {})
1048
+ == getattr(scorer, "_kwargs", {})
1049
+ ):
1050
+ score_func = name
1051
+ break
1052
+ except Exception:
1053
+ continue
1054
+
1055
+ return {
1056
+ "score_func": score_func,
1057
+ "sign": scorer._sign,
1058
+ "kwargs": scorer._kwargs,
1059
+ "thresholds": scorer._thresholds,
1060
+ "response_method": scorer._response_method,
1061
+ }
1062
+
1063
+ def _deserialize_curve_scorer(self, data: Dict[str, Any]) -> _CurveScorer:
1064
+ from sklearn.metrics import get_scorer
1065
+
1066
+ score_func_name = data["score_func"]
1067
+ if score_func_name is not None:
1068
+ # Get the base scorer (e.g. accuracy, f1, etc.)
1069
+ base_scorer = get_scorer(score_func_name)
1070
+ # Use from_scorer to reconstruct the _CurveScorer
1071
+ return _CurveScorer.from_scorer(
1072
+ base_scorer,
1073
+ response_method=data.get("response_method", "predict"),
1074
+ thresholds=data.get("thresholds"),
1075
+ )
1076
+ else:
1077
+ raise ValueError(
1078
+ "Cannot deserialize custom/non-standard _CurveScorer functions."
1079
+ )
1080
+
1081
+ def serialize(self, model: BaseEstimator) -> Dict[str, Any]:
1082
+ """
1083
+ Serialize a scikit-learn estimator to a dictionary.
1084
+
1085
+ This method extracts relevant attributes from the model, converts them to
1086
+ JSON-serializable types, and returns a dictionary representation of the model.
1087
+
1088
+ Parameters
1089
+ ----------
1090
+ model : BaseEstimator
1091
+ The scikit-learn estimator to serialize.
1092
+
1093
+ Returns
1094
+ -------
1095
+ Dict[str, Any]
1096
+ A dictionary representation of the model.
1097
+
1098
+ Raises
1099
+ ------
1100
+ SerializationError
1101
+ If there's an error during serialization.
1102
+
1103
+ Examples
1104
+ --------
1105
+ >>> from sklearn.linear_model import LogisticRegression
1106
+ >>> from sklearn.datasets import make_classification
1107
+ >>> X, y = make_classification(n_samples=100, n_features=20, n_classes=2)
1108
+ >>> model = LogisticRegression().fit(X, y)
1109
+ >>> serializer = SklearnSerializer()
1110
+ >>> serialized_dict = serializer.serialize(model)
1111
+ """
1112
+ # Extract and build estimator params and its types/dtypes map
1113
+ params = model.get_params(deep=False)
1114
+ param_types, param_dtypes = self._get_type_maps(params)
1115
+
1116
+ # Build serializable estimator including extra info
1117
+ serialized_estimator = {
1118
+ "estimator_class": model.__class__.__name__,
1119
+ "params": self.convert_to_serializable(params),
1120
+ "param_types": param_types,
1121
+ "param_dtypes": param_dtypes,
1122
+ "producer_version": sklearn.__version__,
1123
+ "producer_name": model.__module__.split(".")[0],
1124
+ "domain": "sklearn",
1125
+ "openmodels_format_version": OPENMODELS_FORMAT_VERSION,
1126
+ "openmodels_version": _openmodels_version(),
1127
+ }
1128
+
1129
+ try:
1130
+ check_is_fitted(model)
1131
+ except NotFittedError:
1132
+ return serialized_estimator
1133
+
1134
+ # Extract and build fitted attributes and its types/dtypes map
1135
+ attributes = self._extract_estimator_attributes(model)
1136
+ attribute_types, attribute_dtypes = self._get_type_maps(attributes)
1137
+
1138
+ serializable_attributes = self.convert_to_serializable(attributes)
1139
+
1140
+ return {
1141
+ **serialized_estimator,
1142
+ "attributes": serializable_attributes,
1143
+ "attribute_types": attribute_types,
1144
+ "attribute_dtypes": attribute_dtypes,
1145
+ }
1146
+
1147
+ def deserialize(self, data: Dict[str, Any]) -> BaseEstimator:
1148
+ """
1149
+ Deserialize a dictionary representation back into a scikit-learn estimator.
1150
+
1151
+ This method reconstructs a scikit-learn estimator from its dictionary
1152
+ representation, converting attributes back to their original types.
1153
+
1154
+ Parameters
1155
+ ----------
1156
+ data : Dict[str, Any]
1157
+ The dictionary representation of the model.
1158
+
1159
+ Returns
1160
+ -------
1161
+ BaseEstimator
1162
+ The deserialized scikit-learn estimator.
1163
+
1164
+ Raises
1165
+ ------
1166
+ UnsupportedEstimatorError
1167
+ If the estimator class is not supported.
1168
+
1169
+ Examples
1170
+ --------
1171
+ >>> serializer = SklearnSerializer()
1172
+ >>> deserialized_model = serializer.deserialize(serialized_dict)
1173
+ >>> predictions = deserialized_model.predict(X_test)
1174
+ """
1175
+ # Version control check
1176
+ self._check_version(data.get("producer_version"))
1177
+ self._check_format_version(data.get("openmodels_format_version"))
1178
+
1179
+ # Reset per-call scratch state used by _deserialize_cfnode/_resolve_birch_leaf_links.
1180
+ self._birch_pending_leaf_links = []
1181
+
1182
+ estimator_class = data["estimator_class"]
1183
+ if estimator_class in NOT_SUPPORTED_ESTIMATORS:
1184
+ raise UnsupportedEstimatorError(
1185
+ f"Unsupported estimator class: {estimator_class}"
1186
+ )
1187
+
1188
+ # Reconstruct params with correct types/dtypes
1189
+ params = data.get("params", {})
1190
+ param_types = data.get("param_types", {})
1191
+ param_dtypes = data.get("param_dtypes", {})
1192
+
1193
+ # Ensure tuples are reconstructed correctly
1194
+ for key, value in params.items():
1195
+ if param_types.get(key) == "tuple" and isinstance(value, list):
1196
+ params[key] = tuple(value)
1197
+
1198
+ # Get valid constructor arguments for the estimator
1199
+ estimator_cls = self._all_estimators[estimator_class]
1200
+ valid_args = list(inspect.signature(estimator_cls.__init__).parameters.keys())
1201
+ # Remove 'self' if present
1202
+ valid_args = [arg for arg in valid_args if arg != "self"]
1203
+
1204
+ reconstructed_params = {}
1205
+ for param_name, param_value in params.items():
1206
+ # Only include params that are valid constructor arguments
1207
+ if param_name not in valid_args:
1208
+ continue
1209
+ # Handle PatchExtractor's 'patch_size' parameter
1210
+ if (
1211
+ estimator_class == "PatchExtractor"
1212
+ and param_name == "patch_size"
1213
+ and isinstance(param_value, list)
1214
+ ):
1215
+ param_value = tuple(param_value)
1216
+ param_type = param_types.get(param_name)
1217
+ param_dtype = param_dtypes.get(param_name) or None
1218
+ reconstructed_params[param_name] = self.convert_from_serializable(
1219
+ param_value, param_type, param_dtype
1220
+ )
1221
+ model = estimator_cls(**reconstructed_params)
1222
+
1223
+ if "attributes" not in data:
1224
+ return model # Unfitted model
1225
+
1226
+ for attribute, value in data["attributes"].items():
1227
+ attr_type = data["attribute_types"].get(attribute)
1228
+ attr_dtype = data.get("attribute_dtypes", {}).get(attribute) or None
1229
+
1230
+ # Handle tree_ separately
1231
+ if attr_type == "Tree":
1232
+ model.tree_ = self._deserialize_tree(value)
1233
+ continue
1234
+ # Skip _tree attribute for KDTree - let the transformer recreate it
1235
+ if attr_type == "KDTree":
1236
+ model._tree = self._deserialize_kdtree(value)
1237
+ continue
1238
+ # Use convert_from_serializable for all attributes
1239
+ setattr(
1240
+ model,
1241
+ attribute,
1242
+ self.convert_from_serializable(value, attr_type, attr_dtype),
1243
+ )
1244
+
1245
+ if estimator_class == "Birch" and self._birch_pending_leaf_links:
1246
+ self._resolve_birch_leaf_links(model)
1247
+
1248
+ return model