openmodels 0.1.0a1__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.
- openmodels-0.1.0a1/LICENSE +19 -0
- openmodels-0.1.0a1/PKG-INFO +162 -0
- openmodels-0.1.0a1/README.md +144 -0
- openmodels-0.1.0a1/openmodels/__init__.py +50 -0
- openmodels-0.1.0a1/openmodels/converters/__init__.py +11 -0
- openmodels-0.1.0a1/openmodels/converters/json_converter.py +58 -0
- openmodels-0.1.0a1/openmodels/converters/pickle_converter.py +58 -0
- openmodels-0.1.0a1/openmodels/core.py +112 -0
- openmodels-0.1.0a1/openmodels/exceptions.py +26 -0
- openmodels-0.1.0a1/openmodels/format_registry.py +73 -0
- openmodels-0.1.0a1/openmodels/protocols.py +83 -0
- openmodels-0.1.0a1/openmodels/serializers/__init__.py +10 -0
- openmodels-0.1.0a1/openmodels/serializers/sklearn_serializer.py +269 -0
- openmodels-0.1.0a1/openmodels/test_helpers.py +230 -0
- openmodels-0.1.0a1/pyproject.toml +29 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Copyright (c) 2024 SFTec
|
|
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,162 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: openmodels
|
|
3
|
+
Version: 0.1.0a1
|
|
4
|
+
Summary: Export scikit-learn model files to JSON for sharing or deploying predictive models with peace of mind.
|
|
5
|
+
License: MIT
|
|
6
|
+
Author: Alejandro Gutierrez
|
|
7
|
+
Author-email: agutierrez@sftec.es>, Pau Cabaneros <pau.cabaneros@gmail.com>, Raúl Marín <hi@raulmarin.dev>, Ruben Parrilla <rparrilla@sftec.es
|
|
8
|
+
Requires-Python: >=3.9,<4.0
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Requires-Dist: scikit-learn (>=1.5.0,<2.0.0)
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# OpenModels
|
|
19
|
+
|
|
20
|
+
[](https://badge.fury.io/py/openmodels)
|
|
21
|
+
[](https://opensource.org/licenses/MIT)
|
|
22
|
+
[](https://pypi.org/project/openmodels/)
|
|
23
|
+
|
|
24
|
+
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.
|
|
25
|
+
|
|
26
|
+
## Key Features
|
|
27
|
+
|
|
28
|
+
- **Format Agnostic**: Supports any serialization format through a plugin-based system.
|
|
29
|
+
- **Extensible**: Easily add support for new model types and serialization formats.
|
|
30
|
+
- **Safe**: Provides alternatives to potentially unsafe serialization methods like Pickle.
|
|
31
|
+
- **Transparent**: Supports human-readable formats for easy inspection of serialized models.
|
|
32
|
+
|
|
33
|
+
## Installation
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install openmodels
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Quick Start
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from openmodels import SerializationManager, SklearnSerializer
|
|
43
|
+
from sklearn.ensemble import RandomForestClassifier
|
|
44
|
+
from sklearn.datasets import make_classification
|
|
45
|
+
|
|
46
|
+
# Create and train a scikit-learn model
|
|
47
|
+
X, y = make_classification(n_samples=1000, n_features=4, n_informative=2, n_redundant=0, random_state=0, shuffle=False)
|
|
48
|
+
model = RandomForestClassifier(n_estimators=10, max_depth=5, random_state=0)
|
|
49
|
+
model.fit(X, y)
|
|
50
|
+
|
|
51
|
+
# Create a SerializationManager
|
|
52
|
+
manager = SerializationManager(SklearnSerializer())
|
|
53
|
+
|
|
54
|
+
# Serialize the model (default format is JSON)
|
|
55
|
+
serialized_model = manager.serialize(model)
|
|
56
|
+
|
|
57
|
+
# Deserialize the model
|
|
58
|
+
deserialized_model = manager.deserialize(serialized_model)
|
|
59
|
+
|
|
60
|
+
# Use the deserialized model
|
|
61
|
+
predictions = deserialized_model.predict(X[:5])
|
|
62
|
+
print(predictions)
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Extensibility
|
|
66
|
+
|
|
67
|
+
OpenModels is designed to be easily extended with new serialization formats and model types.
|
|
68
|
+
|
|
69
|
+
### Adding a New Format
|
|
70
|
+
|
|
71
|
+
To add a new serialization format, create a class that implements the `FormatConverter` protocol and register it with the `FormatRegistry`:
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
from openmodels.protocols import FormatConverter
|
|
75
|
+
from openmodels.format_registry import FormatRegistry
|
|
76
|
+
from typing import Dict, Any
|
|
77
|
+
|
|
78
|
+
class YAMLConverter(FormatConverter):
|
|
79
|
+
@staticmethod
|
|
80
|
+
def serialize_to_format(data: Dict[str, Any]) -> str:
|
|
81
|
+
import yaml
|
|
82
|
+
return yaml.dump(data)
|
|
83
|
+
|
|
84
|
+
@staticmethod
|
|
85
|
+
def deserialize_from_format(formatted_data: str) -> Dict[str, Any]:
|
|
86
|
+
import yaml
|
|
87
|
+
return yaml.safe_load(formatted_data)
|
|
88
|
+
|
|
89
|
+
FormatRegistry.register("yaml", YAMLConverter)
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
### Adding a New Model Serializer
|
|
93
|
+
|
|
94
|
+
To add support for a new type of model, create a class that implements the `ModelSerializer` protocol:
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
from openmodels.protocols import ModelSerializer
|
|
98
|
+
from typing import Any, Dict
|
|
99
|
+
|
|
100
|
+
class TensorFlowSerializer(ModelSerializer):
|
|
101
|
+
def serialize(self, model: Any) -> Dict[str, Any]:
|
|
102
|
+
# Implementation for serializing TensorFlow models
|
|
103
|
+
...
|
|
104
|
+
|
|
105
|
+
def deserialize(self, data: Dict[str, Any]) -> Any:
|
|
106
|
+
# Implementation for deserializing TensorFlow models
|
|
107
|
+
...
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## Supported Models
|
|
111
|
+
|
|
112
|
+
OpenModels currently supports a wide range of scikit-learn models, including:
|
|
113
|
+
|
|
114
|
+
- Classification: LogisticRegression, RandomForestClassifier, SVC, etc.
|
|
115
|
+
- Regression: LinearRegression, RandomForestRegressor, SVR, etc.
|
|
116
|
+
- Clustering: KMeans
|
|
117
|
+
- Dimensionality Reduction: PCA
|
|
118
|
+
|
|
119
|
+
For a full list of supported models, please refer to the `SUPPORTED_ESTIMATORS` dictionary in `serializers/sklearn_serializer.py`.
|
|
120
|
+
|
|
121
|
+
## Contributing
|
|
122
|
+
|
|
123
|
+
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.
|
|
124
|
+
|
|
125
|
+
Please refer to our [Contributing Guidelines](CONTRIBUTING.md) for more information on how to get started.
|
|
126
|
+
|
|
127
|
+
## Running Tests
|
|
128
|
+
|
|
129
|
+
To run the tests:
|
|
130
|
+
|
|
131
|
+
1. Clone the repository:
|
|
132
|
+
|
|
133
|
+
```bash
|
|
134
|
+
git clone https://github.com/your-repo/openmodels.git
|
|
135
|
+
cd openmodels
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
2. Install the package and its dependencies:
|
|
139
|
+
|
|
140
|
+
```bash
|
|
141
|
+
pip install -e .
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
3. Run the tests:
|
|
145
|
+
```bash
|
|
146
|
+
pytest
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
## License
|
|
150
|
+
|
|
151
|
+
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
|
|
152
|
+
|
|
153
|
+
## Changelog
|
|
154
|
+
|
|
155
|
+
For a detailed changelog, please see the [CHANGELOG.md](CHANGELOG.md) file.
|
|
156
|
+
|
|
157
|
+
## Support
|
|
158
|
+
|
|
159
|
+
If you encounter any issues or have questions, please [file an issue](https://github.com/SF-Tec/openmodels) on our GitHub repository.
|
|
160
|
+
|
|
161
|
+
We're always looking to improve OpenModels. If you have any suggestions or feature requests, please let us know!
|
|
162
|
+
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
# OpenModels
|
|
2
|
+
|
|
3
|
+
[](https://badge.fury.io/py/openmodels)
|
|
4
|
+
[](https://opensource.org/licenses/MIT)
|
|
5
|
+
[](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.
|
|
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.ensemble import RandomForestClassifier
|
|
27
|
+
from sklearn.datasets import make_classification
|
|
28
|
+
|
|
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)
|
|
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
|
+
predictions = deserialized_model.predict(X[:5])
|
|
45
|
+
print(predictions)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Extensibility
|
|
49
|
+
|
|
50
|
+
OpenModels is designed to be easily extended with new serialization formats and model types.
|
|
51
|
+
|
|
52
|
+
### Adding a New Format
|
|
53
|
+
|
|
54
|
+
To add a new serialization format, create a class that implements the `FormatConverter` protocol and register it with the `FormatRegistry`:
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
from openmodels.protocols import FormatConverter
|
|
58
|
+
from openmodels.format_registry import FormatRegistry
|
|
59
|
+
from typing import Dict, Any
|
|
60
|
+
|
|
61
|
+
class YAMLConverter(FormatConverter):
|
|
62
|
+
@staticmethod
|
|
63
|
+
def serialize_to_format(data: Dict[str, Any]) -> str:
|
|
64
|
+
import yaml
|
|
65
|
+
return yaml.dump(data)
|
|
66
|
+
|
|
67
|
+
@staticmethod
|
|
68
|
+
def deserialize_from_format(formatted_data: str) -> Dict[str, Any]:
|
|
69
|
+
import yaml
|
|
70
|
+
return yaml.safe_load(formatted_data)
|
|
71
|
+
|
|
72
|
+
FormatRegistry.register("yaml", YAMLConverter)
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### Adding a New Model Serializer
|
|
76
|
+
|
|
77
|
+
To add support for a new type of model, create a class that implements the `ModelSerializer` protocol:
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
from openmodels.protocols import ModelSerializer
|
|
81
|
+
from typing import Any, Dict
|
|
82
|
+
|
|
83
|
+
class TensorFlowSerializer(ModelSerializer):
|
|
84
|
+
def serialize(self, model: Any) -> Dict[str, Any]:
|
|
85
|
+
# Implementation for serializing TensorFlow models
|
|
86
|
+
...
|
|
87
|
+
|
|
88
|
+
def deserialize(self, data: Dict[str, Any]) -> Any:
|
|
89
|
+
# Implementation for deserializing TensorFlow models
|
|
90
|
+
...
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## Supported Models
|
|
94
|
+
|
|
95
|
+
OpenModels currently supports a wide range of scikit-learn models, including:
|
|
96
|
+
|
|
97
|
+
- Classification: LogisticRegression, RandomForestClassifier, SVC, etc.
|
|
98
|
+
- Regression: LinearRegression, RandomForestRegressor, SVR, etc.
|
|
99
|
+
- Clustering: KMeans
|
|
100
|
+
- Dimensionality Reduction: PCA
|
|
101
|
+
|
|
102
|
+
For a full list of supported models, please refer to the `SUPPORTED_ESTIMATORS` dictionary in `serializers/sklearn_serializer.py`.
|
|
103
|
+
|
|
104
|
+
## Contributing
|
|
105
|
+
|
|
106
|
+
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.
|
|
107
|
+
|
|
108
|
+
Please refer to our [Contributing Guidelines](CONTRIBUTING.md) for more information on how to get started.
|
|
109
|
+
|
|
110
|
+
## Running Tests
|
|
111
|
+
|
|
112
|
+
To run the tests:
|
|
113
|
+
|
|
114
|
+
1. Clone the repository:
|
|
115
|
+
|
|
116
|
+
```bash
|
|
117
|
+
git clone https://github.com/your-repo/openmodels.git
|
|
118
|
+
cd openmodels
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
2. Install the package and its dependencies:
|
|
122
|
+
|
|
123
|
+
```bash
|
|
124
|
+
pip install -e .
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
3. Run the tests:
|
|
128
|
+
```bash
|
|
129
|
+
pytest
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
## License
|
|
133
|
+
|
|
134
|
+
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
|
|
135
|
+
|
|
136
|
+
## Changelog
|
|
137
|
+
|
|
138
|
+
For a detailed changelog, please see the [CHANGELOG.md](CHANGELOG.md) file.
|
|
139
|
+
|
|
140
|
+
## Support
|
|
141
|
+
|
|
142
|
+
If you encounter any issues or have questions, please [file an issue](https://github.com/SF-Tec/openmodels) on our GitHub repository.
|
|
143
|
+
|
|
144
|
+
We're always looking to improve OpenModels. If you have any suggestions or feature requests, please let us know!
|
|
@@ -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,58 @@
|
|
|
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
|
+
return json.dumps(data)
|
|
37
|
+
|
|
38
|
+
@staticmethod
|
|
39
|
+
def deserialize_from_format(formatted_data: str) -> Dict[str, Any]:
|
|
40
|
+
"""
|
|
41
|
+
Convert a JSON string to a dictionary.
|
|
42
|
+
|
|
43
|
+
Parameters
|
|
44
|
+
----------
|
|
45
|
+
formatted_data : str
|
|
46
|
+
The JSON string to convert.
|
|
47
|
+
|
|
48
|
+
Returns
|
|
49
|
+
-------
|
|
50
|
+
Dict[str, Any]
|
|
51
|
+
The dictionary representation of the JSON data.
|
|
52
|
+
|
|
53
|
+
Raises
|
|
54
|
+
------
|
|
55
|
+
json.JSONDecodeError
|
|
56
|
+
If the input string is not valid JSON.
|
|
57
|
+
"""
|
|
58
|
+
return json.loads(formatted_data)
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Pickle converter for the OpenModels library.
|
|
3
|
+
|
|
4
|
+
This module provides a converter for serializing to and from pickle format.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import pickle
|
|
8
|
+
from typing import Any, Dict
|
|
9
|
+
|
|
10
|
+
from openmodels.protocols import FormatConverter
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class PickleConverter(FormatConverter):
|
|
14
|
+
"""
|
|
15
|
+
Converter for pickle format.
|
|
16
|
+
|
|
17
|
+
This class provides static methods to convert between dictionary
|
|
18
|
+
representations and pickle byte strings.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
@staticmethod
|
|
22
|
+
def serialize_to_format(data: Dict[str, Any]) -> bytes:
|
|
23
|
+
"""
|
|
24
|
+
Convert a dictionary to a pickle byte string.
|
|
25
|
+
|
|
26
|
+
Parameters
|
|
27
|
+
----------
|
|
28
|
+
data : Dict[str, Any]
|
|
29
|
+
The dictionary to convert.
|
|
30
|
+
|
|
31
|
+
Returns
|
|
32
|
+
-------
|
|
33
|
+
bytes
|
|
34
|
+
The pickle byte string representation of the data.
|
|
35
|
+
"""
|
|
36
|
+
return pickle.dumps(data)
|
|
37
|
+
|
|
38
|
+
@staticmethod
|
|
39
|
+
def deserialize_from_format(formatted_data: bytes) -> Dict[str, Any]:
|
|
40
|
+
"""
|
|
41
|
+
Convert a pickle byte string to a dictionary.
|
|
42
|
+
|
|
43
|
+
Parameters
|
|
44
|
+
----------
|
|
45
|
+
formatted_data : bytes
|
|
46
|
+
The pickle byte string to convert.
|
|
47
|
+
|
|
48
|
+
Returns
|
|
49
|
+
-------
|
|
50
|
+
Dict[str, Any]
|
|
51
|
+
The dictionary representation of the pickle data.
|
|
52
|
+
|
|
53
|
+
Raises
|
|
54
|
+
------
|
|
55
|
+
pickle.UnpicklingError
|
|
56
|
+
If the input bytes cannot be unpickled.
|
|
57
|
+
"""
|
|
58
|
+
return pickle.loads(formatted_data)
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Core API module for the OpenModels library.
|
|
3
|
+
|
|
4
|
+
This module contains the SerializationManager class, which is the main interface
|
|
5
|
+
for serializing and deserializing machine learning models using various formats.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from typing import Any
|
|
9
|
+
from .protocols import ModelSerializer
|
|
10
|
+
from .format_registry import FormatRegistry
|
|
11
|
+
from .exceptions import SerializationError, DeserializationError
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class SerializationManager:
|
|
15
|
+
"""
|
|
16
|
+
Manage the serialization and deserialization of machine learning models.
|
|
17
|
+
|
|
18
|
+
This class coordinates the process of converting models to various formats
|
|
19
|
+
and back, using specified model serializers and format converters.
|
|
20
|
+
|
|
21
|
+
Attributes
|
|
22
|
+
----------
|
|
23
|
+
model_serializer : ModelSerializer
|
|
24
|
+
The serializer used to convert models to and from dictionary representations.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(self, model_serializer: ModelSerializer):
|
|
28
|
+
"""
|
|
29
|
+
Initialize the SerializationManager with a model serializer.
|
|
30
|
+
|
|
31
|
+
Parameters
|
|
32
|
+
----------
|
|
33
|
+
model_serializer : ModelSerializer
|
|
34
|
+
The serializer to use for converting models to and from dictionary representations.
|
|
35
|
+
"""
|
|
36
|
+
self.model_serializer = model_serializer
|
|
37
|
+
|
|
38
|
+
def serialize(self, model: Any, format_name: str = "json") -> Any:
|
|
39
|
+
"""
|
|
40
|
+
Serialize a model to the specified format.
|
|
41
|
+
|
|
42
|
+
Parameters
|
|
43
|
+
----------
|
|
44
|
+
model : Any
|
|
45
|
+
The machine learning model to serialize.
|
|
46
|
+
format_name : str, optional
|
|
47
|
+
The target format (default is "json").
|
|
48
|
+
|
|
49
|
+
Returns
|
|
50
|
+
-------
|
|
51
|
+
Any
|
|
52
|
+
The serialized model in the specified format.
|
|
53
|
+
|
|
54
|
+
Raises
|
|
55
|
+
------
|
|
56
|
+
SerializationError
|
|
57
|
+
If the model serializer doesn't return a dictionary or if there's an error during
|
|
58
|
+
serialization.
|
|
59
|
+
UnsupportedFormatError
|
|
60
|
+
If the specified format is not supported.
|
|
61
|
+
|
|
62
|
+
Examples
|
|
63
|
+
--------
|
|
64
|
+
>>> manager = SerializationManager(SklearnSerializer())
|
|
65
|
+
>>> model = LogisticRegression()
|
|
66
|
+
>>> serialized_model = manager.serialize(model, format_name="json")
|
|
67
|
+
"""
|
|
68
|
+
converter = FormatRegistry.get_converter(format_name)
|
|
69
|
+
serialized_dict = self.model_serializer.serialize(model)
|
|
70
|
+
if not isinstance(serialized_dict, dict):
|
|
71
|
+
raise SerializationError(
|
|
72
|
+
f"Model serializer must return a dict, got {type(serialized_dict)}"
|
|
73
|
+
)
|
|
74
|
+
return converter.serialize_to_format(serialized_dict)
|
|
75
|
+
|
|
76
|
+
def deserialize(self, serialized_model: Any, format_name: str = "json") -> Any:
|
|
77
|
+
"""
|
|
78
|
+
Deserialize a model from the specified format.
|
|
79
|
+
|
|
80
|
+
Parameters
|
|
81
|
+
----------
|
|
82
|
+
serialized_model : Any
|
|
83
|
+
The serialized model data.
|
|
84
|
+
format_name : str, optional
|
|
85
|
+
The format of the serialized data (default is "json").
|
|
86
|
+
|
|
87
|
+
Returns
|
|
88
|
+
-------
|
|
89
|
+
Any
|
|
90
|
+
The deserialized machine learning model.
|
|
91
|
+
|
|
92
|
+
Raises
|
|
93
|
+
------
|
|
94
|
+
DeserializationError
|
|
95
|
+
If the format converter doesn't return a dictionary or if there's an error during
|
|
96
|
+
deserialization.
|
|
97
|
+
UnsupportedFormatError
|
|
98
|
+
If the specified format_name is not supported.
|
|
99
|
+
|
|
100
|
+
Examples
|
|
101
|
+
--------
|
|
102
|
+
>>> manager = SerializationManager(SklearnSerializer())
|
|
103
|
+
>>> deserialized_model = manager.deserialize(serialized_model, format_name="json")
|
|
104
|
+
>>> predictions = deserialized_model.predict(X_test)
|
|
105
|
+
"""
|
|
106
|
+
converter = FormatRegistry.get_converter(format_name)
|
|
107
|
+
deserialized_dict = converter.deserialize_from_format(serialized_model)
|
|
108
|
+
if not isinstance(deserialized_dict, dict):
|
|
109
|
+
raise DeserializationError(
|
|
110
|
+
f"Format converter must return a dict, got {type(deserialized_dict)}"
|
|
111
|
+
)
|
|
112
|
+
return self.model_serializer.deserialize(deserialized_dict)
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Custom exceptions for the OpenModels library.
|
|
3
|
+
|
|
4
|
+
This module defines custom exception classes used throughout the OpenModels
|
|
5
|
+
library to provide more specific error handling and improve debuggability.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class OpenModelsError(Exception):
|
|
10
|
+
"""Base exception class for all OpenModels library errors."""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class SerializationError(OpenModelsError):
|
|
14
|
+
"""Exception raised when there's an error during model serialization."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class DeserializationError(OpenModelsError):
|
|
18
|
+
"""Exception raised when there's an error during model deserialization."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class UnsupportedFormatError(OpenModelsError):
|
|
22
|
+
"""Exception raised when an unsupported serialization format is requested."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class UnsupportedEstimatorError(OpenModelsError):
|
|
26
|
+
"""Exception raised when an unsupported estimator is encountered."""
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Format registry module for the OpenModels library.
|
|
3
|
+
|
|
4
|
+
This module provides a registry for format converters, allowing dynamic
|
|
5
|
+
registration and retrieval of converters for different serialization formats.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from typing import Dict, Type
|
|
9
|
+
from .protocols import FormatConverter
|
|
10
|
+
from .exceptions import UnsupportedFormatError
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class FormatRegistry:
|
|
14
|
+
"""
|
|
15
|
+
A registry for format converters.
|
|
16
|
+
|
|
17
|
+
This class manages the registration and retrieval of format converters,
|
|
18
|
+
allowing the SerializationManager to support multiple serialization formats.
|
|
19
|
+
|
|
20
|
+
Attributes
|
|
21
|
+
----------
|
|
22
|
+
_converters : Dict[str, Type[FormatConverter]]
|
|
23
|
+
A dictionary mapping format names to their respective converter classes.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
_converters: Dict[str, Type[FormatConverter]] = {}
|
|
27
|
+
|
|
28
|
+
@classmethod
|
|
29
|
+
def register(cls, format_name: str, converter: Type[FormatConverter]) -> None:
|
|
30
|
+
"""
|
|
31
|
+
Register a new format converter.
|
|
32
|
+
|
|
33
|
+
Parameters
|
|
34
|
+
----------
|
|
35
|
+
format_name : str
|
|
36
|
+
The name of the format (e.g., "json", "pickle").
|
|
37
|
+
converter : Type[FormatConverter]
|
|
38
|
+
The converter class for the format.
|
|
39
|
+
|
|
40
|
+
Examples
|
|
41
|
+
--------
|
|
42
|
+
>>> FormatRegistry.register("json", JSONConverter)
|
|
43
|
+
"""
|
|
44
|
+
cls._converters[format_name] = converter
|
|
45
|
+
|
|
46
|
+
@classmethod
|
|
47
|
+
def get_converter(cls, format_name: str) -> Type[FormatConverter]:
|
|
48
|
+
"""
|
|
49
|
+
Retrieve a format converter by name.
|
|
50
|
+
|
|
51
|
+
Parameters
|
|
52
|
+
----------
|
|
53
|
+
format_name : str
|
|
54
|
+
The name of the format to retrieve.
|
|
55
|
+
|
|
56
|
+
Returns
|
|
57
|
+
-------
|
|
58
|
+
Type[FormatConverter]
|
|
59
|
+
The converter class for the specified format.
|
|
60
|
+
|
|
61
|
+
Raises
|
|
62
|
+
------
|
|
63
|
+
UnsupportedFormatError
|
|
64
|
+
If the specified format is not supported.
|
|
65
|
+
|
|
66
|
+
Examples
|
|
67
|
+
--------
|
|
68
|
+
>>> json_converter = FormatRegistry.get_converter("json")
|
|
69
|
+
>>> serialized_data = json_converter.serialize_to_format(data_dict)
|
|
70
|
+
"""
|
|
71
|
+
if format_name not in cls._converters:
|
|
72
|
+
raise UnsupportedFormatError(f"Unsupported format: {format_name}")
|
|
73
|
+
return cls._converters[format_name]
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Protocol definitions for the OpenModels library.
|
|
3
|
+
|
|
4
|
+
This module defines the protocols (interfaces) that model serializers and
|
|
5
|
+
format converters must implement to be compatible with the SerializationManager.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from abc import abstractmethod
|
|
9
|
+
from typing import Any, Dict, Protocol
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ModelSerializer(Protocol):
|
|
13
|
+
"""Protocol for model serializers."""
|
|
14
|
+
|
|
15
|
+
@abstractmethod
|
|
16
|
+
def serialize(self, model: Any) -> Dict[str, Any]:
|
|
17
|
+
"""
|
|
18
|
+
Serialize a model to a dictionary representation.
|
|
19
|
+
|
|
20
|
+
Parameters
|
|
21
|
+
----------
|
|
22
|
+
model : Any
|
|
23
|
+
The model to serialize.
|
|
24
|
+
|
|
25
|
+
Returns
|
|
26
|
+
-------
|
|
27
|
+
Dict[str, Any]
|
|
28
|
+
A dictionary representation of the model.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
@abstractmethod
|
|
32
|
+
def deserialize(self, data: Dict[str, Any]) -> Any:
|
|
33
|
+
"""
|
|
34
|
+
Deserialize a model from a dictionary representation.
|
|
35
|
+
|
|
36
|
+
Parameters
|
|
37
|
+
----------
|
|
38
|
+
data : Dict[str, Any]
|
|
39
|
+
The dictionary representation of the model.
|
|
40
|
+
|
|
41
|
+
Returns
|
|
42
|
+
-------
|
|
43
|
+
Any
|
|
44
|
+
The deserialized model.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class FormatConverter(Protocol):
|
|
49
|
+
"""Protocol for format converters."""
|
|
50
|
+
|
|
51
|
+
@staticmethod
|
|
52
|
+
@abstractmethod
|
|
53
|
+
def serialize_to_format(data: Dict[str, Any]) -> Any:
|
|
54
|
+
"""
|
|
55
|
+
Convert a dictionary to a specific format.
|
|
56
|
+
|
|
57
|
+
Parameters
|
|
58
|
+
----------
|
|
59
|
+
data : Dict[str, Any]
|
|
60
|
+
The dictionary to convert.
|
|
61
|
+
|
|
62
|
+
Returns
|
|
63
|
+
-------
|
|
64
|
+
Any
|
|
65
|
+
The data in the specific format.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
@staticmethod
|
|
69
|
+
@abstractmethod
|
|
70
|
+
def deserialize_from_format(formatted_data: Any) -> Dict[str, Any]:
|
|
71
|
+
"""
|
|
72
|
+
Convert data from a specific format to a dictionary.
|
|
73
|
+
|
|
74
|
+
Parameters
|
|
75
|
+
----------
|
|
76
|
+
formatted_data : Any
|
|
77
|
+
The data in the specific format.
|
|
78
|
+
|
|
79
|
+
Returns
|
|
80
|
+
-------
|
|
81
|
+
Dict[str, Any]
|
|
82
|
+
The dictionary representation of the data.
|
|
83
|
+
"""
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Serializers module for the OpenModels library.
|
|
3
|
+
|
|
4
|
+
This module provides serializers for different types of machine learning models.
|
|
5
|
+
Currently, it includes a serializer for scikit-learn models.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from .sklearn_serializer import SklearnSerializer
|
|
9
|
+
|
|
10
|
+
__all__ = ["SklearnSerializer"]
|
|
@@ -0,0 +1,269 @@
|
|
|
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
|
+
|
|
11
|
+
import sklearn
|
|
12
|
+
from sklearn.base import BaseEstimator, check_is_fitted
|
|
13
|
+
from sklearn.cluster import KMeans
|
|
14
|
+
from sklearn.decomposition import PCA
|
|
15
|
+
from sklearn.cross_decomposition import PLSRegression
|
|
16
|
+
from sklearn.ensemble import (
|
|
17
|
+
RandomForestRegressor,
|
|
18
|
+
RandomForestClassifier,
|
|
19
|
+
GradientBoostingClassifier,
|
|
20
|
+
GradientBoostingRegressor,
|
|
21
|
+
)
|
|
22
|
+
from sklearn.svm import SVR, SVC
|
|
23
|
+
from sklearn.linear_model import (
|
|
24
|
+
LogisticRegression,
|
|
25
|
+
Lasso,
|
|
26
|
+
Ridge,
|
|
27
|
+
LinearRegression,
|
|
28
|
+
Perceptron,
|
|
29
|
+
)
|
|
30
|
+
from sklearn.naive_bayes import BernoulliNB, GaussianNB, MultinomialNB, ComplementNB
|
|
31
|
+
from sklearn.discriminant_analysis import (
|
|
32
|
+
LinearDiscriminantAnalysis,
|
|
33
|
+
QuadraticDiscriminantAnalysis,
|
|
34
|
+
)
|
|
35
|
+
from sklearn.dummy import DummyClassifier
|
|
36
|
+
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
|
|
37
|
+
from sklearn.neural_network import MLPClassifier, MLPRegressor
|
|
38
|
+
from sklearn.exceptions import NotFittedError
|
|
39
|
+
|
|
40
|
+
from openmodels.exceptions import UnsupportedEstimatorError, SerializationError
|
|
41
|
+
from openmodels.protocols import ModelSerializer
|
|
42
|
+
|
|
43
|
+
# Dictionary of supported estimators
|
|
44
|
+
SUPPORTED_ESTIMATORS: Dict[str, Type[sklearn.base.BaseEstimator]] = {
|
|
45
|
+
"BernoulliNB": BernoulliNB,
|
|
46
|
+
"ComplementNB": ComplementNB,
|
|
47
|
+
"DecisionTreeClassifier": DecisionTreeClassifier,
|
|
48
|
+
"DecisionTreeRegressor": DecisionTreeRegressor,
|
|
49
|
+
"DummyClassifier": DummyClassifier,
|
|
50
|
+
"GaussianNB": GaussianNB,
|
|
51
|
+
"GradientBoostingClassifier": GradientBoostingClassifier,
|
|
52
|
+
"GradientBoostingRegressor": GradientBoostingRegressor,
|
|
53
|
+
"Lasso": Lasso,
|
|
54
|
+
"LinearDiscriminantAnalysis": LinearDiscriminantAnalysis,
|
|
55
|
+
"LinearRegression": LinearRegression,
|
|
56
|
+
"LogisticRegression": LogisticRegression,
|
|
57
|
+
"KMeans": KMeans,
|
|
58
|
+
"MLPClassifier": MLPClassifier,
|
|
59
|
+
"MLPRegressor": MLPRegressor,
|
|
60
|
+
"MultinomialNB": MultinomialNB,
|
|
61
|
+
"PCA": PCA,
|
|
62
|
+
"Perceptron": Perceptron,
|
|
63
|
+
"PLSRegression": PLSRegression,
|
|
64
|
+
"QuadraticDiscriminantAnalysis": QuadraticDiscriminantAnalysis,
|
|
65
|
+
"RandomForestClassifier": RandomForestClassifier,
|
|
66
|
+
"RandomForestRegressor": RandomForestRegressor,
|
|
67
|
+
"Ridge": Ridge,
|
|
68
|
+
"SVC": SVC,
|
|
69
|
+
"SVR": SVR,
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
# List of supported types for serialization
|
|
73
|
+
SUPPORTED_TYPES: List[Type] = [
|
|
74
|
+
bool,
|
|
75
|
+
str,
|
|
76
|
+
int,
|
|
77
|
+
float,
|
|
78
|
+
list,
|
|
79
|
+
tuple,
|
|
80
|
+
np.float64,
|
|
81
|
+
np.ndarray,
|
|
82
|
+
]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class SklearnSerializer(ModelSerializer):
|
|
86
|
+
"""
|
|
87
|
+
Serializer for scikit-learn estimators.
|
|
88
|
+
|
|
89
|
+
This class provides methods to convert scikit-learn estimators to and from
|
|
90
|
+
dictionary representations, which can then be used with various format converters.
|
|
91
|
+
|
|
92
|
+
The serializer supports a wide range of scikit-learn estimators and handles
|
|
93
|
+
the conversion of numpy arrays and other non-JSON-serializable types.
|
|
94
|
+
|
|
95
|
+
Attributes
|
|
96
|
+
----------
|
|
97
|
+
SUPPORTED_ESTIMATORS : Dict[str, Type[BaseEstimator]]
|
|
98
|
+
A dictionary of supported scikit-learn estimator classes.
|
|
99
|
+
SUPPORTED_TYPES : List[Type]
|
|
100
|
+
A list of supported types for serialization.
|
|
101
|
+
"""
|
|
102
|
+
|
|
103
|
+
@staticmethod
|
|
104
|
+
def _convert_to_serializable_types(value: Any) -> Any:
|
|
105
|
+
"""
|
|
106
|
+
Convert a value to a serializable type.
|
|
107
|
+
|
|
108
|
+
Parameters
|
|
109
|
+
----------
|
|
110
|
+
value : Any
|
|
111
|
+
The value to convert.
|
|
112
|
+
|
|
113
|
+
Returns
|
|
114
|
+
-------
|
|
115
|
+
Any
|
|
116
|
+
The serializable representation of the value.
|
|
117
|
+
"""
|
|
118
|
+
if isinstance(value, (np.ndarray, list)):
|
|
119
|
+
return SklearnSerializer._array_to_list(value)
|
|
120
|
+
return value
|
|
121
|
+
|
|
122
|
+
@staticmethod
|
|
123
|
+
def _convert_to_sklearn_types(value: Any) -> Any:
|
|
124
|
+
"""
|
|
125
|
+
Convert a JSON-deserialized value to its scikit-learn type.
|
|
126
|
+
|
|
127
|
+
Parameters
|
|
128
|
+
----------
|
|
129
|
+
value : Any
|
|
130
|
+
The JSON-deserialized value.
|
|
131
|
+
|
|
132
|
+
Returns
|
|
133
|
+
-------
|
|
134
|
+
Any
|
|
135
|
+
The scikit-learn type of the value.
|
|
136
|
+
"""
|
|
137
|
+
if isinstance(value, list):
|
|
138
|
+
return np.array(value)
|
|
139
|
+
return value
|
|
140
|
+
|
|
141
|
+
@staticmethod
|
|
142
|
+
def _array_to_list(array: Any) -> Any:
|
|
143
|
+
"""
|
|
144
|
+
Recursively convert numpy arrays to nested lists.
|
|
145
|
+
|
|
146
|
+
Parameters
|
|
147
|
+
----------
|
|
148
|
+
array : array-like
|
|
149
|
+
The array or nested structure to convert.
|
|
150
|
+
|
|
151
|
+
Returns
|
|
152
|
+
-------
|
|
153
|
+
list or Any
|
|
154
|
+
The input converted to a nested list structure, or the original value if not an array.
|
|
155
|
+
"""
|
|
156
|
+
if isinstance(array, np.ndarray):
|
|
157
|
+
return SklearnSerializer._array_to_list(array.tolist())
|
|
158
|
+
elif isinstance(array, list):
|
|
159
|
+
return [SklearnSerializer._array_to_list(item) for item in array]
|
|
160
|
+
elif isinstance(array, tuple):
|
|
161
|
+
return tuple(SklearnSerializer._array_to_list(item) for item in array)
|
|
162
|
+
else:
|
|
163
|
+
return array
|
|
164
|
+
|
|
165
|
+
def serialize(self, model: BaseEstimator) -> Dict[str, Any]:
|
|
166
|
+
"""
|
|
167
|
+
Serialize a scikit-learn estimator to a dictionary.
|
|
168
|
+
|
|
169
|
+
This method extracts relevant attributes from the model, converts them to
|
|
170
|
+
JSON-serializable types, and returns a dictionary representation of the model.
|
|
171
|
+
|
|
172
|
+
Parameters
|
|
173
|
+
----------
|
|
174
|
+
model : BaseEstimator
|
|
175
|
+
The scikit-learn estimator to serialize.
|
|
176
|
+
|
|
177
|
+
Returns
|
|
178
|
+
-------
|
|
179
|
+
Dict[str, Any]
|
|
180
|
+
A dictionary representation of the model.
|
|
181
|
+
|
|
182
|
+
Raises
|
|
183
|
+
------
|
|
184
|
+
SerializationError
|
|
185
|
+
If the model has not been fitted or if there's an error during serialization.
|
|
186
|
+
|
|
187
|
+
Examples
|
|
188
|
+
--------
|
|
189
|
+
>>> from sklearn.linear_model import LogisticRegression
|
|
190
|
+
>>> from sklearn.datasets import make_classification
|
|
191
|
+
>>> X, y = make_classification(n_samples=100, n_features=20, n_classes=2)
|
|
192
|
+
>>> model = LogisticRegression().fit(X, y)
|
|
193
|
+
>>> serializer = SklearnSerializer()
|
|
194
|
+
>>> serialized_dict = serializer.serialize(model)
|
|
195
|
+
"""
|
|
196
|
+
try:
|
|
197
|
+
check_is_fitted(model)
|
|
198
|
+
except NotFittedError as e:
|
|
199
|
+
raise SerializationError("Cannot serialize an unfitted model") from e
|
|
200
|
+
|
|
201
|
+
filtered_attribute_keys = [
|
|
202
|
+
key
|
|
203
|
+
for key in dir(model)
|
|
204
|
+
if not callable(getattr(model, key))
|
|
205
|
+
and not key.endswith("__")
|
|
206
|
+
and type(getattr(model, key)) in SUPPORTED_TYPES
|
|
207
|
+
and (
|
|
208
|
+
not isinstance(getattr(type(model), key, None), property)
|
|
209
|
+
or getattr(type(model), key).fset is not None
|
|
210
|
+
)
|
|
211
|
+
]
|
|
212
|
+
|
|
213
|
+
attribute_values = [getattr(model, key) for key in filtered_attribute_keys]
|
|
214
|
+
attribute_types = [type(value) for value in attribute_values]
|
|
215
|
+
serializable_attribute_values = [
|
|
216
|
+
self._convert_to_serializable_types(value) for value in attribute_values
|
|
217
|
+
]
|
|
218
|
+
|
|
219
|
+
return {
|
|
220
|
+
"attributes": dict(
|
|
221
|
+
zip(filtered_attribute_keys, serializable_attribute_values)
|
|
222
|
+
),
|
|
223
|
+
"attribute_types": [str(attr_type) for attr_type in attribute_types],
|
|
224
|
+
"estimator_class": model.__class__.__name__,
|
|
225
|
+
"params": model.get_params(),
|
|
226
|
+
"producer_name": model.__module__.split(".")[0],
|
|
227
|
+
"producer_version": model.__getstate__()["_sklearn_version"],
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
def deserialize(self, data: Dict[str, Any]) -> BaseEstimator:
|
|
231
|
+
"""
|
|
232
|
+
Deserialize a dictionary representation back into a scikit-learn estimator.
|
|
233
|
+
|
|
234
|
+
This method reconstructs a scikit-learn estimator from its dictionary
|
|
235
|
+
representation, converting attributes back to their original types.
|
|
236
|
+
|
|
237
|
+
Parameters
|
|
238
|
+
----------
|
|
239
|
+
data : Dict[str, Any]
|
|
240
|
+
The dictionary representation of the model.
|
|
241
|
+
|
|
242
|
+
Returns
|
|
243
|
+
-------
|
|
244
|
+
BaseEstimator
|
|
245
|
+
The deserialized scikit-learn estimator.
|
|
246
|
+
|
|
247
|
+
Raises
|
|
248
|
+
------
|
|
249
|
+
UnsupportedEstimatorError
|
|
250
|
+
If the estimator class is not supported.
|
|
251
|
+
|
|
252
|
+
Examples
|
|
253
|
+
--------
|
|
254
|
+
>>> serializer = SklearnSerializer()
|
|
255
|
+
>>> deserialized_model = serializer.deserialize(serialized_dict)
|
|
256
|
+
>>> predictions = deserialized_model.predict(X_test)
|
|
257
|
+
"""
|
|
258
|
+
estimator_class = data["estimator_class"]
|
|
259
|
+
if estimator_class not in SUPPORTED_ESTIMATORS:
|
|
260
|
+
raise UnsupportedEstimatorError(
|
|
261
|
+
f"Unsupported estimator class: {estimator_class}"
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
model = SUPPORTED_ESTIMATORS[estimator_class](**data["params"])
|
|
265
|
+
|
|
266
|
+
for attribute, value in data["attributes"].items():
|
|
267
|
+
setattr(model, attribute, self._convert_to_sklearn_types(value))
|
|
268
|
+
|
|
269
|
+
return model
|
|
@@ -0,0 +1,230 @@
|
|
|
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 os
|
|
7
|
+
from typing import Optional, Union, Protocol, runtime_checkable, TypeVar, cast
|
|
8
|
+
import numpy as np
|
|
9
|
+
from numpy import testing
|
|
10
|
+
from sklearn.base import BaseEstimator
|
|
11
|
+
|
|
12
|
+
from openmodels import SerializationManager, SklearnSerializer
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@runtime_checkable
|
|
16
|
+
class PredictorModel(Protocol):
|
|
17
|
+
def predict(self, X: np.ndarray) -> np.ndarray: ...
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@runtime_checkable
|
|
21
|
+
class TransformerModel(Protocol):
|
|
22
|
+
def transform(self, X: np.ndarray) -> np.ndarray: ...
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@runtime_checkable
|
|
26
|
+
class FittableModel(Protocol):
|
|
27
|
+
def fit(self, X: np.ndarray, y: np.ndarray) -> "FittableModel": ...
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
ModelType = Union[PredictorModel, TransformerModel, FittableModel]
|
|
31
|
+
T = TypeVar("T", bound=Union[BaseEstimator, ModelType])
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def fit_model(
|
|
35
|
+
model: FittableModel, x: np.ndarray, y: np.ndarray, abs: bool = False
|
|
36
|
+
) -> FittableModel:
|
|
37
|
+
"""
|
|
38
|
+
Fits a model to the provided data.
|
|
39
|
+
|
|
40
|
+
Parameters
|
|
41
|
+
----------
|
|
42
|
+
model : T
|
|
43
|
+
The scikit-learn model to fit.
|
|
44
|
+
x : np.ndarray
|
|
45
|
+
The training input samples.
|
|
46
|
+
y : np.ndarray
|
|
47
|
+
The target values (class labels in classification, real numbers in regression).
|
|
48
|
+
abs : bool, default=False
|
|
49
|
+
Whether to take the absolute value of the input data before fitting the model.
|
|
50
|
+
|
|
51
|
+
Returns
|
|
52
|
+
-------
|
|
53
|
+
T
|
|
54
|
+
The fitted scikit-learn model.
|
|
55
|
+
"""
|
|
56
|
+
if not isinstance(model, FittableModel):
|
|
57
|
+
raise TypeError("Model must have a 'fit' method")
|
|
58
|
+
|
|
59
|
+
if abs:
|
|
60
|
+
model.fit(np.absolute(x), y)
|
|
61
|
+
else:
|
|
62
|
+
model.fit(x, y)
|
|
63
|
+
return model
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def run_test_predictions(
|
|
67
|
+
model1: PredictorModel, model2: PredictorModel, x: np.ndarray
|
|
68
|
+
) -> None:
|
|
69
|
+
"""
|
|
70
|
+
Compares the predictions of two models on the given data.
|
|
71
|
+
|
|
72
|
+
Parameters
|
|
73
|
+
----------
|
|
74
|
+
model1 : PredictorModel
|
|
75
|
+
The first scikit-learn model with a predict method.
|
|
76
|
+
model2 : PredictorModel
|
|
77
|
+
The second scikit-learn model with a predict method.
|
|
78
|
+
x : np.ndarray
|
|
79
|
+
The input samples.
|
|
80
|
+
|
|
81
|
+
Raises
|
|
82
|
+
------
|
|
83
|
+
AssertionError
|
|
84
|
+
If the predictions of the two models are not equal.
|
|
85
|
+
"""
|
|
86
|
+
expected_predictions = model1.predict(x)
|
|
87
|
+
actual_predictions = model2.predict(x)
|
|
88
|
+
testing.assert_array_equal(expected_predictions, actual_predictions)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def run_test_transformed_data(
|
|
92
|
+
model1: TransformerModel, model2: TransformerModel, x: np.ndarray
|
|
93
|
+
) -> None:
|
|
94
|
+
"""
|
|
95
|
+
Compares the transformed data of two models on the given data.
|
|
96
|
+
|
|
97
|
+
Parameters
|
|
98
|
+
----------
|
|
99
|
+
model1 : TransformerModel
|
|
100
|
+
The first scikit-learn model with a transform method.
|
|
101
|
+
model2 : TransformerModel
|
|
102
|
+
The second scikit-learn model with a transform method.
|
|
103
|
+
x : np.ndarray
|
|
104
|
+
The input samples.
|
|
105
|
+
|
|
106
|
+
Raises
|
|
107
|
+
------
|
|
108
|
+
AssertionError
|
|
109
|
+
If the transformed data of the two models are not almost equal.
|
|
110
|
+
"""
|
|
111
|
+
expected_transformed_data = model1.transform(x)
|
|
112
|
+
actual_transformed_data = model2.transform(x)
|
|
113
|
+
testing.assert_array_almost_equal(
|
|
114
|
+
expected_transformed_data, actual_transformed_data
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def run_test_model(
|
|
119
|
+
model: FittableModel,
|
|
120
|
+
x: np.ndarray,
|
|
121
|
+
y: np.ndarray,
|
|
122
|
+
x_sparse: Optional[np.ndarray],
|
|
123
|
+
y_sparse: Optional[np.ndarray],
|
|
124
|
+
model_name: str,
|
|
125
|
+
abs: bool = False,
|
|
126
|
+
) -> None:
|
|
127
|
+
"""
|
|
128
|
+
Tests the serialization and deserialization of a scikit-learn model.
|
|
129
|
+
|
|
130
|
+
Parameters
|
|
131
|
+
----------
|
|
132
|
+
model : Union[BaseEstimator, ModelType]
|
|
133
|
+
The scikit-learn model to test.
|
|
134
|
+
x : np.ndarray
|
|
135
|
+
The training input samples.
|
|
136
|
+
y : np.ndarray
|
|
137
|
+
The target values (class labels in classification, real numbers in regression).
|
|
138
|
+
x_sparse : np.ndarray or None
|
|
139
|
+
The sparse training input samples.
|
|
140
|
+
y_sparse : np.ndarray or None
|
|
141
|
+
The sparse target values.
|
|
142
|
+
model_name : str
|
|
143
|
+
The name of the file to save the serialized model to.
|
|
144
|
+
abs : bool, default=False
|
|
145
|
+
Whether to take the absolute value of the input data before fitting the model.
|
|
146
|
+
"""
|
|
147
|
+
# Fit and test the model
|
|
148
|
+
fitted_model = fit_model(model, x, y, abs)
|
|
149
|
+
if x_sparse is not None and y_sparse is not None:
|
|
150
|
+
fit_model(model, x_sparse, y_sparse, abs)
|
|
151
|
+
|
|
152
|
+
# Create a SerializationManager instance
|
|
153
|
+
manager = SerializationManager(SklearnSerializer())
|
|
154
|
+
|
|
155
|
+
# Serialize and deserialize the model
|
|
156
|
+
serialized_model = manager.serialize(fitted_model, format_name="json")
|
|
157
|
+
deserialized_model = manager.deserialize(serialized_model, format_name="json")
|
|
158
|
+
|
|
159
|
+
# Test the deserialized model
|
|
160
|
+
if isinstance(model, PredictorModel):
|
|
161
|
+
run_test_predictions(
|
|
162
|
+
cast(PredictorModel, fitted_model),
|
|
163
|
+
cast(PredictorModel, deserialized_model),
|
|
164
|
+
x,
|
|
165
|
+
)
|
|
166
|
+
elif isinstance(model, TransformerModel):
|
|
167
|
+
run_test_transformed_data(
|
|
168
|
+
cast(TransformerModel, fitted_model),
|
|
169
|
+
cast(TransformerModel, deserialized_model),
|
|
170
|
+
x,
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
# Serialize and deserialize the model to/from a file
|
|
174
|
+
model_file_path = f"./test/temp/{model_name}.json"
|
|
175
|
+
|
|
176
|
+
# Ensure the directory exists
|
|
177
|
+
os.makedirs(os.path.dirname(model_file_path), exist_ok=True)
|
|
178
|
+
|
|
179
|
+
with open(model_file_path, "w", encoding="utf-8") as f:
|
|
180
|
+
f.write(serialized_model)
|
|
181
|
+
|
|
182
|
+
with open(model_file_path, "r", encoding="utf-8") as f:
|
|
183
|
+
serialized_model_from_file = f.read()
|
|
184
|
+
|
|
185
|
+
deserialized_model_from_file = manager.deserialize(
|
|
186
|
+
serialized_model_from_file, format_name="json"
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
# Test the deserialized model from file
|
|
190
|
+
if isinstance(model, PredictorModel):
|
|
191
|
+
run_test_predictions(
|
|
192
|
+
cast(PredictorModel, fitted_model),
|
|
193
|
+
cast(PredictorModel, deserialized_model_from_file),
|
|
194
|
+
x,
|
|
195
|
+
)
|
|
196
|
+
elif isinstance(model, TransformerModel):
|
|
197
|
+
run_test_transformed_data(
|
|
198
|
+
cast(TransformerModel, fitted_model),
|
|
199
|
+
cast(TransformerModel, deserialized_model_from_file),
|
|
200
|
+
x,
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
# Clean up the temporary file
|
|
204
|
+
os.remove(model_file_path)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def create_test_data(
|
|
208
|
+
n_samples: int = 100, n_features: int = 5, random_state: int = 42
|
|
209
|
+
) -> tuple:
|
|
210
|
+
"""
|
|
211
|
+
Creates test data for model fitting and testing.
|
|
212
|
+
|
|
213
|
+
Parameters
|
|
214
|
+
----------
|
|
215
|
+
n_samples : int, optional
|
|
216
|
+
The number of samples to generate (default is 100).
|
|
217
|
+
n_features : int, optional
|
|
218
|
+
The number of features to generate (default is 5).
|
|
219
|
+
random_state : int, optional
|
|
220
|
+
The random state for reproducibility (default is 42).
|
|
221
|
+
|
|
222
|
+
Returns
|
|
223
|
+
-------
|
|
224
|
+
tuple
|
|
225
|
+
A tuple containing (X, y) where X is the feature matrix and y is the target vector.
|
|
226
|
+
"""
|
|
227
|
+
np.random.seed(random_state)
|
|
228
|
+
x = np.random.randn(n_samples, n_features)
|
|
229
|
+
y = np.random.randint(0, 2, size=n_samples)
|
|
230
|
+
return x, y
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
[tool.poetry]
|
|
2
|
+
name = "openmodels"
|
|
3
|
+
version = "0.1.0-alpha.1"
|
|
4
|
+
description = "Export scikit-learn model files to JSON for sharing or deploying predictive models with peace of mind."
|
|
5
|
+
authors = [
|
|
6
|
+
"Alejandro Gutierrez <agutierrez@sftec.es>, Pau Cabaneros <pau.cabaneros@gmail.com>, Raúl Marín <hi@raulmarin.dev>, Ruben Parrilla <rparrilla@sftec.es>",
|
|
7
|
+
]
|
|
8
|
+
license = "MIT"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
|
|
11
|
+
[tool.poetry.dependencies]
|
|
12
|
+
python = ">=3.9,<4.0"
|
|
13
|
+
scikit-learn = "^1.5.0"
|
|
14
|
+
|
|
15
|
+
[tool.poetry.group.dev.dependencies]
|
|
16
|
+
poetry-types = "^0.5.1"
|
|
17
|
+
mypy = "^1.10.0"
|
|
18
|
+
pytest = "^8.2.2"
|
|
19
|
+
pre-commit = "^3.7.1"
|
|
20
|
+
black = "^24.4.2"
|
|
21
|
+
flake8 = "^7.1.1"
|
|
22
|
+
|
|
23
|
+
[build-system]
|
|
24
|
+
requires = ["poetry-core"]
|
|
25
|
+
build-backend = "poetry.core.masonry.api"
|
|
26
|
+
|
|
27
|
+
[[tool.mypy.overrides]]
|
|
28
|
+
module = ["sklearn", "sklearn.*"]
|
|
29
|
+
ignore_missing_imports = true
|