openmodels 0.1.0a2__tar.gz → 0.1.0a4__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: openmodels
3
- Version: 0.1.0a2
3
+ Version: 0.1.0a4
4
4
  Summary: Export scikit-learn model files to JSON for sharing or deploying predictive models with peace of mind.
5
5
  License: MIT
6
6
  Author: Alejandro Gutierrez
@@ -41,13 +41,13 @@ pip install openmodels
41
41
 
42
42
  ```python
43
43
  from openmodels import SerializationManager, SklearnSerializer
44
- from sklearn.ensemble import RandomForestClassifier
44
+ from sklearn.decomposition import PCA
45
45
  from sklearn.datasets import make_classification
46
46
 
47
47
  # Create and train a scikit-learn model
48
- X, y = make_classification(n_samples=1000, n_features=4, n_informative=2, n_redundant=0, random_state=0, shuffle=False)
49
- model = RandomForestClassifier(n_estimators=10, max_depth=5, random_state=0)
50
- model.fit(X, y)
48
+ X, _ = make_classification(n_samples=1000, n_features=4, n_informative=2, n_redundant=0, random_state=0, shuffle=False)
49
+ model = PCA(n_components=2, random_state=0)
50
+ model.fit(X)
51
51
 
52
52
  # Create a SerializationManager
53
53
  manager = SerializationManager(SklearnSerializer())
@@ -59,8 +59,8 @@ serialized_model = manager.serialize(model)
59
59
  deserialized_model = manager.deserialize(serialized_model)
60
60
 
61
61
  # Use the deserialized model
62
- predictions = deserialized_model.predict(X[:5])
63
- print(predictions)
62
+ transformed_data = deserialized_model.transform(X[:5])
63
+ print(transformed_data)
64
64
  ```
65
65
 
66
66
  ## Extensibility
@@ -108,16 +108,34 @@ class TensorFlowSerializer(ModelSerializer):
108
108
  ...
109
109
  ```
110
110
 
111
- ## Supported Models
111
+ ## Supported Models (scikit-learn)
112
112
 
113
113
  OpenModels currently supports a wide range of scikit-learn models, including:
114
114
 
115
- - Classification: LogisticRegression, RandomForestClassifier, SVC, etc.
116
- - Regression: LinearRegression, RandomForestRegressor, SVR, etc.
115
+ - Classification: LogisticRegression, SVC, etc.
116
+ - Regression: LinearRegression, SVR, etc.
117
117
  - Clustering: KMeans
118
118
  - Dimensionality Reduction: PCA
119
119
 
120
- For a full list of supported models, please refer to the `SUPPORTED_ESTIMATORS` dictionary in `serializers/sklearn_serializer.py`.
120
+ For a full list of supported models, you can programmatically retrieve them using the `SklearnSerializer.all_estimators()` method:
121
+
122
+ ```python
123
+ from openmodels.serializers import SklearnSerializer
124
+
125
+ # Get all supported estimators (classifiers, regressors, etc.)
126
+ all_supported = SklearnSerializer.all_estimators()
127
+ print([name for name, cls in all_supported])
128
+
129
+ # To get only classifiers:
130
+ classifiers = SklearnSerializer.all_estimators(type_filter="classifier")
131
+ print([name for name, cls in classifiers])
132
+
133
+ # To get only regressors:
134
+ regressors = SklearnSerializer.all_estimators(type_filter="regressor")
135
+ print([name for name, cls in regressors])
136
+ ```
137
+
138
+ This will print the names of all scikit-learn estimators supported by OpenModels, filtered to exclude those that are not currently supported.
121
139
 
122
140
  ## Contributing
123
141
 
@@ -23,13 +23,13 @@ pip install openmodels
23
23
 
24
24
  ```python
25
25
  from openmodels import SerializationManager, SklearnSerializer
26
- from sklearn.ensemble import RandomForestClassifier
26
+ from sklearn.decomposition import PCA
27
27
  from sklearn.datasets import make_classification
28
28
 
29
29
  # Create and train a scikit-learn model
30
- X, y = make_classification(n_samples=1000, n_features=4, n_informative=2, n_redundant=0, random_state=0, shuffle=False)
31
- model = RandomForestClassifier(n_estimators=10, max_depth=5, random_state=0)
32
- model.fit(X, y)
30
+ X, _ = make_classification(n_samples=1000, n_features=4, n_informative=2, n_redundant=0, random_state=0, shuffle=False)
31
+ model = PCA(n_components=2, random_state=0)
32
+ model.fit(X)
33
33
 
34
34
  # Create a SerializationManager
35
35
  manager = SerializationManager(SklearnSerializer())
@@ -41,8 +41,8 @@ serialized_model = manager.serialize(model)
41
41
  deserialized_model = manager.deserialize(serialized_model)
42
42
 
43
43
  # Use the deserialized model
44
- predictions = deserialized_model.predict(X[:5])
45
- print(predictions)
44
+ transformed_data = deserialized_model.transform(X[:5])
45
+ print(transformed_data)
46
46
  ```
47
47
 
48
48
  ## Extensibility
@@ -90,16 +90,34 @@ class TensorFlowSerializer(ModelSerializer):
90
90
  ...
91
91
  ```
92
92
 
93
- ## Supported Models
93
+ ## Supported Models (scikit-learn)
94
94
 
95
95
  OpenModels currently supports a wide range of scikit-learn models, including:
96
96
 
97
- - Classification: LogisticRegression, RandomForestClassifier, SVC, etc.
98
- - Regression: LinearRegression, RandomForestRegressor, SVR, etc.
97
+ - Classification: LogisticRegression, SVC, etc.
98
+ - Regression: LinearRegression, SVR, etc.
99
99
  - Clustering: KMeans
100
100
  - Dimensionality Reduction: PCA
101
101
 
102
- For a full list of supported models, please refer to the `SUPPORTED_ESTIMATORS` dictionary in `serializers/sklearn_serializer.py`.
102
+ For a full list of supported models, you can programmatically retrieve them using the `SklearnSerializer.all_estimators()` method:
103
+
104
+ ```python
105
+ from openmodels.serializers import SklearnSerializer
106
+
107
+ # Get all supported estimators (classifiers, regressors, etc.)
108
+ all_supported = SklearnSerializer.all_estimators()
109
+ print([name for name, cls in all_supported])
110
+
111
+ # To get only classifiers:
112
+ classifiers = SklearnSerializer.all_estimators(type_filter="classifier")
113
+ print([name for name, cls in classifiers])
114
+
115
+ # To get only regressors:
116
+ regressors = SklearnSerializer.all_estimators(type_filter="regressor")
117
+ print([name for name, cls in regressors])
118
+ ```
119
+
120
+ This will print the names of all scikit-learn estimators supported by OpenModels, filtered to exclude those that are not currently supported.
103
121
 
104
122
  ## Contributing
105
123
 
@@ -0,0 +1,549 @@
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, Dict, List, Tuple, Type, Optional
9
+ import numpy as np
10
+ from scipy.sparse import _csr, csr_matrix # type: ignore
11
+
12
+ from sklearn.base import BaseEstimator, check_is_fitted
13
+ from sklearn.exceptions import NotFittedError
14
+ from sklearn.utils.discovery import all_estimators
15
+
16
+ from openmodels.exceptions import UnsupportedEstimatorError, SerializationError
17
+ from openmodels.protocols import ModelSerializer
18
+
19
+ ALL_ESTIMATORS = {
20
+ name: cls for name, cls in all_estimators() if issubclass(cls, BaseEstimator)
21
+ }
22
+
23
+ NOT_SUPPORTED_ESTIMATORS: list[str] = [
24
+ # Regressors:
25
+ "AdaBoostRegressor", # Object of type DecisionTreeRegressor is not JSON serializable
26
+ "BaggingRegressor", # Object of type DecisionTreeRegressor is not JSON serializable
27
+ "DecisionTreeRegressor", # Object of type Tree is not JSON serializable
28
+ "ExtraTreeRegressor", # Object of type Tree is not JSON serializable
29
+ "ExtraTreesRegressor", # Object of type ExtraTreeRegressor is not JSON serializable
30
+ "GammaRegressor", # Object of type HalfGammaLoss is not JSON serializable
31
+ "GaussianProcessRegressor", # Object of type Product is not JSON serializable
32
+ "GradientBoostingRegressor", # Object of type DecisionTreeRegressor is not JSON serializable
33
+ "HistGradientBoostingRegressor", # Object of type HalfSquaredError is not JSON serializable
34
+ "IsotonicRegression", # Object of type interp1d is not JSON serializable
35
+ "MultiOutputRegressor", # MultiOutputRegressor.__init__() missing 1 required positional argument: 'estimator'
36
+ "PoissonRegressor", # Object of type HalfPoissonLoss is not JSON serializable
37
+ "RandomForestRegressor", # Object of type DecisionTreeRegressor is not JSON serializable
38
+ "RANSACRegressor", # Object of type LinearRegression is not JSON serializable
39
+ "RegressorChain", # _BaseChain.__init__() missing 1 required positional argument: 'base_estimator'
40
+ "StackingRegressor", # StackingRegressor.__init__() missing 1 required positional argument: 'estimators'
41
+ "TransformedTargetRegressor", # Object of type LinearRegression is not JSON serializable
42
+ "DecisionTreeClassifier", # Object of type _Tree is not JSON serializable
43
+ "TweedieRegressor", # Object of type HalfTweedieLossIdentity is not JSON serializable
44
+ "VotingRegressor", # VotingRegressor.__init__() missing 1 required positional argument: 'estimators'
45
+ # Classifiers:
46
+ "AdaBoostClassifier", # Object of type DecisionTreeClassifier is not JSON serializable
47
+ "BaggingClassifier", # Object of type DecisionTreeClassifier is not JSON serializable
48
+ "CalibratedClassifierCV", # Object of type _CalibratedClassifier is not JSON serializable
49
+ "ClassifierChain", # ClassifierChain.__init__() missing 1 required positional argument: 'base_estimator'
50
+ "DecisionTreeClassifier", # Object of type _Tree is not JSON serializable
51
+ "ExtraTreeClassifier", # Object of type _Tree is not JSON serializable
52
+ "ExtraTreesClassifier", # Object of type ExtraTreeClassifier is not JSON serializable
53
+ "FixedThresholdClassifier", # FixedThresholdClassifier.__init__() missing 1 required positional argument: 'estimator'
54
+ "GaussianProcessClassifier", # Object of type OneVsRestClassifier is not JSON serializable
55
+ "GradientBoostingClassifier", # Object of type DecisionTreeRegressor is not JSON serializable
56
+ "HistGradientBoostingClassifier", # Object of type TreePredictor is not JSON serializable
57
+ "KNeighborsClassifier", # Object of type KDTree is not JSON serializable
58
+ "MLPClassifier", # Object of type LabelBinarizer is not JSON serializable
59
+ "MultiOutputClassifier", # MultiOutputClassifier.__init__() missing 1 required positional argument: 'estimator'
60
+ "OneVsOneClassifier", # OneVsOneClassifier.__init__() missing 1 required positional argument: 'estimator'
61
+ "OneVsRestClassifier", # OneVsOneClassifier.__init__() missing 1 required positional argument: 'estimator'
62
+ "OutputCodeClassifier", # OneVsOneClassifier.__init__() missing 1 required positional argument: 'estimator'
63
+ "PassiveAggressiveClassifier", # Object of type Hinge is not JSON serializable
64
+ "Perceptron", # Object of type Hinge is not JSON serializable
65
+ "RadiusNeighborsClassifier", # Object of type KDTree is not JSON serializable
66
+ "RandomForestClassifier", # Object of type DecisionTreeClassifier is not JSON serializable
67
+ "RidgeClassifier", # Object of type LabelBinarizer is not JSON serializable
68
+ "RidgeClassifierCV", # Object of type LabelBinarizer is not JSON serializable
69
+ "SGDClassifier", # Object of type Hinge is not JSON serializable
70
+ "SelfTrainingClassifier", # ValueError: You must pass an estimator to SelfTrainingClassifier. Use `estimator`.
71
+ "StackingClassifier", # StackingClassifier.__init__() missing 1 required positional argument: 'estimators'
72
+ "TunedThresholdClassifierCV", # TunedThresholdClassifierCV.__init__() missing 1 required positional argument: 'estimator'
73
+ "VotingClassifier", # VotingClassifier.__init__() missing 1 required positional argument: 'estimators'
74
+ # Clusters:
75
+ "Birch", # Object of type _CFNode is not JSON serializable
76
+ "BisectingKMeans", # Object of type _BisectingTree is not JSON serializable
77
+ "FeatureAgglomeration", # Object of type _ArrayFunctionDispatcher is not JSON serializable
78
+ "HDBSCAN", # data type "[('left_node', '<i8'), ('right_node', '<i8')...]" not understood
79
+ # Transformers:
80
+ "ColumnTransformer", # ColumnTransformer.__init__() missing 1 required positional argument: 'transformers'
81
+ "DictVectorizer", # Object of type type is not JSON serializable (in params)
82
+ "FeatureHasher", # openmodels.exceptions.SerializationError: Cannot serialize an unfitted model
83
+ "FeatureUnion", # FeatureUnion.__init__() missing 1 required positional argument: 'transformer_list'
84
+ "GaussianRandomProjection", # Object of type RandomState is not JSON serializable
85
+ "GenericUnivariateSelect", # Object of type function is not JSON serializable
86
+ "HashingVectorizer", # openmodels.exceptions.SerializationError: Cannot serialize an unfitted model
87
+ "Isomap", # Object of type KernelPCA is not JSON serializable
88
+ "KBinsDiscretizer", # Object of type OneHotEncoder is not JSON serializable
89
+ "KNeighborsTransformer", # Object of type KDTree is not JSON serializable
90
+ "KernelPCA", # Object of type KernelCenterer is not JSON serializable
91
+ "LatentDirichletAllocation", # Object of type RandomState is not JSON serializable
92
+ "LinearDiscriminantAnalysis", # This LinearDiscriminantAnalysis estimator requires y to be passed, but the target y is None
93
+ "LocallyLinearEmbedding", # Object of type NearestNeighbors is not JSON serializable"
94
+ "LabelBinarizer", # LabelBinarizer.fit() takes 2 positional arguments but 3 were given
95
+ "LabelEncoder", # LabelEncoder.fit() takes 2 positional arguments but 3 were given
96
+ "MultiLabelBinarizer", # MultiLabelBinarizer.fit() takes 2 positional arguments but 3 were given
97
+ "NeighborhoodComponentsAnalysis", # This NeighborhoodComponentsAnalysis estimator requires y to be passed, but the target y is None.
98
+ "OneHotEncoder", # Object of type type is not JSON serializable
99
+ "OrdinalEncoder", # Object of type type is not JSON serializable
100
+ "PatchExtractor", # ValueError: not enough values to unpack (expected 3, got 2)
101
+ "PowerTransformer", # Object of type StandardScaler is not JSON serializable
102
+ "RFE", # RFE.__init__() missing 1 required positional argument: 'estimator'
103
+ "RFECV", # RFECV.__init__() missing 1 required positional argument: 'estimator'
104
+ "RadiusNeighborsTransformer", # Object of type KDTree is not JSON serializable
105
+ "RandomTreesEmbedding", # Object of type ExtraTreeRegressor is not JSON serializable
106
+ "SelectFdr", # Object of type function is not JSON serializable
107
+ "SelectFpr", # Object of type function is not JSON serializable
108
+ "SelectFromModel", # SelectFromModel.__init__() missing 1 required positional argument: 'estimator'
109
+ "SelectFwe", # Object of type function is not JSON serializable
110
+ "SelectKBest", # Object of type function is not JSON serializable
111
+ "SelectPercentile", # Object of type function is not JSON serializable
112
+ "SequentialFeatureSelector", # SequentialFeatureSelector.__init__() missing 1 required positional argument: 'estimator'
113
+ "SimpleImputer", # Object of type Float64DType is not JSON serializable
114
+ "SkewedChi2Sampler", # ValueError: X may not contain entries smaller than -skewedness.
115
+ "SparseCoder", # SparseCoder.__init__() missing 1 required positional argument: 'dictionary'
116
+ "SparseRandomProjection", # ValueError: lead to a target dimension of 3353 which is larger than the original space with n_features=5
117
+ "SplineTransformer", # Object of type BSpline is not JSON serializable
118
+ "TargetEncoder", # ValueError: Expected array-like (array or non-string sequence), got None
119
+ "TfidfTransformer", # ValueError
120
+ # Others:
121
+ "BayesianGaussianMixture", # Object of type ndarray is not JSON serializable
122
+ "CountVectorizer", # AttributeError: 'numpy.ndarray' object has no attribute 'lower'
123
+ "FrozenEstimator", # FrozenEstimator.__init__() missing 1 required positional argument: 'estimator'
124
+ "GridSearchCV", # GridSearchCV.__init__() missing 2 required positional arguments: 'estimator' and 'param_grid'
125
+ "IsolationForest", # Object of type ExtraTreeRegressor is not JSON serializable
126
+ "KernelDensity", # Object of type KDTree is not JSON serializable
127
+ "LocalOutlierFactor", # AttributeError: This 'LocalOutlierFactor' has no attribute 'predict'
128
+ "Pipeline", # Pipeline.__init__() missing 1 required positional argument: 'steps'
129
+ "RandomizedSearchCV", # RandomizedSearchCV.__init__() missing 2 required positional arguments: 'estimator' and 'param_distributions'
130
+ "SGDOneClassSVM", # Object of type Hinge is not JSON serializable
131
+ "TfidfVectorizer", # AttributeError: 'numpy.ndarray' object has no attribute 'lower'
132
+ ]
133
+
134
+ # Dictionary of attribute exceptions
135
+ ATTRIBUTE_EXCEPTIONS: Dict[str, List] = {
136
+ # Regressors:
137
+ "PLSRegression": ["_x_mean", "_predict_1d"],
138
+ "SVR": [
139
+ "_sparse",
140
+ "_n_support",
141
+ "_dual_coef_",
142
+ "_intercept_",
143
+ "_probA",
144
+ "_probB",
145
+ "_gamma",
146
+ ],
147
+ "KNeighborsRegressor": ["_fit_method", "_fit_X", "_y"],
148
+ "NuSVR": ["_sparse", "_gamma", "_n_support", "_probA", "_probB"],
149
+ "TweedieRegressor": ["_base_loss"],
150
+ "GaussianProcessRegressor": ["kernel_"],
151
+ "HistGradientBoostingRegressor": ["_loss"],
152
+ "RadiusNeighborsRegressor": ["_fit_method", "_fit_X", "_y"],
153
+ "CCA": ["_x_mean", "_predict_1d"],
154
+ "GammaRegressor": ["_base_loss"],
155
+ "PoissonRegressor": ["_base_loss"],
156
+ "PLSCanonical": ["_x_mean", "_predict_1d"],
157
+ "IsotonicRegression": ["f_"],
158
+ # Clusters:
159
+ "BisectingKMeans": ["_bisecting_tree"],
160
+ "KMeans": ["_n_threads"],
161
+ "MiniBatchKMeans": ["_n_threads"],
162
+ # Classifiers:
163
+ "DummyClassifier": ["_strategy"],
164
+ "HistGradientBoostingClassifier": [
165
+ "_preprocessor",
166
+ "_baseline_prediction",
167
+ "_predictors",
168
+ ],
169
+ "MLPClassifier": ["_label_binarizer"],
170
+ "NuSVC": ["_sparse", "_n_support", "_probA", "_probB", "_gamma"],
171
+ "KNeighborsClassifier": ["_fit_method", "_fit_X", "_y", "_tree"],
172
+ "RadiusNeighborsClassifier": ["_fit_method", "_fit_X", "_y", "_tree"],
173
+ "RidgeClassifier": ["_label_binarizer"],
174
+ "RidgeClassifierCV": ["_label_binarizer"],
175
+ "SVC": [
176
+ "_sparse",
177
+ "_n_support",
178
+ "_dual_coef_",
179
+ "_intercept_",
180
+ "_probA",
181
+ "_probB",
182
+ "_gamma",
183
+ ],
184
+ # Transformers:
185
+ "KBinsDiscretizer": ["_encoder"],
186
+ "KernelPCA": ["_centerer"],
187
+ "KNNImputer": ["_mask_fit_X", "_valid_mask"],
188
+ "KNeighborsTransformer": ["_fit_method", "_tree"],
189
+ "PowerTransformer": ["_scaler"],
190
+ "RadiusNeighborsTransformer": ["_fit_method", "_tree"],
191
+ "SimpleImputer": ["_fit_dtype"],
192
+ "MiniBatchNMF": ["_n_components", "_transform_max_iter", "_beta_loss", "_gamma"],
193
+ "MissingIndicator": ["_n_features", "_precomputed"],
194
+ "PolynomialFeatures": ["_max_degree", "_n_out_full", "_min_degree"],
195
+ "PLSSVD": ["_x_mean", "_x_std"],
196
+ # Others:
197
+ "OneClassSVM": ["_sparse", "_n_support", "_probA", "_probB", "_gamma"],
198
+ }
199
+
200
+
201
+ class SklearnSerializer(ModelSerializer):
202
+ """
203
+ Serializer for scikit-learn estimators.
204
+
205
+ This class provides methods to convert scikit-learn estimators to and from
206
+ dictionary representations, which can then be used with various format converters.
207
+
208
+ The serializer supports a wide range of scikit-learn estimators and handles
209
+ the conversion of numpy arrays and other non-JSON-serializable types.
210
+
211
+ Attributes
212
+ ----------
213
+ SUPPORTED_ESTIMATORS : Dict[str, Type[BaseEstimator]]
214
+ A dictionary of supported scikit-learn estimator classes.
215
+ SUPPORTED_TYPES : List[Type]
216
+ A list of supported types for serialization.
217
+ """
218
+
219
+ @staticmethod
220
+ def all_estimators(
221
+ type_filter: Optional[str] = None,
222
+ ) -> List[Tuple[str, Type[BaseEstimator]]]:
223
+ """
224
+ Get all scikit-learn supported estimators.
225
+
226
+ Returns
227
+ -------
228
+ Dict[str, BaseEstimator]
229
+ A dictionary of all scikit-learn supported estimators.
230
+ """
231
+
232
+ return [
233
+ (name, cls)
234
+ for name, cls in all_estimators(type_filter=type_filter)
235
+ if name not in NOT_SUPPORTED_ESTIMATORS
236
+ ]
237
+
238
+ @staticmethod
239
+ def _convert_to_serializable_types(value: Any) -> Any:
240
+ """
241
+ Convert a value to a serializable type.
242
+
243
+ Parameters
244
+ ----------
245
+ value : Any
246
+ The value to convert.
247
+
248
+ Returns
249
+ -------
250
+ Any
251
+ The serializable representation of the value.
252
+ """
253
+ if isinstance(value, dict):
254
+ # Scikit-learn estimators (e.g., LogisticRegressionCV) may use non-string types
255
+ # (such as np.int64 or float) as dictionary keys for attributes like `coefs_paths_`.
256
+ # However, JSON serialization requires all dictionary keys to be strings.
257
+ # The following logic ensures all dictionary keys are converted to strings
258
+ # to guarantee compatibility with JSON serialization and deserialization.
259
+ # NOTE: This ensures that LogisticRegressionCV works, but to put back the original
260
+ # types we need to convert the keys back to the original types (done on fit).
261
+ return {
262
+ str(k): SklearnSerializer._convert_to_serializable_types(v)
263
+ for k, v in value.items()
264
+ }
265
+ if isinstance(value, (np.ndarray, List)):
266
+ return SklearnSerializer._array_to_list(value)
267
+ if isinstance(value, _csr.csr_matrix):
268
+ # Convert indices and indptr to int32 explicitly
269
+ csr_value = csr_matrix(value)
270
+ serialized_sparse_matrix = {
271
+ "data": SklearnSerializer._array_to_list(csr_value.data),
272
+ "indptr": SklearnSerializer._array_to_list(
273
+ csr_value.indptr.astype(np.int32)
274
+ ),
275
+ "indices": SklearnSerializer._array_to_list(
276
+ csr_value.indices.astype(np.int32)
277
+ ),
278
+ "shape": SklearnSerializer._array_to_list(csr_value.shape),
279
+ }
280
+ return serialized_sparse_matrix
281
+ if isinstance(value, (np.generic)):
282
+ # Convert numpy scalar (e.g., np.int64, np.float64) to native Python type
283
+ return value.item()
284
+
285
+ return value
286
+
287
+ @staticmethod
288
+ def _convert_to_sklearn_types(
289
+ value: Any, attr_type: Any = "none", attr_dtype: Optional[str] = None
290
+ ) -> Any:
291
+ """
292
+ Convert a JSON-deserialized value to its scikit-learn type.
293
+
294
+ Parameters
295
+ ----------
296
+ value : Any
297
+ The JSON-deserialized value.
298
+ attr_type : str
299
+ The target type to convert to.
300
+
301
+ Returns
302
+ -------
303
+ Any
304
+ The scikit-learn type of the value.
305
+ """
306
+ # Base case: if attr_type is not a list, convert value based on attr_type
307
+ if isinstance(attr_type, str):
308
+ type_map = {
309
+ "int": int,
310
+ "int64": np.int64,
311
+ "int32": np.int32,
312
+ "float": float,
313
+ "float64": np.float64,
314
+ "str": str,
315
+ "tuple": tuple,
316
+ }
317
+ if attr_type == "csr_matrix":
318
+ # Ensure all sparse matrix components are of correct dtype
319
+ return csr_matrix(
320
+ (
321
+ np.array(value["data"], dtype=attr_dtype or np.float64),
322
+ np.array(value["indices"], dtype=np.int32),
323
+ np.array(value["indptr"], dtype=np.int32),
324
+ ),
325
+ shape=tuple(value["shape"]),
326
+ )
327
+ elif attr_type == "ndarray":
328
+ return np.array(value, dtype=attr_dtype or np.float64)
329
+ elif attr_type in type_map:
330
+ return type_map[attr_type](value)
331
+ # Add other types as needed
332
+ return value # Return as-is if no specific conversion is needed
333
+ # Recursive case: if attr_type is a list, process each element in value
334
+ elif isinstance(attr_type, List) and isinstance(value, List):
335
+ return [
336
+ SklearnSerializer._convert_to_sklearn_types(v, t, attr_dtype)
337
+ for v, t in zip(value, attr_type)
338
+ ]
339
+
340
+ return value
341
+
342
+ @staticmethod
343
+ def _array_to_list(array: Any) -> Any:
344
+ """
345
+ Recursively convert numpy arrays to nested lists.
346
+
347
+ Parameters
348
+ ----------
349
+ array : array-like
350
+ The array or nested structure to convert.
351
+
352
+ Returns
353
+ -------
354
+ list or Any
355
+ The input converted to a nested list structure, or the original value if not an array.
356
+ """
357
+ if isinstance(array, np.ndarray):
358
+ return SklearnSerializer._array_to_list(array.tolist())
359
+ elif isinstance(array, list):
360
+ return [SklearnSerializer._array_to_list(item) for item in array]
361
+ elif isinstance(array, tuple):
362
+ return tuple(SklearnSerializer._array_to_list(item) for item in array)
363
+ elif isinstance(array, np.generic):
364
+ return array.item()
365
+ else:
366
+ return array
367
+
368
+ @staticmethod
369
+ def get_nested_types(item: Any) -> Any:
370
+ """
371
+ Recursively determine the type of elements within nested lists.
372
+
373
+ Parameters
374
+ ----------
375
+ item : Any
376
+ The item to inspect for nested types.
377
+
378
+ Returns
379
+ -------
380
+ Any
381
+ A nested list representing the types of elements in the input item.
382
+
383
+ Examples
384
+ ---------
385
+
386
+ [1, [1, 2, [1, 2, 3]], 2] -> ['int',['int','int','ndarray'],'int']
387
+
388
+ """
389
+ if isinstance(item, List) and item: # If it's a list and not empty
390
+ return [SklearnSerializer.get_nested_types(subitem) for subitem in item]
391
+ else:
392
+ # Return the type name if it's not a list or it's an empty list
393
+ return type(item).__name__
394
+
395
+ @staticmethod
396
+ def get_dtype(value: Any) -> str:
397
+ """
398
+ Get the dtype of a numpy array, otherwise return empty string.
399
+ """
400
+ if isinstance(value, np.ndarray):
401
+ return str(value.dtype) # Get the actual numpy dtype
402
+ return ""
403
+
404
+ def serialize(self, model: BaseEstimator) -> Dict[str, Any]:
405
+ """
406
+ Serialize a scikit-learn estimator to a dictionary.
407
+
408
+ This method extracts relevant attributes from the model, converts them to
409
+ JSON-serializable types, and returns a dictionary representation of the model.
410
+
411
+ Parameters
412
+ ----------
413
+ model : BaseEstimator
414
+ The scikit-learn estimator to serialize.
415
+
416
+ Returns
417
+ -------
418
+ Dict[str, Any]
419
+ A dictionary representation of the model.
420
+
421
+ Raises
422
+ ------
423
+ SerializationError
424
+ If the model has not been fitted or if there's an error during serialization.
425
+
426
+ Examples
427
+ --------
428
+ >>> from sklearn.linear_model import LogisticRegression
429
+ >>> from sklearn.datasets import make_classification
430
+ >>> X, y = make_classification(n_samples=100, n_features=20, n_classes=2)
431
+ >>> model = LogisticRegression().fit(X, y)
432
+ >>> serializer = SklearnSerializer()
433
+ >>> serialized_dict = serializer.serialize(model)
434
+ """
435
+ try:
436
+ check_is_fitted(model)
437
+ except NotFittedError as e:
438
+ raise SerializationError("Cannot serialize an unfitted model") from e
439
+
440
+ # Get all attributes that are not private, not properties, and not callable
441
+ # Attributes that have been estimated from the data must always have a name ending with
442
+ # trailing underscore,
443
+ # for example the coefficients of some regression estimator would be stored in a
444
+ # coef_ attribute after fit has been called.
445
+ # https://scikit-learn.org/stable/glossary.html#term-attributes
446
+ # https://scikit-learn.org/stable/developers/develop.html#estimated-attributes
447
+ # NOTE: This is not always true for all estimators, but it is a good starting point.
448
+ filtered_attribute_keys = [
449
+ key
450
+ for key in dir(model)
451
+ if not key.startswith("__") # not private
452
+ and key.endswith("_")
453
+ and not key.endswith("__")
454
+ and not isinstance(getattr(type(model), key, None), property)
455
+ and not callable(getattr(model, key))
456
+ ]
457
+
458
+ # There are some attributes that are removed in the previous filter according to the
459
+ # sklearn documentation.
460
+ # However, they are still needed in the serialized model so we add them to the list.
461
+ filtered_attribute_keys = filtered_attribute_keys + ATTRIBUTE_EXCEPTIONS.get(
462
+ model.__class__.__name__, []
463
+ )
464
+
465
+ attribute_values = [getattr(model, key) for key in filtered_attribute_keys]
466
+
467
+ # Generate attribute types with nested structure.
468
+ # These types are used to convert the serialized attributes back to their original types.
469
+ attribute_types = [
470
+ SklearnSerializer.get_nested_types(value) for value in attribute_values
471
+ ]
472
+
473
+ attribute_dtypes_map = {
474
+ key: SklearnSerializer.get_dtype(value)
475
+ for key, value in zip(filtered_attribute_keys, attribute_values)
476
+ if isinstance(value, np.ndarray) # Only include NumPy arrays
477
+ }
478
+
479
+ attribute_types_map = dict(zip(filtered_attribute_keys, attribute_types))
480
+
481
+ serializable_attribute_values = [
482
+ self._convert_to_serializable_types(value) for value in attribute_values
483
+ ]
484
+
485
+ # We losely follow the ONNX standard for the serialized model.
486
+ # https://github.com/onnx/onnx/blob/main/docs/IR.md
487
+ return {
488
+ "attributes": dict(
489
+ zip(filtered_attribute_keys, serializable_attribute_values)
490
+ ),
491
+ "attribute_types": attribute_types_map,
492
+ "attribute_dtypes": attribute_dtypes_map,
493
+ "estimator_class": model.__class__.__name__,
494
+ "params": model.get_params(),
495
+ "producer_name": model.__module__.split(".")[0],
496
+ "producer_version": getattr(model, "_sklearn_version", None),
497
+ "model_version": getattr(model, "_sklearn_version", None),
498
+ "domain": "sklearn",
499
+ }
500
+
501
+ def deserialize(self, data: Dict[str, Any]) -> BaseEstimator:
502
+ """
503
+ Deserialize a dictionary representation back into a scikit-learn estimator.
504
+
505
+ This method reconstructs a scikit-learn estimator from its dictionary
506
+ representation, converting attributes back to their original types.
507
+
508
+ Parameters
509
+ ----------
510
+ data : Dict[str, Any]
511
+ The dictionary representation of the model.
512
+
513
+ Returns
514
+ -------
515
+ BaseEstimator
516
+ The deserialized scikit-learn estimator.
517
+
518
+ Raises
519
+ ------
520
+ UnsupportedEstimatorError
521
+ If the estimator class is not supported.
522
+
523
+ Examples
524
+ --------
525
+ >>> serializer = SklearnSerializer()
526
+ >>> deserialized_model = serializer.deserialize(serialized_dict)
527
+ >>> predictions = deserialized_model.predict(X_test)
528
+ """
529
+ estimator_class = data["estimator_class"]
530
+ if estimator_class in NOT_SUPPORTED_ESTIMATORS:
531
+ raise UnsupportedEstimatorError(
532
+ f"Unsupported estimator class: {estimator_class}"
533
+ )
534
+
535
+ model = ALL_ESTIMATORS[estimator_class](**data["params"])
536
+
537
+ for attribute, value in data["attributes"].items():
538
+ # Retrieve the attribute type from data["attribute_types"]
539
+ attr_type = data["attribute_types"].get(attribute)
540
+ # Get dtype if available
541
+ attr_dtype = data.get("attribute_dtypes", {}).get(attribute)
542
+ # Pass both value and attr_type to _convert_to_sklearn_types
543
+ setattr(
544
+ model,
545
+ attribute,
546
+ self._convert_to_sklearn_types(value, attr_type, attr_dtype),
547
+ )
548
+
549
+ return model
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "openmodels"
3
- version = "0.1.0-alpha.2"
3
+ version = "0.1.0-alpha.4"
4
4
  description = "Export scikit-learn model files to JSON for sharing or deploying predictive models with peace of mind."
5
5
  authors = [
6
6
  "Alejandro Gutierrez <agutierrez@sftec.es>, Pau Cabaneros <pau.cabaneros@gmail.com>, Raúl Marín <hi@raulmarin.dev>, Ruben Parrilla <rparrilla@sftec.es>",
@@ -1,419 +0,0 @@
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, Dict, List, Type
9
- import numpy as np
10
- from scipy.sparse import _csr, csr_matrix # type: ignore
11
-
12
- import sklearn
13
- from sklearn.base import BaseEstimator, check_is_fitted
14
- from sklearn.cluster import KMeans
15
- from sklearn.decomposition import PCA
16
- from sklearn.cross_decomposition import PLSRegression
17
-
18
- # from sklearn.ensemble import (
19
- # RandomForestRegressor,
20
- # RandomForestClassifier,
21
- # GradientBoostingClassifier,
22
- # GradientBoostingRegressor,
23
- # )
24
-
25
- from sklearn.svm import SVR, SVC
26
- from sklearn.linear_model import (
27
- LogisticRegression,
28
- Lasso,
29
- Ridge,
30
- LinearRegression,
31
- # Perceptron,
32
- )
33
- from sklearn.naive_bayes import BernoulliNB, GaussianNB, MultinomialNB, ComplementNB
34
- from sklearn.discriminant_analysis import (
35
- LinearDiscriminantAnalysis,
36
- QuadraticDiscriminantAnalysis,
37
- )
38
- from sklearn.dummy import DummyClassifier
39
-
40
- # from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
41
- from sklearn.neural_network import MLPRegressor
42
- from sklearn.exceptions import NotFittedError
43
-
44
- from openmodels.exceptions import UnsupportedEstimatorError, SerializationError
45
- from openmodels.protocols import ModelSerializer
46
-
47
- # Dictionary of supported estimators
48
- SUPPORTED_ESTIMATORS: Dict[str, Type[sklearn.base.BaseEstimator]] = {
49
- "BernoulliNB": BernoulliNB,
50
- "ComplementNB": ComplementNB,
51
- "GaussianNB": GaussianNB,
52
- # "DecisionTreeClassifier": DecisionTreeClassifier, # tree_ instance
53
- # "DecisionTreeRegressor": DecisionTreeRegressor, # tree_ instance
54
- "DummyClassifier": DummyClassifier,
55
- # "GradientBoostingClassifier": GradientBoostingClassifier,
56
- # contains stimators_ attribute with DecisionTreeRegressor
57
- # "GradientBoostingRegressor": GradientBoostingRegressor,
58
- # contains stimators_ attribute with DecisionTreeRegressor
59
- "Lasso": Lasso,
60
- "LinearDiscriminantAnalysis": LinearDiscriminantAnalysis,
61
- "LinearRegression": LinearRegression,
62
- "LogisticRegression": LogisticRegression,
63
- "KMeans": KMeans,
64
- # "MLPClassifier": MLPClassifier, # needs _label_binarizer attribute with LabelBinarizer type
65
- "MLPRegressor": MLPRegressor,
66
- "MultinomialNB": MultinomialNB,
67
- "PCA": PCA,
68
- # "Perceptron": Perceptron, # contains loss_function_ attribut with Hinge type
69
- "PLSRegression": PLSRegression,
70
- "QuadraticDiscriminantAnalysis": QuadraticDiscriminantAnalysis,
71
- # "RandomForestClassifier": RandomForestClassifier,
72
- # contains stimators_ attribute with DecisionTreeRegressor
73
- # "RandomForestRegressor": RandomForestRegressor,
74
- # contains stimators_ attribute with DecisionTreeRegressor
75
- "Ridge": Ridge,
76
- "SVC": SVC,
77
- "SVR": SVR,
78
- }
79
-
80
- # Dictionary of attribute exceptions
81
- ATTRIBUTE_EXCEPTIONS: Dict[str, list] = {
82
- "BernoulliNB": [],
83
- "ComplementNB": [],
84
- # "DecisionTreeClassifier": [], # not suppoted
85
- # "DecisionTreeRegressor": [], # not suppoted
86
- "DummyClassifier": ["_strategy"],
87
- "GaussianNB": [],
88
- # "GradientBoostingClassifier": [], # not supported
89
- "GradientBoostingRegressor": [],
90
- "Lasso": [],
91
- "LinearDiscriminantAnalysis": [],
92
- "LinearRegression": [],
93
- "LogisticRegression": [],
94
- "KMeans": ["_n_threads"],
95
- # "MLPClassifier": ["_label_binarizer"], # not supported
96
- "MLPRegressor": [], # not supported
97
- "MultinomialNB": [],
98
- "PCA": [],
99
- # "Perceptron": [], # not supported
100
- "PLSRegression": ["_x_mean", "_predict_1d"],
101
- "QuadraticDiscriminantAnalysis": [],
102
- # "RandomForestClassifier": [], # not supported
103
- # "RandomForestRegressor": [], # not supported
104
- "Ridge": [],
105
- "SVC": [
106
- "_sparse",
107
- "_n_support",
108
- "_dual_coef_",
109
- "_intercept_",
110
- "_probA",
111
- "_probB",
112
- "_gamma",
113
- ],
114
- "SVR": [
115
- "_sparse",
116
- "_n_support",
117
- "_dual_coef_",
118
- "_intercept_",
119
- "_probA",
120
- "_probB",
121
- "_gamma",
122
- ],
123
- }
124
-
125
- # List of supported types for serialization
126
- SUPPORTED_TYPES: List[Type] = [
127
- bool,
128
- str,
129
- int,
130
- float,
131
- list,
132
- tuple,
133
- np.float64,
134
- np.ndarray,
135
- ]
136
-
137
-
138
- class SklearnSerializer(ModelSerializer):
139
- """
140
- Serializer for scikit-learn estimators.
141
-
142
- This class provides methods to convert scikit-learn estimators to and from
143
- dictionary representations, which can then be used with various format converters.
144
-
145
- The serializer supports a wide range of scikit-learn estimators and handles
146
- the conversion of numpy arrays and other non-JSON-serializable types.
147
-
148
- Attributes
149
- ----------
150
- SUPPORTED_ESTIMATORS : Dict[str, Type[BaseEstimator]]
151
- A dictionary of supported scikit-learn estimator classes.
152
- SUPPORTED_TYPES : List[Type]
153
- A list of supported types for serialization.
154
- """
155
-
156
- @staticmethod
157
- def _convert_to_serializable_types(value: Any) -> Any:
158
- """
159
- Convert a value to a serializable type.
160
-
161
- Parameters
162
- ----------
163
- value : Any
164
- The value to convert.
165
-
166
- Returns
167
- -------
168
- Any
169
- The serializable representation of the value.
170
- """
171
- if isinstance(value, (np.ndarray, list)):
172
- return SklearnSerializer._array_to_list(value)
173
- if isinstance(value, _csr.csr_matrix):
174
- # Convert indices and indptr to int32 explicitly
175
- csr_value = csr_matrix(value)
176
- serialized_sparse_matrix = {
177
- "data": SklearnSerializer._array_to_list(csr_value.data),
178
- "indptr": SklearnSerializer._array_to_list(
179
- csr_value.indptr.astype(np.int32)
180
- ),
181
- "indices": SklearnSerializer._array_to_list(
182
- csr_value.indices.astype(np.int32)
183
- ),
184
- "shape": SklearnSerializer._array_to_list(csr_value.shape),
185
- }
186
- return serialized_sparse_matrix
187
-
188
- return value
189
-
190
- @staticmethod
191
- def _convert_to_sklearn_types(value: Any, attr_type: str = "none") -> Any:
192
- """
193
- Convert a JSON-deserialized value to its scikit-learn type.
194
-
195
- Parameters
196
- ----------
197
- value : Any
198
- The JSON-deserialized value.
199
- attr_type : str
200
- The target type to convert to.
201
-
202
- Returns
203
- -------
204
- Any
205
- The scikit-learn type of the value.
206
- """
207
- # Base case: if attr_type is not a list, convert value based on attr_type
208
- if isinstance(attr_type, str):
209
- if attr_type == "csr_matrix":
210
- # Ensure all sparse matrix components are of correct dtype
211
- return csr_matrix(
212
- (
213
- np.array(value["data"], dtype=np.float64),
214
- np.array(value["indices"], dtype=np.int32),
215
- np.array(value["indptr"], dtype=np.int32),
216
- ),
217
- shape=tuple(value["shape"]),
218
- )
219
- elif attr_type == "ndarray":
220
- return np.array(value)
221
- elif attr_type == "int":
222
- return int(value)
223
- elif attr_type == "float":
224
- return float(value)
225
- elif attr_type == "str":
226
- return str(value)
227
- # Add other types as needed
228
- return value # Return as-is if no specific conversion is needed
229
- # Recursive case: if attr_type is a list, process each element in value
230
- elif isinstance(attr_type, list) and isinstance(value, list):
231
- return [
232
- SklearnSerializer._convert_to_sklearn_types(v, t)
233
- for v, t in zip(value, attr_type)
234
- ]
235
-
236
- return value
237
-
238
- @staticmethod
239
- def _array_to_list(array: Any) -> Any:
240
- """
241
- Recursively convert numpy arrays to nested lists.
242
-
243
- Parameters
244
- ----------
245
- array : array-like
246
- The array or nested structure to convert.
247
-
248
- Returns
249
- -------
250
- list or Any
251
- The input converted to a nested list structure, or the original value if not an array.
252
- """
253
- if isinstance(array, np.ndarray):
254
- return SklearnSerializer._array_to_list(array.tolist())
255
- elif isinstance(array, list):
256
- return [SklearnSerializer._array_to_list(item) for item in array]
257
- elif isinstance(array, tuple):
258
- return tuple(SklearnSerializer._array_to_list(item) for item in array)
259
- else:
260
- return array
261
-
262
- @staticmethod
263
- def get_nested_types(item: Any) -> Any:
264
- """
265
- Recursively determine the type of elements within nested lists.
266
-
267
- Parameters
268
- ----------
269
- item : Any
270
- The item to inspect for nested types.
271
-
272
- Returns
273
- -------
274
- Any
275
- A nested list representing the types of elements in the input item.
276
-
277
- Examples
278
- ---------
279
-
280
- [1, [1, 2, [1, 2, 3]], 2] -> ['int',['int','int','ndarray'],'int']
281
-
282
- """
283
- if isinstance(item, list) and item: # If it's a list and not empty
284
- return [SklearnSerializer.get_nested_types(subitem) for subitem in item]
285
- else:
286
- # Return the type name if it's not a list or it's an empty list
287
- return type(item).__name__
288
-
289
- def serialize(self, model: BaseEstimator) -> Dict[str, Any]:
290
- """
291
- Serialize a scikit-learn estimator to a dictionary.
292
-
293
- This method extracts relevant attributes from the model, converts them to
294
- JSON-serializable types, and returns a dictionary representation of the model.
295
-
296
- Parameters
297
- ----------
298
- model : BaseEstimator
299
- The scikit-learn estimator to serialize.
300
-
301
- Returns
302
- -------
303
- Dict[str, Any]
304
- A dictionary representation of the model.
305
-
306
- Raises
307
- ------
308
- SerializationError
309
- If the model has not been fitted or if there's an error during serialization.
310
-
311
- Examples
312
- --------
313
- >>> from sklearn.linear_model import LogisticRegression
314
- >>> from sklearn.datasets import make_classification
315
- >>> X, y = make_classification(n_samples=100, n_features=20, n_classes=2)
316
- >>> model = LogisticRegression().fit(X, y)
317
- >>> serializer = SklearnSerializer()
318
- >>> serialized_dict = serializer.serialize(model)
319
- """
320
- try:
321
- check_is_fitted(model)
322
- except NotFittedError as e:
323
- raise SerializationError("Cannot serialize an unfitted model") from e
324
-
325
- # Get all attributes that are not private, not properties, and not callable
326
- # Attributes that have been estimated from the data must always have a name ending with
327
- # trailing underscore,
328
- # for example the coefficients of some regression estimator would be stored in a
329
- # coef_ attribute after fit has been called.
330
- # https://scikit-learn.org/stable/glossary.html#term-attributes
331
- # https://scikit-learn.org/stable/developers/develop.html#estimated-attributes
332
- # NOTE: This is not always true for all estimators, but it is a good starting point.
333
- filtered_attribute_keys = [
334
- key
335
- for key in dir(model)
336
- if not key.startswith("__") # not private
337
- and key.endswith("_")
338
- and not key.endswith("__")
339
- and not isinstance(getattr(type(model), key, None), property)
340
- and not callable(getattr(model, key))
341
- ]
342
-
343
- # There are some attributes that are removed in the previous filter according to the
344
- # sklearn documentation.
345
- # However, they are still needed in the serialized model so we add them to the list.
346
- filtered_attribute_keys = (
347
- filtered_attribute_keys + ATTRIBUTE_EXCEPTIONS[model.__class__.__name__]
348
- )
349
-
350
- attribute_values = [getattr(model, key) for key in filtered_attribute_keys]
351
-
352
- # Generate attribute types with nested structure.
353
- # These types are used to convert the serialized attributes back to their original types.
354
- attribute_types = [
355
- SklearnSerializer.get_nested_types(value) for value in attribute_values
356
- ]
357
-
358
- serializable_attribute_values = [
359
- self._convert_to_serializable_types(value) for value in attribute_values
360
- ]
361
-
362
- # We losely follow the ONNX standard for the serialized model.
363
- # https://github.com/onnx/onnx/blob/main/docs/IR.md
364
- return {
365
- "attributes": dict(
366
- zip(filtered_attribute_keys, serializable_attribute_values)
367
- ),
368
- "attribute_types": dict(zip(filtered_attribute_keys, attribute_types)),
369
- "estimator_class": model.__class__.__name__,
370
- "params": model.get_params(),
371
- "producer_name": model.__module__.split(".")[0],
372
- "producer_version": model.__getstate__()["_sklearn_version"],
373
- "model_version": model.__getstate__()["_sklearn_version"],
374
- "domain": "sklearn",
375
- }
376
-
377
- def deserialize(self, data: Dict[str, Any]) -> BaseEstimator:
378
- """
379
- Deserialize a dictionary representation back into a scikit-learn estimator.
380
-
381
- This method reconstructs a scikit-learn estimator from its dictionary
382
- representation, converting attributes back to their original types.
383
-
384
- Parameters
385
- ----------
386
- data : Dict[str, Any]
387
- The dictionary representation of the model.
388
-
389
- Returns
390
- -------
391
- BaseEstimator
392
- The deserialized scikit-learn estimator.
393
-
394
- Raises
395
- ------
396
- UnsupportedEstimatorError
397
- If the estimator class is not supported.
398
-
399
- Examples
400
- --------
401
- >>> serializer = SklearnSerializer()
402
- >>> deserialized_model = serializer.deserialize(serialized_dict)
403
- >>> predictions = deserialized_model.predict(X_test)
404
- """
405
- estimator_class = data["estimator_class"]
406
- if estimator_class not in SUPPORTED_ESTIMATORS:
407
- raise UnsupportedEstimatorError(
408
- f"Unsupported estimator class: {estimator_class}"
409
- )
410
-
411
- model = SUPPORTED_ESTIMATORS[estimator_class](**data["params"])
412
-
413
- for attribute, value in data["attributes"].items():
414
- # Retrieve the attribute type from data["attribute_types"]
415
- attr_type = data["attribute_types"].get(attribute)
416
- # Pass both value and attr_type to _convert_to_sklearn_types
417
- setattr(model, attribute, self._convert_to_sklearn_types(value, attr_type))
418
-
419
- return model
File without changes