openmodels 0.1.0a2__tar.gz → 0.1.0a3__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.0a3
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
@@ -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
@@ -5,7 +5,7 @@ This module provides a serializer for scikit-learn models, allowing them to be
5
5
  converted to and from dictionary representations.
6
6
  """
7
7
 
8
- from typing import Any, Dict, List, Type
8
+ from typing import Any, Dict, Type, Optional
9
9
  import numpy as np
10
10
  from scipy.sparse import _csr, csr_matrix # type: ignore
11
11
 
@@ -122,18 +122,6 @@ ATTRIBUTE_EXCEPTIONS: Dict[str, list] = {
122
122
  ],
123
123
  }
124
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
125
 
138
126
  class SklearnSerializer(ModelSerializer):
139
127
  """
@@ -188,7 +176,9 @@ class SklearnSerializer(ModelSerializer):
188
176
  return value
189
177
 
190
178
  @staticmethod
191
- def _convert_to_sklearn_types(value: Any, attr_type: str = "none") -> Any:
179
+ def _convert_to_sklearn_types(
180
+ value: Any, attr_type: Any = "none", attr_dtype: Optional[str] = None
181
+ ) -> Any:
192
182
  """
193
183
  Convert a JSON-deserialized value to its scikit-learn type.
194
184
 
@@ -210,26 +200,30 @@ class SklearnSerializer(ModelSerializer):
210
200
  # Ensure all sparse matrix components are of correct dtype
211
201
  return csr_matrix(
212
202
  (
213
- np.array(value["data"], dtype=np.float64),
203
+ np.array(value["data"], dtype=attr_dtype or np.float64),
214
204
  np.array(value["indices"], dtype=np.int32),
215
205
  np.array(value["indptr"], dtype=np.int32),
216
206
  ),
217
207
  shape=tuple(value["shape"]),
218
208
  )
219
209
  elif attr_type == "ndarray":
220
- return np.array(value)
210
+ return np.array(value, dtype=attr_dtype or np.float64)
221
211
  elif attr_type == "int":
222
212
  return int(value)
223
213
  elif attr_type == "float":
224
214
  return float(value)
215
+ elif attr_type == "float64":
216
+ return np.float64(value)
225
217
  elif attr_type == "str":
226
218
  return str(value)
219
+ elif attr_type == "tuple":
220
+ return tuple(value)
227
221
  # Add other types as needed
228
222
  return value # Return as-is if no specific conversion is needed
229
223
  # Recursive case: if attr_type is a list, process each element in value
230
224
  elif isinstance(attr_type, list) and isinstance(value, list):
231
225
  return [
232
- SklearnSerializer._convert_to_sklearn_types(v, t)
226
+ SklearnSerializer._convert_to_sklearn_types(v, t, attr_dtype)
233
227
  for v, t in zip(value, attr_type)
234
228
  ]
235
229
 
@@ -286,6 +280,15 @@ class SklearnSerializer(ModelSerializer):
286
280
  # Return the type name if it's not a list or it's an empty list
287
281
  return type(item).__name__
288
282
 
283
+ @staticmethod
284
+ def get_dtype(value: Any) -> str:
285
+ """
286
+ Get the dtype of a numpy array, otherwise return empty string.
287
+ """
288
+ if isinstance(value, np.ndarray):
289
+ return str(value.dtype) # Get the actual numpy dtype
290
+ return ""
291
+
289
292
  def serialize(self, model: BaseEstimator) -> Dict[str, Any]:
290
293
  """
291
294
  Serialize a scikit-learn estimator to a dictionary.
@@ -359,6 +362,12 @@ class SklearnSerializer(ModelSerializer):
359
362
  self._convert_to_serializable_types(value) for value in attribute_values
360
363
  ]
361
364
 
365
+ attribute_dtypes_map = {
366
+ key: SklearnSerializer.get_dtype(value)
367
+ for key, value in zip(filtered_attribute_keys, attribute_values)
368
+ if isinstance(value, np.ndarray) # Only include NumPy arrays
369
+ }
370
+
362
371
  # We losely follow the ONNX standard for the serialized model.
363
372
  # https://github.com/onnx/onnx/blob/main/docs/IR.md
364
373
  return {
@@ -366,6 +375,7 @@ class SklearnSerializer(ModelSerializer):
366
375
  zip(filtered_attribute_keys, serializable_attribute_values)
367
376
  ),
368
377
  "attribute_types": dict(zip(filtered_attribute_keys, attribute_types)),
378
+ "attribute_dtypes": attribute_dtypes_map,
369
379
  "estimator_class": model.__class__.__name__,
370
380
  "params": model.get_params(),
371
381
  "producer_name": model.__module__.split(".")[0],
@@ -413,7 +423,13 @@ class SklearnSerializer(ModelSerializer):
413
423
  for attribute, value in data["attributes"].items():
414
424
  # Retrieve the attribute type from data["attribute_types"]
415
425
  attr_type = data["attribute_types"].get(attribute)
426
+ # Get dtype if available
427
+ attr_dtype = data.get("attribute_dtypes", {}).get(attribute)
416
428
  # Pass both value and attr_type to _convert_to_sklearn_types
417
- setattr(model, attribute, self._convert_to_sklearn_types(value, attr_type))
429
+ setattr(
430
+ model,
431
+ attribute,
432
+ self._convert_to_sklearn_types(value, attr_type, attr_dtype),
433
+ )
418
434
 
419
435
  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.3"
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>",
File without changes