openmodels 0.1.0__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.
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2024 Gnpd
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
@@ -0,0 +1,274 @@
1
+ Metadata-Version: 2.4
2
+ Name: openmodels
3
+ Version: 0.1.0
4
+ Summary: Export scikit-learn model files to JSON for sharing or deploying predictive models with peace of mind.
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Keywords: scikit-learn,serialization,machine-learning,json,model-export,mlops
8
+ Author: Alejandro Gutierrez
9
+ Author-email: a.gutierrez@g-npd.com
10
+ Requires-Python: >=3.10,<4.0
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Requires-Dist: scikit-learn (>=1.6.0,<2.0.0)
23
+ Project-URL: Changelog, https://github.com/Gnpd/openmodels/blob/main/CHANGELOG.md
24
+ Project-URL: Documentation, https://gnpd.github.io/openmodels/
25
+ Project-URL: Homepage, https://gnpd.github.io/openmodels/
26
+ Project-URL: Issues, https://github.com/Gnpd/openmodels/issues
27
+ Project-URL: Repository, https://github.com/Gnpd/openmodels
28
+ Description-Content-Type: text/markdown
29
+
30
+ # OpenModels
31
+
32
+ [![PyPI version](https://badge.fury.io/py/openmodels.svg?cacheBust=1)](https://badge.fury.io/py/openmodels)
33
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
34
+ [![Python Versions](https://img.shields.io/pypi/pyversions/openmodels.svg?cacheBust=1)](https://pypi.org/project/openmodels/)
35
+
36
+ OpenModels is a flexible and extensible library for serializing and deserializing machine learning models. It's designed to support any serialization format through a plugin-based architecture, providing a safe and transparent solution for exporting and sharing predictive models.
37
+
38
+ ## Key Features
39
+
40
+ - **Format Agnostic**: Supports any serialization format through a plugin-based system.
41
+ - **Extensible**: Easily add support for new model types and serialization formats.
42
+ - **Safe**: Provides alternatives to potentially unsafe serialization methods like Pickle (see [Security](#security)).
43
+ - **Transparent**: Supports human-readable formats for easy inspection of serialized models.
44
+
45
+ ## Installation
46
+
47
+ ```bash
48
+ pip install openmodels
49
+ ```
50
+
51
+ ## Quick Start
52
+
53
+ ```python
54
+ from openmodels import SerializationManager, SklearnSerializer
55
+ from sklearn.decomposition import PCA
56
+ from sklearn.datasets import make_classification
57
+
58
+ # Create and train a scikit-learn model
59
+ X, _ = make_classification(n_samples=1000, n_features=4, n_informative=2, n_redundant=0, random_state=0, shuffle=False)
60
+ model = PCA(n_components=2, random_state=0)
61
+ model.fit(X)
62
+
63
+ # Create a SerializationManager
64
+ manager = SerializationManager(SklearnSerializer())
65
+
66
+ # Serialize the model (default format is JSON)
67
+ serialized_model = manager.serialize(model)
68
+
69
+ # Deserialize the model
70
+ deserialized_model = manager.deserialize(serialized_model)
71
+
72
+ # Use the deserialized model
73
+ transformed_data = deserialized_model.transform(X[:5])
74
+ print(transformed_data)
75
+ ```
76
+
77
+ ## Saving and Loading Models
78
+ OpenModels provides high-level `save` and `load` methods for convenient file I/O:
79
+
80
+ ```python
81
+ # Serialize and save a model to a file in JSON format
82
+ manager.save(model, "model.json", format_name="json")
83
+
84
+ # Load and deserialize a model from a file
85
+ loaded_model = manager.load("model.json", format_name="json")
86
+ ```
87
+
88
+ ## Extensibility
89
+
90
+ OpenModels is designed to be easily extended with new serialization formats and model types.
91
+
92
+ ### Adding a New Format
93
+
94
+ To add a new serialization format, create a class that implements the `FormatConverter` protocol and register it with the `FormatRegistry`:
95
+
96
+ ```python
97
+ from openmodels.protocols import FormatConverter
98
+ from openmodels.format_registry import FormatRegistry
99
+ from typing import Dict, Any
100
+
101
+ class YAMLConverter(FormatConverter):
102
+ @staticmethod
103
+ def serialize_to_format(data: Dict[str, Any]) -> str:
104
+ import yaml
105
+ return yaml.dump(data)
106
+
107
+ @staticmethod
108
+ def deserialize_from_format(formatted_data: str) -> Dict[str, Any]:
109
+ import yaml
110
+ return yaml.safe_load(formatted_data)
111
+
112
+ FormatRegistry.register("yaml", YAMLConverter)
113
+ ```
114
+
115
+ ### Adding a New Model Serializer
116
+
117
+ To add support for a new type of model, create a class that implements the `ModelSerializer` protocol:
118
+
119
+ ```python
120
+ from openmodels.protocols import ModelSerializer
121
+ from typing import Any, Dict
122
+
123
+ class TensorFlowSerializer(ModelSerializer):
124
+ def serialize(self, model: Any) -> Dict[str, Any]:
125
+ # Implementation for serializing TensorFlow models
126
+ ...
127
+
128
+ def deserialize(self, data: Dict[str, Any]) -> Any:
129
+ # Implementation for deserializing TensorFlow models
130
+ ...
131
+ ```
132
+
133
+ ## Supported Models (scikit-learn)
134
+
135
+ OpenModels supports every scikit-learn estimator, including:
136
+
137
+ - Classification: LogisticRegression, SVC, etc.
138
+ - Regression: LinearRegression, SVR, etc.
139
+ - Clustering: KMeans
140
+ - Dimensionality Reduction: PCA
141
+
142
+ See the [Supported Models](https://gnpd.github.io/openmodels/supported_models.html) docs page
143
+ for the full breakdown by category, and the
144
+ [serialized format reference](https://gnpd.github.io/openmodels/format.html) for what actually
145
+ gets written to disk.
146
+
147
+ You can also retrieve the list programmatically using the `SklearnSerializer.all_estimators()` method:
148
+
149
+ ```python
150
+ from openmodels.serializers import SklearnSerializer
151
+
152
+ # Get all supported estimators (classifiers, regressors, etc.)
153
+ all_supported = SklearnSerializer.all_estimators()
154
+ print([name for name, cls in all_supported])
155
+
156
+ # To get only classifiers:
157
+ classifiers = SklearnSerializer.all_estimators(type_filter="classifier")
158
+ print([name for name, cls in classifiers])
159
+
160
+ # To get only regressors:
161
+ regressors = SklearnSerializer.all_estimators(type_filter="regressor")
162
+ print([name for name, cls in regressors])
163
+ ```
164
+
165
+ ## Using Custom Estimators and Pipelines (Third-Party Support)
166
+
167
+ OpenModels can serialize and deserialize models and pipelines that include third-party estimators, such as those from [chemotools](https://github.com/paucablop/chemotools).
168
+
169
+ ```python
170
+ from openmodels import SerializationManager, SklearnSerializer
171
+ from chemotools.utils.discovery import all_estimators # chemotools >=0.2.2
172
+ from chemotools.derivative import SavitzkyGolay
173
+ from sklearn.cross_decomposition import PLSRegression
174
+ from sklearn.pipeline import make_pipeline
175
+
176
+ # Example data
177
+ from chemotools.datasets import load_fermentation_train
178
+ X_train, y_train = load_fermentation_train()
179
+
180
+ # Define a pipeline with chemotools preprocessing and sklearn estimator
181
+ pipeline = make_pipeline(
182
+ SavitzkyGolay(window_size=3, polynomial_order=1, derivate_order=1),
183
+ PLSRegression(n_components=2)
184
+ )
185
+
186
+ # Fit the pipeline
187
+ pipeline.fit(X_train, y_train)
188
+
189
+ # Serialize and deserialize the pipeline using OpenModels
190
+ serializer = SklearnSerializer(custom_estimators=all_estimators)
191
+ manager = SerializationManager(serializer)
192
+
193
+ serialized = manager.serialize(pipeline)
194
+ restored = manager.deserialize(serialized)
195
+
196
+ # Use the restored pipeline
197
+ y_train_pred = restored.predict(X_train)
198
+ print(y_train_pred)
199
+ ```
200
+
201
+ You can pass any compatible `all_estimators` function, list, or dictionary to `SklearnSerializer(custom_estimators=...)` to extend support for custom or third-party estimators.
202
+
203
+ ## scikit-learn Version Compatibility
204
+
205
+ OpenModels is tested against the following scikit-learn versions via the on-demand [`scikit-learn compatibility`](https://github.com/Gnpd/openmodels/actions/workflows/sklearn-compat.yml) CI workflow:
206
+
207
+ | scikit-learn | Status |
208
+ |---|---|
209
+ | 1.6.1 | ✅ Tested |
210
+ | 1.7.2 | ✅ Tested |
211
+ | 1.8.0 | ✅ Tested |
212
+ | 1.9.0 | ✅ Tested |
213
+
214
+ If you encounter any incompatibility or a use case where the library does not work correctly with your version of scikit-learn, please [open an issue](https://github.com/Gnpd/openmodels/issues/new) — we would greatly appreciate your feedback!
215
+
216
+ ## Contributing
217
+
218
+ We welcome contributions to OpenModels! Whether you want to add support for new models, implement new serialization formats, or improve the existing codebase, your help is appreciated.
219
+
220
+ Please refer to our [Contributing Guidelines](https://github.com/Gnpd/openmodels/blob/main/CONTRIBUTING.md) for more information on how to get started.
221
+
222
+ ## Running Tests
223
+
224
+ The package utilizes [Taskfile](https://taskfile.dev/) as a task runner to automate and standardize development flows.
225
+
226
+ To run the tests:
227
+
228
+ 1. Clone the repository:
229
+
230
+ ```bash
231
+ git clone https://github.com/Gnpd/openmodels.git
232
+ cd openmodels
233
+ ```
234
+
235
+ 2. Install the package and its development dependencies:
236
+
237
+ ```bash
238
+ task install:dev
239
+ ```
240
+
241
+ 3. Run the tests:
242
+
243
+ ```bash
244
+ task test
245
+ ```
246
+
247
+ ## Security
248
+
249
+ OpenModels's JSON format is plain data and safe to load from untrusted sources. The
250
+ optional Pickle format is not: like any pickle-based tool, deserializing it can execute
251
+ arbitrary code, so only load pickle files from sources you trust. See
252
+ [SECURITY.md](https://github.com/Gnpd/openmodels/blob/main/SECURITY.md) for details and
253
+ how to report a vulnerability.
254
+
255
+ ## License
256
+
257
+ This project is licensed under the MIT License. See the [LICENSE](https://github.com/Gnpd/openmodels/blob/main/LICENSE) file for details.
258
+
259
+ ## Changelog
260
+
261
+ For a detailed changelog, please see the [CHANGELOG.md](https://github.com/Gnpd/openmodels/blob/main/CHANGELOG.md) file.
262
+
263
+ ## Support
264
+
265
+ If you encounter any issues or have questions, please [file an issue](https://github.com/Gnpd/openmodels/issues/new) on our GitHub repository.
266
+
267
+ We're always looking to improve OpenModels. If you have any suggestions or feature requests, please let us know!
268
+
269
+ ## Acknowledgements
270
+
271
+ During the revision and design of OpenModels, we came across the discontinued project [**sklearn-json**](https://github.com/mlrequest/sklearn-json).
272
+ Although no longer maintained, it provided valuable ideas — particularly around testing approaches — that inspired parts of our implementation.
273
+ We would like to acknowledge and thank its authors for their earlier contributions to open model serialization efforts in the scikit-learn ecosystem.
274
+
@@ -0,0 +1,244 @@
1
+ # OpenModels
2
+
3
+ [![PyPI version](https://badge.fury.io/py/openmodels.svg?cacheBust=1)](https://badge.fury.io/py/openmodels)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+ [![Python Versions](https://img.shields.io/pypi/pyversions/openmodels.svg?cacheBust=1)](https://pypi.org/project/openmodels/)
6
+
7
+ OpenModels is a flexible and extensible library for serializing and deserializing machine learning models. It's designed to support any serialization format through a plugin-based architecture, providing a safe and transparent solution for exporting and sharing predictive models.
8
+
9
+ ## Key Features
10
+
11
+ - **Format Agnostic**: Supports any serialization format through a plugin-based system.
12
+ - **Extensible**: Easily add support for new model types and serialization formats.
13
+ - **Safe**: Provides alternatives to potentially unsafe serialization methods like Pickle (see [Security](#security)).
14
+ - **Transparent**: Supports human-readable formats for easy inspection of serialized models.
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ pip install openmodels
20
+ ```
21
+
22
+ ## Quick Start
23
+
24
+ ```python
25
+ from openmodels import SerializationManager, SklearnSerializer
26
+ from sklearn.decomposition import PCA
27
+ from sklearn.datasets import make_classification
28
+
29
+ # Create and train a scikit-learn model
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
+
34
+ # Create a SerializationManager
35
+ manager = SerializationManager(SklearnSerializer())
36
+
37
+ # Serialize the model (default format is JSON)
38
+ serialized_model = manager.serialize(model)
39
+
40
+ # Deserialize the model
41
+ deserialized_model = manager.deserialize(serialized_model)
42
+
43
+ # Use the deserialized model
44
+ transformed_data = deserialized_model.transform(X[:5])
45
+ print(transformed_data)
46
+ ```
47
+
48
+ ## Saving and Loading Models
49
+ OpenModels provides high-level `save` and `load` methods for convenient file I/O:
50
+
51
+ ```python
52
+ # Serialize and save a model to a file in JSON format
53
+ manager.save(model, "model.json", format_name="json")
54
+
55
+ # Load and deserialize a model from a file
56
+ loaded_model = manager.load("model.json", format_name="json")
57
+ ```
58
+
59
+ ## Extensibility
60
+
61
+ OpenModels is designed to be easily extended with new serialization formats and model types.
62
+
63
+ ### Adding a New Format
64
+
65
+ To add a new serialization format, create a class that implements the `FormatConverter` protocol and register it with the `FormatRegistry`:
66
+
67
+ ```python
68
+ from openmodels.protocols import FormatConverter
69
+ from openmodels.format_registry import FormatRegistry
70
+ from typing import Dict, Any
71
+
72
+ class YAMLConverter(FormatConverter):
73
+ @staticmethod
74
+ def serialize_to_format(data: Dict[str, Any]) -> str:
75
+ import yaml
76
+ return yaml.dump(data)
77
+
78
+ @staticmethod
79
+ def deserialize_from_format(formatted_data: str) -> Dict[str, Any]:
80
+ import yaml
81
+ return yaml.safe_load(formatted_data)
82
+
83
+ FormatRegistry.register("yaml", YAMLConverter)
84
+ ```
85
+
86
+ ### Adding a New Model Serializer
87
+
88
+ To add support for a new type of model, create a class that implements the `ModelSerializer` protocol:
89
+
90
+ ```python
91
+ from openmodels.protocols import ModelSerializer
92
+ from typing import Any, Dict
93
+
94
+ class TensorFlowSerializer(ModelSerializer):
95
+ def serialize(self, model: Any) -> Dict[str, Any]:
96
+ # Implementation for serializing TensorFlow models
97
+ ...
98
+
99
+ def deserialize(self, data: Dict[str, Any]) -> Any:
100
+ # Implementation for deserializing TensorFlow models
101
+ ...
102
+ ```
103
+
104
+ ## Supported Models (scikit-learn)
105
+
106
+ OpenModels supports every scikit-learn estimator, including:
107
+
108
+ - Classification: LogisticRegression, SVC, etc.
109
+ - Regression: LinearRegression, SVR, etc.
110
+ - Clustering: KMeans
111
+ - Dimensionality Reduction: PCA
112
+
113
+ See the [Supported Models](https://gnpd.github.io/openmodels/supported_models.html) docs page
114
+ for the full breakdown by category, and the
115
+ [serialized format reference](https://gnpd.github.io/openmodels/format.html) for what actually
116
+ gets written to disk.
117
+
118
+ You can also retrieve the list programmatically using the `SklearnSerializer.all_estimators()` method:
119
+
120
+ ```python
121
+ from openmodels.serializers import SklearnSerializer
122
+
123
+ # Get all supported estimators (classifiers, regressors, etc.)
124
+ all_supported = SklearnSerializer.all_estimators()
125
+ print([name for name, cls in all_supported])
126
+
127
+ # To get only classifiers:
128
+ classifiers = SklearnSerializer.all_estimators(type_filter="classifier")
129
+ print([name for name, cls in classifiers])
130
+
131
+ # To get only regressors:
132
+ regressors = SklearnSerializer.all_estimators(type_filter="regressor")
133
+ print([name for name, cls in regressors])
134
+ ```
135
+
136
+ ## Using Custom Estimators and Pipelines (Third-Party Support)
137
+
138
+ OpenModels can serialize and deserialize models and pipelines that include third-party estimators, such as those from [chemotools](https://github.com/paucablop/chemotools).
139
+
140
+ ```python
141
+ from openmodels import SerializationManager, SklearnSerializer
142
+ from chemotools.utils.discovery import all_estimators # chemotools >=0.2.2
143
+ from chemotools.derivative import SavitzkyGolay
144
+ from sklearn.cross_decomposition import PLSRegression
145
+ from sklearn.pipeline import make_pipeline
146
+
147
+ # Example data
148
+ from chemotools.datasets import load_fermentation_train
149
+ X_train, y_train = load_fermentation_train()
150
+
151
+ # Define a pipeline with chemotools preprocessing and sklearn estimator
152
+ pipeline = make_pipeline(
153
+ SavitzkyGolay(window_size=3, polynomial_order=1, derivate_order=1),
154
+ PLSRegression(n_components=2)
155
+ )
156
+
157
+ # Fit the pipeline
158
+ pipeline.fit(X_train, y_train)
159
+
160
+ # Serialize and deserialize the pipeline using OpenModels
161
+ serializer = SklearnSerializer(custom_estimators=all_estimators)
162
+ manager = SerializationManager(serializer)
163
+
164
+ serialized = manager.serialize(pipeline)
165
+ restored = manager.deserialize(serialized)
166
+
167
+ # Use the restored pipeline
168
+ y_train_pred = restored.predict(X_train)
169
+ print(y_train_pred)
170
+ ```
171
+
172
+ You can pass any compatible `all_estimators` function, list, or dictionary to `SklearnSerializer(custom_estimators=...)` to extend support for custom or third-party estimators.
173
+
174
+ ## scikit-learn Version Compatibility
175
+
176
+ OpenModels is tested against the following scikit-learn versions via the on-demand [`scikit-learn compatibility`](https://github.com/Gnpd/openmodels/actions/workflows/sklearn-compat.yml) CI workflow:
177
+
178
+ | scikit-learn | Status |
179
+ |---|---|
180
+ | 1.6.1 | ✅ Tested |
181
+ | 1.7.2 | ✅ Tested |
182
+ | 1.8.0 | ✅ Tested |
183
+ | 1.9.0 | ✅ Tested |
184
+
185
+ If you encounter any incompatibility or a use case where the library does not work correctly with your version of scikit-learn, please [open an issue](https://github.com/Gnpd/openmodels/issues/new) — we would greatly appreciate your feedback!
186
+
187
+ ## Contributing
188
+
189
+ We welcome contributions to OpenModels! Whether you want to add support for new models, implement new serialization formats, or improve the existing codebase, your help is appreciated.
190
+
191
+ Please refer to our [Contributing Guidelines](https://github.com/Gnpd/openmodels/blob/main/CONTRIBUTING.md) for more information on how to get started.
192
+
193
+ ## Running Tests
194
+
195
+ The package utilizes [Taskfile](https://taskfile.dev/) as a task runner to automate and standardize development flows.
196
+
197
+ To run the tests:
198
+
199
+ 1. Clone the repository:
200
+
201
+ ```bash
202
+ git clone https://github.com/Gnpd/openmodels.git
203
+ cd openmodels
204
+ ```
205
+
206
+ 2. Install the package and its development dependencies:
207
+
208
+ ```bash
209
+ task install:dev
210
+ ```
211
+
212
+ 3. Run the tests:
213
+
214
+ ```bash
215
+ task test
216
+ ```
217
+
218
+ ## Security
219
+
220
+ OpenModels's JSON format is plain data and safe to load from untrusted sources. The
221
+ optional Pickle format is not: like any pickle-based tool, deserializing it can execute
222
+ arbitrary code, so only load pickle files from sources you trust. See
223
+ [SECURITY.md](https://github.com/Gnpd/openmodels/blob/main/SECURITY.md) for details and
224
+ how to report a vulnerability.
225
+
226
+ ## License
227
+
228
+ This project is licensed under the MIT License. See the [LICENSE](https://github.com/Gnpd/openmodels/blob/main/LICENSE) file for details.
229
+
230
+ ## Changelog
231
+
232
+ For a detailed changelog, please see the [CHANGELOG.md](https://github.com/Gnpd/openmodels/blob/main/CHANGELOG.md) file.
233
+
234
+ ## Support
235
+
236
+ If you encounter any issues or have questions, please [file an issue](https://github.com/Gnpd/openmodels/issues/new) on our GitHub repository.
237
+
238
+ We're always looking to improve OpenModels. If you have any suggestions or feature requests, please let us know!
239
+
240
+ ## Acknowledgements
241
+
242
+ During the revision and design of OpenModels, we came across the discontinued project [**sklearn-json**](https://github.com/mlrequest/sklearn-json).
243
+ Although no longer maintained, it provided valuable ideas — particularly around testing approaches — that inspired parts of our implementation.
244
+ We would like to acknowledge and thank its authors for their earlier contributions to open model serialization efforts in the scikit-learn ecosystem.
@@ -0,0 +1,50 @@
1
+ """
2
+ OpenModels: A flexible library for serializing and deserializing machine learning models.
3
+
4
+ This package provides tools for converting machine learning models to various
5
+ formats and back. It supports different model types and serialization formats
6
+ through a plugin-based system.
7
+
8
+ Main components:
9
+ - SerializationManager: Coordinates the serialization and deserialization process.
10
+ - SklearnSerializer: Handles serialization for scikit-learn models.
11
+ - JSONConverter, PickleConverter: Convert between dict and specific formats.
12
+ - FormatRegistry: Manages available format converters.
13
+
14
+ Example usage:
15
+ from openmodels import SerializationManager, SklearnSerializer
16
+ from sklearn.linear_model import LogisticRegression
17
+
18
+ # Create and train a scikit-learn model
19
+ model = LogisticRegression()
20
+ model.fit(X_train, y_train)
21
+
22
+ # Create a SerializationManager
23
+ manager = SerializationManager(SklearnSerializer())
24
+
25
+ # Serialize the model to JSON
26
+ serialized_model = manager.serialize(model, format="json")
27
+
28
+ # Deserialize the model from JSON
29
+ deserialized_model = manager.deserialize(serialized_model, format="json")
30
+
31
+ # Use the deserialized model
32
+ predictions = deserialized_model.predict(X_test)
33
+
34
+ For more advanced usage and custom serializers or converters, refer to the documentation.
35
+ """
36
+
37
+ from .core import SerializationManager
38
+ from .serializers import SklearnSerializer
39
+ from .converters import JSONConverter, PickleConverter
40
+ from .format_registry import FormatRegistry
41
+
42
+ # Register the JSONConverter
43
+ FormatRegistry.register("json", JSONConverter)
44
+ FormatRegistry.register("pickle", PickleConverter)
45
+
46
+ __all__ = [
47
+ "FormatRegistry",
48
+ "SerializationManager",
49
+ "SklearnSerializer",
50
+ ]
@@ -0,0 +1,11 @@
1
+ """
2
+ Converters module for the OpenModels library.
3
+
4
+ This module provides converters for different serialization formats.
5
+ Currently, it includes converters for JSON and pickle formats.
6
+ """
7
+
8
+ from .json_converter import JSONConverter
9
+ from .pickle_converter import PickleConverter
10
+
11
+ __all__ = ["JSONConverter", "PickleConverter"]
@@ -0,0 +1,61 @@
1
+ """
2
+ JSON converter for the OpenModels library.
3
+
4
+ This module provides a converter for serializing to and from JSON format.
5
+ """
6
+
7
+ import json
8
+ from typing import Any, Dict
9
+
10
+ from openmodels.protocols import FormatConverter
11
+
12
+
13
+ class JSONConverter(FormatConverter):
14
+ """
15
+ Converter for JSON format.
16
+
17
+ This class provides static methods to convert between dictionary
18
+ representations and JSON strings.
19
+ """
20
+
21
+ @staticmethod
22
+ def serialize_to_format(data: Dict[str, Any]) -> str:
23
+ """
24
+ Convert a dictionary to a JSON string.
25
+
26
+ Parameters
27
+ ----------
28
+ data : Dict[str, Any]
29
+ The dictionary to convert.
30
+
31
+ Returns
32
+ -------
33
+ str
34
+ The JSON string representation of the data.
35
+ """
36
+
37
+ if not isinstance(data, dict):
38
+ raise TypeError("Data must be a dictionary.")
39
+ return json.dumps(data)
40
+
41
+ @staticmethod
42
+ def deserialize_from_format(formatted_data: str) -> Dict[str, Any]:
43
+ """
44
+ Convert a JSON string to a dictionary.
45
+
46
+ Parameters
47
+ ----------
48
+ formatted_data : str
49
+ The JSON string to convert.
50
+
51
+ Returns
52
+ -------
53
+ Dict[str, Any]
54
+ The dictionary representation of the JSON data.
55
+
56
+ Raises
57
+ ------
58
+ json.JSONDecodeError
59
+ If the input string is not valid JSON.
60
+ """
61
+ return json.loads(formatted_data)