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.
- openmodels/__init__.py +50 -0
- openmodels/converters/__init__.py +11 -0
- openmodels/converters/json_converter.py +61 -0
- openmodels/converters/pickle_converter.py +72 -0
- openmodels/core.py +205 -0
- openmodels/exceptions.py +26 -0
- openmodels/format_registry.py +73 -0
- openmodels/protocols.py +83 -0
- openmodels/serializers/__init__.py +10 -0
- openmodels/serializers/base.py +329 -0
- openmodels/serializers/sklearn/__init__.py +0 -0
- openmodels/serializers/sklearn/_custom_estimator.py +73 -0
- openmodels/serializers/sklearn/sklearn_serializer.py +1248 -0
- openmodels/test_helpers.py +540 -0
- openmodels-0.1.0.dist-info/METADATA +274 -0
- openmodels-0.1.0.dist-info/RECORD +18 -0
- openmodels-0.1.0.dist-info/WHEEL +4 -0
- openmodels-0.1.0.dist-info/licenses/LICENSE +19 -0
|
@@ -0,0 +1,540 @@
|
|
|
1
|
+
"""
|
|
2
|
+
This file contains functions for testing the serialization and deserialization of scikit-learn
|
|
3
|
+
models using the `openmodels` library.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import functools
|
|
7
|
+
import os
|
|
8
|
+
from contextlib import contextmanager
|
|
9
|
+
from typing import (
|
|
10
|
+
Iterator,
|
|
11
|
+
Optional,
|
|
12
|
+
Type,
|
|
13
|
+
Union,
|
|
14
|
+
Protocol,
|
|
15
|
+
runtime_checkable,
|
|
16
|
+
TypeVar,
|
|
17
|
+
cast,
|
|
18
|
+
)
|
|
19
|
+
import numpy as np
|
|
20
|
+
from numpy import testing
|
|
21
|
+
from sklearn.base import BaseEstimator
|
|
22
|
+
from sklearn.feature_extraction import FeatureHasher
|
|
23
|
+
from sklearn.feature_selection import GenericUnivariateSelect, f_classif
|
|
24
|
+
from sklearn.preprocessing import LabelBinarizer
|
|
25
|
+
from scipy.sparse import csr_matrix # type: ignore
|
|
26
|
+
|
|
27
|
+
from openmodels import SerializationManager, SklearnSerializer
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def assert_sparse_matrix_equal(a, b):
|
|
31
|
+
"""Assert that two sparse matrices are equal in shape and values (as float64)."""
|
|
32
|
+
assert type(a) is type(b)
|
|
33
|
+
assert a.shape == b.shape
|
|
34
|
+
np.testing.assert_allclose(
|
|
35
|
+
a.toarray().astype(np.float64), b.toarray().astype(np.float64)
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@runtime_checkable
|
|
40
|
+
class PredictorModel(Protocol):
|
|
41
|
+
def predict(self, X: Union[np.ndarray, csr_matrix]) -> np.ndarray: ...
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@runtime_checkable
|
|
45
|
+
class TransformerModel(Protocol):
|
|
46
|
+
def transform(self, X: Union[np.ndarray, csr_matrix]) -> np.ndarray: ...
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@runtime_checkable
|
|
50
|
+
class FittableModel(Protocol):
|
|
51
|
+
def fit(
|
|
52
|
+
self, X: Union[np.ndarray, csr_matrix], y: np.ndarray
|
|
53
|
+
) -> "FittableModel": ...
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
ModelType = Union[PredictorModel, TransformerModel, FittableModel]
|
|
57
|
+
T = TypeVar("T", bound=Union[BaseEstimator, ModelType])
|
|
58
|
+
|
|
59
|
+
_ROUNDTRIPPABLE_METHODS = ("fit", "fit_transform", "fit_predict")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@contextmanager
|
|
63
|
+
def roundtrip_fit(
|
|
64
|
+
*classes: Type[BaseEstimator], format_name: str = "json"
|
|
65
|
+
) -> Iterator[None]:
|
|
66
|
+
"""
|
|
67
|
+
Monkeypatch fit()/fit_transform()/fit_predict() on the given estimator classes so that,
|
|
68
|
+
immediately after fitting, the estimator's *fitted* attributes are replaced with the result
|
|
69
|
+
of an openmodels serialize -> deserialize round-trip. Restores the original methods on exit.
|
|
70
|
+
|
|
71
|
+
Only methods defined directly on the class are patched (not inherited ones), since e.g.
|
|
72
|
+
TransformerMixin.fit_transform already calls self.fit(...) and would be covered by patching
|
|
73
|
+
fit alone; only classes that override fit_transform/fit_predict directly need those patched.
|
|
74
|
+
|
|
75
|
+
Only attributes openmodels actually serializes as fitted state (per
|
|
76
|
+
SklearnSerializer._extract_estimator_attributes - sklearn's trailing-underscore convention,
|
|
77
|
+
plus the small set of private attributes some estimators need at predict time) are copied
|
|
78
|
+
back onto the original instance. Constructor-set parameters are deliberately left untouched:
|
|
79
|
+
JSON has no tuple type, so e.g. a tuple-valued param would come back as a list after a
|
|
80
|
+
round-trip even though openmodels never claims to preserve exact param typing - copying it
|
|
81
|
+
over would make the *test infrastructure* look like a fidelity bug in checks like
|
|
82
|
+
check_dont_overwrite_parameters.
|
|
83
|
+
|
|
84
|
+
This lets sklearn's own estimator-specific test suites be reused unmodified against
|
|
85
|
+
round-tripped models: any assertion they make about a fitted estimator becomes, implicitly,
|
|
86
|
+
an openmodels fidelity check.
|
|
87
|
+
"""
|
|
88
|
+
serializer = SklearnSerializer()
|
|
89
|
+
manager = SerializationManager(serializer)
|
|
90
|
+
originals: dict = {}
|
|
91
|
+
|
|
92
|
+
def _roundtrip(instance) -> None:
|
|
93
|
+
fitted_keys = serializer._extract_estimator_attributes(instance).keys()
|
|
94
|
+
serialized = manager.serialize(instance, format_name=format_name)
|
|
95
|
+
deserialized = manager.deserialize(serialized, format_name=format_name)
|
|
96
|
+
for key in fitted_keys:
|
|
97
|
+
if hasattr(deserialized, key):
|
|
98
|
+
setattr(instance, key, getattr(deserialized, key))
|
|
99
|
+
|
|
100
|
+
class _RoundtripDescriptor:
|
|
101
|
+
"""
|
|
102
|
+
Wraps `orig` (a plain function, or a descriptor like sklearn's @available_if or a
|
|
103
|
+
property) so attribute access still goes through __get__ first. This matters because
|
|
104
|
+
many sklearn meta-estimators (Pipeline, FeatureAgglomeration, ...) use
|
|
105
|
+
hasattr(estimator, "fit_transform")-style availability checks that rely on the
|
|
106
|
+
descriptor's __get__ raising AttributeError when the method isn't actually available
|
|
107
|
+
(e.g. a Pipeline whose last step has no transform()). Replacing the class attribute
|
|
108
|
+
with a plain function would make it unconditionally "available", breaking that check
|
|
109
|
+
for everyone who does hasattr() introspection - not just this test suite.
|
|
110
|
+
"""
|
|
111
|
+
|
|
112
|
+
def __init__(self, orig):
|
|
113
|
+
self._orig = orig
|
|
114
|
+
|
|
115
|
+
def __get__(self, obj, objtype=None):
|
|
116
|
+
if obj is None:
|
|
117
|
+
return self
|
|
118
|
+
# Raises AttributeError here (not inside the call below) if unavailable, exactly
|
|
119
|
+
# like normal attribute access on the original descriptor would.
|
|
120
|
+
bound_orig = self._orig.__get__(obj, objtype)
|
|
121
|
+
|
|
122
|
+
@functools.wraps(bound_orig)
|
|
123
|
+
def wrapper(*args, **kwargs):
|
|
124
|
+
result = bound_orig(*args, **kwargs)
|
|
125
|
+
_roundtrip(obj)
|
|
126
|
+
return result
|
|
127
|
+
|
|
128
|
+
return wrapper
|
|
129
|
+
|
|
130
|
+
for cls in classes:
|
|
131
|
+
for method_name in _ROUNDTRIPPABLE_METHODS:
|
|
132
|
+
if method_name in vars(cls):
|
|
133
|
+
orig = vars(cls)[method_name]
|
|
134
|
+
originals[(cls, method_name)] = orig
|
|
135
|
+
setattr(cls, method_name, _RoundtripDescriptor(orig))
|
|
136
|
+
|
|
137
|
+
try:
|
|
138
|
+
yield
|
|
139
|
+
finally:
|
|
140
|
+
for (cls, method_name), orig in originals.items():
|
|
141
|
+
setattr(cls, method_name, orig)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def ensure_correct_sparse_format(
|
|
145
|
+
x: Union[np.ndarray, csr_matrix],
|
|
146
|
+
) -> Union[np.ndarray, csr_matrix]:
|
|
147
|
+
"""
|
|
148
|
+
Ensure the input data is in the correct format for SVM models.
|
|
149
|
+
"""
|
|
150
|
+
if isinstance(x, csr_matrix):
|
|
151
|
+
# Create a new sparse matrix with correct dtypes
|
|
152
|
+
data = x.data.astype(np.float64)
|
|
153
|
+
indices = x.indices.astype(np.int32)
|
|
154
|
+
indptr = x.indptr.astype(np.int32)
|
|
155
|
+
|
|
156
|
+
# Ensure the indices are properly sorted
|
|
157
|
+
for i in range(x.shape[0]):
|
|
158
|
+
start = indptr[i]
|
|
159
|
+
end = indptr[i + 1]
|
|
160
|
+
if end - start > 0: # If row is not empty
|
|
161
|
+
order = np.argsort(indices[start:end])
|
|
162
|
+
indices[start:end] = indices[start:end][order]
|
|
163
|
+
data[start:end] = data[start:end][order]
|
|
164
|
+
|
|
165
|
+
return csr_matrix(
|
|
166
|
+
(data, indices, indptr),
|
|
167
|
+
shape=x.shape,
|
|
168
|
+
copy=False, # Avoid unnecessary data copying
|
|
169
|
+
)
|
|
170
|
+
return x
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def fit_model(
|
|
174
|
+
model: FittableModel,
|
|
175
|
+
x: Union[np.ndarray, csr_matrix],
|
|
176
|
+
y: np.ndarray,
|
|
177
|
+
abs: bool = False,
|
|
178
|
+
) -> FittableModel:
|
|
179
|
+
"""
|
|
180
|
+
Fits a model to the provided data.
|
|
181
|
+
|
|
182
|
+
Parameters
|
|
183
|
+
----------
|
|
184
|
+
model : FittableModel
|
|
185
|
+
The scikit-learn model to fit.
|
|
186
|
+
x : Union[np.ndarray, csr_matrix]
|
|
187
|
+
The training input samples.
|
|
188
|
+
y : np.ndarray
|
|
189
|
+
The target values (class labels in classification, real numbers in regression).
|
|
190
|
+
abs : bool, default=False
|
|
191
|
+
Whether to take the absolute value of the input data before fitting the model.
|
|
192
|
+
|
|
193
|
+
Returns
|
|
194
|
+
-------
|
|
195
|
+
FittableModel
|
|
196
|
+
The fitted scikit-learn model.
|
|
197
|
+
"""
|
|
198
|
+
if not isinstance(model, FittableModel):
|
|
199
|
+
raise TypeError("Model must have a 'fit' method")
|
|
200
|
+
|
|
201
|
+
# Special case for LabelBinarizer
|
|
202
|
+
if isinstance(model, LabelBinarizer):
|
|
203
|
+
model.fit(y)
|
|
204
|
+
return model
|
|
205
|
+
|
|
206
|
+
if abs:
|
|
207
|
+
if isinstance(x, csr_matrix):
|
|
208
|
+
# Handle absolute value for sparse matrix
|
|
209
|
+
x_abs = csr_matrix(
|
|
210
|
+
(np.absolute(x.data), x.indices, x.indptr), shape=x.shape
|
|
211
|
+
)
|
|
212
|
+
model.fit(x_abs, y)
|
|
213
|
+
else:
|
|
214
|
+
model.fit(np.absolute(x), y)
|
|
215
|
+
else:
|
|
216
|
+
model.fit(x, y)
|
|
217
|
+
return model
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def run_test_predictions(
|
|
221
|
+
model1: Union[PredictorModel, TransformerModel],
|
|
222
|
+
model2: Union[PredictorModel, TransformerModel],
|
|
223
|
+
x: Union[np.ndarray, csr_matrix],
|
|
224
|
+
abs: bool = False,
|
|
225
|
+
) -> None:
|
|
226
|
+
"""
|
|
227
|
+
Test if two models produce the same predictions.
|
|
228
|
+
"""
|
|
229
|
+
# Always ensure input data is in correct format, even for dense arrays
|
|
230
|
+
x = ensure_correct_sparse_format(x)
|
|
231
|
+
|
|
232
|
+
if isinstance(model1, PredictorModel) and isinstance(model2, PredictorModel):
|
|
233
|
+
if abs:
|
|
234
|
+
if isinstance(x, csr_matrix):
|
|
235
|
+
x_abs = csr_matrix(
|
|
236
|
+
(
|
|
237
|
+
np.absolute(x.data),
|
|
238
|
+
x.indices.astype(np.int32),
|
|
239
|
+
x.indptr.astype(np.int32),
|
|
240
|
+
),
|
|
241
|
+
shape=x.shape,
|
|
242
|
+
)
|
|
243
|
+
actual_predictions = model1.predict(x_abs)
|
|
244
|
+
expected_predictions = model2.predict(x_abs)
|
|
245
|
+
else:
|
|
246
|
+
actual_predictions = model1.predict(np.absolute(x))
|
|
247
|
+
expected_predictions = model2.predict(np.absolute(x))
|
|
248
|
+
else:
|
|
249
|
+
actual_predictions = model1.predict(x)
|
|
250
|
+
expected_predictions = model2.predict(x)
|
|
251
|
+
testing.assert_array_almost_equal(actual_predictions, expected_predictions)
|
|
252
|
+
elif isinstance(model1, TransformerModel) and isinstance(model2, TransformerModel):
|
|
253
|
+
if abs:
|
|
254
|
+
if isinstance(x, csr_matrix):
|
|
255
|
+
x_abs = csr_matrix(
|
|
256
|
+
(
|
|
257
|
+
np.absolute(x.data),
|
|
258
|
+
x.indices.astype(np.int32),
|
|
259
|
+
x.indptr.astype(np.int32),
|
|
260
|
+
),
|
|
261
|
+
shape=x.shape,
|
|
262
|
+
)
|
|
263
|
+
actual_predictions = model1.transform(x_abs)
|
|
264
|
+
expected_predictions = model2.transform(x_abs)
|
|
265
|
+
else:
|
|
266
|
+
actual_predictions = model1.transform(np.absolute(x))
|
|
267
|
+
expected_predictions = model2.transform(np.absolute(x))
|
|
268
|
+
else:
|
|
269
|
+
actual_predictions = model1.transform(x)
|
|
270
|
+
expected_predictions = model2.transform(x)
|
|
271
|
+
if isinstance(actual_predictions, csr_matrix) and isinstance(
|
|
272
|
+
expected_predictions, csr_matrix
|
|
273
|
+
):
|
|
274
|
+
assert_sparse_matrix_equal(actual_predictions, expected_predictions)
|
|
275
|
+
else:
|
|
276
|
+
testing.assert_array_almost_equal(actual_predictions, expected_predictions)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def run_test_transformed_data(
|
|
280
|
+
model1: TransformerModel, model2: TransformerModel, x: Union[np.ndarray, csr_matrix]
|
|
281
|
+
) -> None:
|
|
282
|
+
"""
|
|
283
|
+
Compares the transformed data of two models on the given data.
|
|
284
|
+
|
|
285
|
+
Parameters
|
|
286
|
+
----------
|
|
287
|
+
model1 : TransformerModel
|
|
288
|
+
The first scikit-learn model with a transform method.
|
|
289
|
+
model2 : TransformerModel
|
|
290
|
+
The second scikit-learn model with a transform method.
|
|
291
|
+
x : Union[np.ndarray, csr_matrix]
|
|
292
|
+
The input samples.
|
|
293
|
+
|
|
294
|
+
Raises
|
|
295
|
+
------
|
|
296
|
+
AssertionError
|
|
297
|
+
If the transformed data of the two models are not almost equal.
|
|
298
|
+
"""
|
|
299
|
+
expected_transformed_data = model1.transform(x)
|
|
300
|
+
actual_transformed_data = model2.transform(x)
|
|
301
|
+
if isinstance(expected_transformed_data, csr_matrix) and isinstance(
|
|
302
|
+
actual_transformed_data, csr_matrix
|
|
303
|
+
):
|
|
304
|
+
assert_sparse_matrix_equal(expected_transformed_data, actual_transformed_data)
|
|
305
|
+
else:
|
|
306
|
+
testing.assert_array_almost_equal(
|
|
307
|
+
expected_transformed_data, actual_transformed_data
|
|
308
|
+
)
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def run_test_model(
|
|
312
|
+
model: FittableModel,
|
|
313
|
+
x: Union[np.ndarray, csr_matrix],
|
|
314
|
+
y: np.ndarray,
|
|
315
|
+
x_sparse: Optional[Union[np.ndarray, csr_matrix]],
|
|
316
|
+
y_sparse: Optional[np.ndarray],
|
|
317
|
+
model_name: str,
|
|
318
|
+
abs: bool = False,
|
|
319
|
+
) -> None:
|
|
320
|
+
"""
|
|
321
|
+
Tests the serialization and deserialization of a scikit-learn model.
|
|
322
|
+
|
|
323
|
+
Parameters
|
|
324
|
+
----------
|
|
325
|
+
model : Union[BaseEstimator, ModelType]
|
|
326
|
+
The scikit-learn model to test.
|
|
327
|
+
x : Union[np.ndarray, csr_matrix]
|
|
328
|
+
The training input samples.
|
|
329
|
+
y : np.ndarray
|
|
330
|
+
The target values (class labels in classification, real numbers in regression).
|
|
331
|
+
x_sparse : Optional[Union[np.ndarray, csr_matrix]]
|
|
332
|
+
The sparse training input samples.
|
|
333
|
+
y_sparse : np.ndarray or None
|
|
334
|
+
The sparse target values.
|
|
335
|
+
model_name : str
|
|
336
|
+
The name of the file to save the serialized model to.
|
|
337
|
+
abs : bool, default=False
|
|
338
|
+
Whether to take the absolute value of the input data before fitting the model.
|
|
339
|
+
"""
|
|
340
|
+
# Always ensure input data is in correct format, regardless of type
|
|
341
|
+
x = ensure_correct_sparse_format(x)
|
|
342
|
+
if x_sparse is not None:
|
|
343
|
+
x_sparse = ensure_correct_sparse_format(x_sparse)
|
|
344
|
+
|
|
345
|
+
# Fit and test the model
|
|
346
|
+
fitted_model = fit_model(model, x, y, abs)
|
|
347
|
+
|
|
348
|
+
if x_sparse is not None and y_sparse is not None:
|
|
349
|
+
fit_model(model, x_sparse, y_sparse, abs)
|
|
350
|
+
|
|
351
|
+
# Create a SerializationManager instance
|
|
352
|
+
manager = SerializationManager(SklearnSerializer())
|
|
353
|
+
|
|
354
|
+
# Serialize and deserialize the model
|
|
355
|
+
serialized_model = manager.serialize(fitted_model, format_name="json")
|
|
356
|
+
deserialized_model = manager.deserialize(serialized_model, format_name="json")
|
|
357
|
+
|
|
358
|
+
# Test the deserialized model with properly formatted data
|
|
359
|
+
if isinstance(model, PredictorModel):
|
|
360
|
+
run_test_predictions(
|
|
361
|
+
cast(PredictorModel, fitted_model),
|
|
362
|
+
cast(PredictorModel, deserialized_model),
|
|
363
|
+
x, # x is already properly formatted
|
|
364
|
+
abs,
|
|
365
|
+
)
|
|
366
|
+
elif isinstance(model, TransformerModel):
|
|
367
|
+
run_test_transformed_data(
|
|
368
|
+
cast(TransformerModel, fitted_model),
|
|
369
|
+
cast(TransformerModel, deserialized_model),
|
|
370
|
+
x, # x is already properly formatted
|
|
371
|
+
)
|
|
372
|
+
|
|
373
|
+
# Serialize and deserialize the model to/from a file
|
|
374
|
+
model_file_path = f"./test/temp/{model_name}.json"
|
|
375
|
+
|
|
376
|
+
# Ensure the directory exists
|
|
377
|
+
os.makedirs(os.path.dirname(model_file_path), exist_ok=True)
|
|
378
|
+
|
|
379
|
+
with open(model_file_path, "w", encoding="utf-8") as f:
|
|
380
|
+
f.write(serialized_model)
|
|
381
|
+
|
|
382
|
+
with open(model_file_path, "r", encoding="utf-8") as f:
|
|
383
|
+
serialized_model_from_file = f.read()
|
|
384
|
+
|
|
385
|
+
deserialized_model_from_file = manager.deserialize(
|
|
386
|
+
serialized_model_from_file, format_name="json"
|
|
387
|
+
)
|
|
388
|
+
|
|
389
|
+
# Test the deserialized model from file
|
|
390
|
+
if isinstance(model, PredictorModel):
|
|
391
|
+
run_test_predictions(
|
|
392
|
+
cast(PredictorModel, fitted_model),
|
|
393
|
+
cast(PredictorModel, deserialized_model_from_file),
|
|
394
|
+
x,
|
|
395
|
+
abs, # Pass the abs parameter to run_test_predictions
|
|
396
|
+
)
|
|
397
|
+
elif isinstance(model, TransformerModel):
|
|
398
|
+
run_test_transformed_data(
|
|
399
|
+
cast(TransformerModel, fitted_model),
|
|
400
|
+
cast(TransformerModel, deserialized_model_from_file),
|
|
401
|
+
x,
|
|
402
|
+
)
|
|
403
|
+
|
|
404
|
+
# Clean up the temporary file
|
|
405
|
+
os.remove(model_file_path)
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def create_test_data(
|
|
409
|
+
n_samples: int = 100, n_features: int = 5, random_state: int = 42
|
|
410
|
+
) -> tuple:
|
|
411
|
+
"""
|
|
412
|
+
Creates test data for model fitting and testing.
|
|
413
|
+
|
|
414
|
+
Parameters
|
|
415
|
+
----------
|
|
416
|
+
n_samples : int, optional
|
|
417
|
+
The number of samples to generate (default is 100).
|
|
418
|
+
n_features : int, optional
|
|
419
|
+
The number of features to generate (default is 5).
|
|
420
|
+
random_state : int, optional
|
|
421
|
+
The random state for reproducibility (default is 42).
|
|
422
|
+
|
|
423
|
+
Returns
|
|
424
|
+
-------
|
|
425
|
+
tuple
|
|
426
|
+
A tuple containing (X, y) where X is the feature matrix and y is the target vector.
|
|
427
|
+
"""
|
|
428
|
+
np.random.seed(random_state)
|
|
429
|
+
x = np.random.randn(n_samples, n_features)
|
|
430
|
+
y = np.random.randint(0, 2, size=n_samples)
|
|
431
|
+
return x, y
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def run_test_label_binarizer(
|
|
435
|
+
model: LabelBinarizer,
|
|
436
|
+
y: np.ndarray,
|
|
437
|
+
model_name: str,
|
|
438
|
+
) -> None:
|
|
439
|
+
"""
|
|
440
|
+
Special test for LabelBinarizer: fit and transform only use y.
|
|
441
|
+
"""
|
|
442
|
+
# Fit the model
|
|
443
|
+
model.fit(y)
|
|
444
|
+
transformed = model.transform(y)
|
|
445
|
+
|
|
446
|
+
# Serialize and deserialize
|
|
447
|
+
manager = SerializationManager(SklearnSerializer())
|
|
448
|
+
serialized_model = manager.serialize(model, format_name="json")
|
|
449
|
+
deserialized_model = manager.deserialize(serialized_model, format_name="json")
|
|
450
|
+
|
|
451
|
+
# Test transform output
|
|
452
|
+
transformed_deserialized = deserialized_model.transform(y)
|
|
453
|
+
testing.assert_array_equal(transformed, transformed_deserialized)
|
|
454
|
+
|
|
455
|
+
# File round-trip
|
|
456
|
+
model_file_path = f"./test/temp/{model_name}.json"
|
|
457
|
+
os.makedirs(os.path.dirname(model_file_path), exist_ok=True)
|
|
458
|
+
with open(model_file_path, "w", encoding="utf-8") as f:
|
|
459
|
+
f.write(serialized_model)
|
|
460
|
+
with open(model_file_path, "r", encoding="utf-8") as f:
|
|
461
|
+
serialized_model_from_file = f.read()
|
|
462
|
+
deserialized_model_from_file = manager.deserialize(
|
|
463
|
+
serialized_model_from_file, format_name="json"
|
|
464
|
+
)
|
|
465
|
+
transformed_from_file = deserialized_model_from_file.transform(y)
|
|
466
|
+
testing.assert_array_equal(transformed, transformed_from_file)
|
|
467
|
+
os.remove(model_file_path)
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
def test_multilabelbinarizer_minimal():
|
|
471
|
+
from sklearn.preprocessing import MultiLabelBinarizer
|
|
472
|
+
from openmodels.serializers.sklearn.sklearn_serializer import SklearnSerializer
|
|
473
|
+
from openmodels import SerializationManager
|
|
474
|
+
import numpy as np
|
|
475
|
+
|
|
476
|
+
# Integer labels
|
|
477
|
+
y_int = [(1, 2), (3,)]
|
|
478
|
+
mlb = MultiLabelBinarizer()
|
|
479
|
+
transformed = mlb.fit_transform(y_int)
|
|
480
|
+
classes = mlb.classes_.copy()
|
|
481
|
+
|
|
482
|
+
manager = SerializationManager(SklearnSerializer())
|
|
483
|
+
serialized = manager.serialize(mlb)
|
|
484
|
+
mlb2 = manager.deserialize(serialized)
|
|
485
|
+
|
|
486
|
+
np.testing.assert_array_equal(classes, mlb2.classes_)
|
|
487
|
+
np.testing.assert_array_equal(transformed, mlb2.transform(y_int))
|
|
488
|
+
|
|
489
|
+
# String labels
|
|
490
|
+
y_str = [{"sci-fi", "thriller"}, {"comedy"}]
|
|
491
|
+
mlb = MultiLabelBinarizer()
|
|
492
|
+
transformed = mlb.fit_transform(y_str)
|
|
493
|
+
classes = list(mlb.classes_)
|
|
494
|
+
|
|
495
|
+
serialized = manager.serialize(mlb)
|
|
496
|
+
mlb2 = manager.deserialize(serialized)
|
|
497
|
+
|
|
498
|
+
assert list(mlb2.classes_) == classes
|
|
499
|
+
np.testing.assert_array_equal(transformed, mlb2.transform(y_str))
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def test_feature_hasher_serialization():
|
|
503
|
+
# Example 1: Using dictionaries as input
|
|
504
|
+
hasher_dict = FeatureHasher(n_features=10)
|
|
505
|
+
D = [{"dog": 1, "cat": 2, "elephant": 4}, {"dog": 2, "run": 5}]
|
|
506
|
+
transformed_dict = hasher_dict.transform(D).toarray()
|
|
507
|
+
|
|
508
|
+
# Example 2: Using strings as input
|
|
509
|
+
hasher_string = FeatureHasher(n_features=8, input_type="string")
|
|
510
|
+
raw_X = [["dog", "cat", "snake"], ["snake", "dog"], ["cat", "bird"]]
|
|
511
|
+
transformed_string = hasher_string.transform(raw_X).toarray()
|
|
512
|
+
|
|
513
|
+
# Assertions for Example 1
|
|
514
|
+
assert transformed_dict.shape == (2, 10), "Unexpected shape for dictionary input"
|
|
515
|
+
assert not np.all(
|
|
516
|
+
transformed_dict == 0
|
|
517
|
+
), "Transformation failed for dictionary input"
|
|
518
|
+
|
|
519
|
+
# Assertions for Example 2
|
|
520
|
+
assert transformed_string.shape == (3, 8), "Unexpected shape for string input"
|
|
521
|
+
assert not np.all(transformed_string == 0), "Transformation failed for string input"
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def test_generic_univariate_select_serialization():
|
|
525
|
+
# Create the transformer
|
|
526
|
+
transformer = GenericUnivariateSelect(
|
|
527
|
+
score_func=f_classif, mode="percentile", param=50
|
|
528
|
+
)
|
|
529
|
+
|
|
530
|
+
# Serialize the transformer
|
|
531
|
+
serializer = SklearnSerializer()
|
|
532
|
+
serialized = serializer.serialize(transformer)
|
|
533
|
+
|
|
534
|
+
# Deserialize the transformer
|
|
535
|
+
deserialized = serializer.deserialize(serialized)
|
|
536
|
+
|
|
537
|
+
# Check that the deserialized transformer works as expected
|
|
538
|
+
assert deserialized.score_func == f_classif
|
|
539
|
+
assert deserialized.mode == "percentile"
|
|
540
|
+
assert deserialized.param == 50
|