openmodels 0.2.3__tar.gz → 0.2.4__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.2.3 → openmodels-0.2.4}/PKG-INFO +7 -7
- {openmodels-0.2.3 → openmodels-0.2.4}/README.md +6 -6
- {openmodels-0.2.3 → openmodels-0.2.4}/openmodels/serializers/base.py +6 -1
- openmodels-0.2.4/openmodels/serializers/sklearn/_state_validation.py +217 -0
- openmodels-0.2.4/openmodels/serializers/sklearn/_tree_validation.py +363 -0
- {openmodels-0.2.3 → openmodels-0.2.4}/openmodels/serializers/sklearn/sklearn_serializer.py +26 -3
- {openmodels-0.2.3 → openmodels-0.2.4}/pyproject.toml +1 -1
- {openmodels-0.2.3 → openmodels-0.2.4}/LICENSE +0 -0
- {openmodels-0.2.3 → openmodels-0.2.4}/openmodels/__init__.py +0 -0
- {openmodels-0.2.3 → openmodels-0.2.4}/openmodels/converters/__init__.py +0 -0
- {openmodels-0.2.3 → openmodels-0.2.4}/openmodels/converters/json_converter.py +0 -0
- {openmodels-0.2.3 → openmodels-0.2.4}/openmodels/converters/msgpack_converter.py +0 -0
- {openmodels-0.2.3 → openmodels-0.2.4}/openmodels/converters/pickle_converter.py +0 -0
- {openmodels-0.2.3 → openmodels-0.2.4}/openmodels/converters/yaml_converter.py +0 -0
- {openmodels-0.2.3 → openmodels-0.2.4}/openmodels/core.py +0 -0
- {openmodels-0.2.3 → openmodels-0.2.4}/openmodels/exceptions.py +0 -0
- {openmodels-0.2.3 → openmodels-0.2.4}/openmodels/format_registry.py +0 -0
- {openmodels-0.2.3 → openmodels-0.2.4}/openmodels/protocols.py +0 -0
- {openmodels-0.2.3 → openmodels-0.2.4}/openmodels/serializers/__init__.py +0 -0
- {openmodels-0.2.3 → openmodels-0.2.4}/openmodels/serializers/sklearn/__init__.py +0 -0
- {openmodels-0.2.3 → openmodels-0.2.4}/openmodels/serializers/sklearn/_custom_estimator.py +0 -0
- {openmodels-0.2.3 → openmodels-0.2.4}/openmodels/test_helpers.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: openmodels
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.4
|
|
4
4
|
Summary: Export scikit-learn model files to JSON for sharing or deploying predictive models with peace of mind.
|
|
5
5
|
License-Expression: MIT
|
|
6
6
|
License-File: LICENSE
|
|
@@ -268,12 +268,12 @@ To run the tests:
|
|
|
268
268
|
|
|
269
269
|
## Security
|
|
270
270
|
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
code
|
|
275
|
-
[SECURITY.md](https://github.com/Gnpd/openmodels/blob/main/SECURITY.md) for details and
|
|
276
|
-
|
|
271
|
+
Loading a JSON, MessagePack or YAML file doesn't execute code from it, and the model's fitted
|
|
272
|
+
state is checked before scikit-learn uses it. Still, a model from an untrusted source can
|
|
273
|
+
predict whatever its author chose, so treat its outputs as untrusted. Pickle files can execute
|
|
274
|
+
arbitrary code: only load them from sources you trust. See
|
|
275
|
+
[SECURITY.md](https://github.com/Gnpd/openmodels/blob/main/SECURITY.md) for details and how
|
|
276
|
+
to report a vulnerability.
|
|
277
277
|
|
|
278
278
|
## License
|
|
279
279
|
|
|
@@ -235,12 +235,12 @@ To run the tests:
|
|
|
235
235
|
|
|
236
236
|
## Security
|
|
237
237
|
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
code
|
|
242
|
-
[SECURITY.md](https://github.com/Gnpd/openmodels/blob/main/SECURITY.md) for details and
|
|
243
|
-
|
|
238
|
+
Loading a JSON, MessagePack or YAML file doesn't execute code from it, and the model's fitted
|
|
239
|
+
state is checked before scikit-learn uses it. Still, a model from an untrusted source can
|
|
240
|
+
predict whatever its author chose, so treat its outputs as untrusted. Pickle files can execute
|
|
241
|
+
arbitrary code: only load them from sources you trust. See
|
|
242
|
+
[SECURITY.md](https://github.com/Gnpd/openmodels/blob/main/SECURITY.md) for details and how
|
|
243
|
+
to report a vulnerability.
|
|
244
244
|
|
|
245
245
|
## License
|
|
246
246
|
|
|
@@ -584,7 +584,7 @@ class ScipySerializerMixin(SerializerMixin):
|
|
|
584
584
|
|
|
585
585
|
def _deserialize_csr_matrix(self, value, value_dtype=None):
|
|
586
586
|
dtype = value.get("dtype", None) or value_dtype or np.float64
|
|
587
|
-
|
|
587
|
+
matrix = csr_matrix(
|
|
588
588
|
(
|
|
589
589
|
np.array(value["data"], dtype=dtype),
|
|
590
590
|
np.array(value["indices"], dtype=np.int32),
|
|
@@ -592,6 +592,11 @@ class ScipySerializerMixin(SerializerMixin):
|
|
|
592
592
|
),
|
|
593
593
|
shape=tuple(value["shape"]),
|
|
594
594
|
)
|
|
595
|
+
# The constructor only checks the index arrays' lengths; scipy's C++ kernels (e.g. a
|
|
596
|
+
# matrix-vector product at predict) then read x[indices[j]] unchecked. The full check
|
|
597
|
+
# also range-checks every column index and that indptr is non-decreasing.
|
|
598
|
+
matrix.check_format(full_check=True)
|
|
599
|
+
return matrix
|
|
595
600
|
|
|
596
601
|
def _serialize_interp1d(self, value: interp1d):
|
|
597
602
|
fill_value = getattr(value, "fill_value", np.nan)
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Structural checks on non-tree fitted state loaded from a file (tree state is checked in
|
|
3
|
+
`_tree_validation`).
|
|
4
|
+
|
|
5
|
+
scikit-learn's compiled prediction code trusts the shapes of fitted arrays: libsvm sizes its reads
|
|
6
|
+
from `_n_support`, Cython loops (KMeans, pairwise distances, gradient boosting's
|
|
7
|
+
`predict_stages`) run with `boundscheck=False` over widths taken from one array while indexing
|
|
8
|
+
another. A crafted file with inconsistent shapes then makes `predict` crash the process or read
|
|
9
|
+
(or, for gradient boosting, write) memory outside the arrays. These checks reject such files at
|
|
10
|
+
load with `DeserializationError`.
|
|
11
|
+
|
|
12
|
+
Only inconsistencies that reach unchecked compiled code are checked here. Mismatches that
|
|
13
|
+
NumPy or scikit-learn already turn into a clean exception at `predict` (e.g. a short `classes_`)
|
|
14
|
+
are left to them. Sparse matrices are range-checked where they're built
|
|
15
|
+
(`ScipySerializerMixin._deserialize_csr_matrix`).
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
import scipy.sparse as sp # type: ignore
|
|
22
|
+
from sklearn.cluster import Birch, BisectingKMeans, KMeans, MiniBatchKMeans
|
|
23
|
+
from sklearn.ensemble._gb import BaseGradientBoosting
|
|
24
|
+
from sklearn.neighbors._base import NeighborsBase
|
|
25
|
+
from sklearn.svm._base import BaseLibSVM, BaseSVC
|
|
26
|
+
|
|
27
|
+
from openmodels.exceptions import DeserializationError
|
|
28
|
+
from openmodels.serializers.sklearn._tree_validation import (
|
|
29
|
+
_CORRUPT,
|
|
30
|
+
_fail,
|
|
31
|
+
_n_features_in,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _name(model: Any) -> str:
|
|
36
|
+
return type(model).__name__
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _int_vector(value: Any, what: str) -> np.ndarray:
|
|
40
|
+
arr = np.asarray(value)
|
|
41
|
+
if arr.ndim != 1 or not (arr.size == 0 or np.issubdtype(arr.dtype, np.integer)):
|
|
42
|
+
_fail(
|
|
43
|
+
f"{what} must be a 1-D integer array, got shape {arr.shape} ({arr.dtype})"
|
|
44
|
+
)
|
|
45
|
+
return arr
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _validate_libsvm(model: BaseLibSVM) -> None:
|
|
49
|
+
"""
|
|
50
|
+
libsvm's `set_model` takes `nr_class = len(_n_support)` and reads, without checks,
|
|
51
|
+
`nr_class - 1` rows of `l` coefficients from `_dual_coef_`, `nr_class * (nr_class - 1) / 2`
|
|
52
|
+
entries from `_intercept_` (and `_probA`/`_probB`), and, for classifiers, splits the `l`
|
|
53
|
+
support vectors by the counts in `_n_support`. `l` is the number of support vectors, or of
|
|
54
|
+
`support_` entries with a precomputed kernel, where `support_` indexes columns of `X`.
|
|
55
|
+
"""
|
|
56
|
+
required = (
|
|
57
|
+
"_n_support",
|
|
58
|
+
"support_",
|
|
59
|
+
"support_vectors_",
|
|
60
|
+
"_dual_coef_",
|
|
61
|
+
"_intercept_",
|
|
62
|
+
)
|
|
63
|
+
if not all(hasattr(model, attr) for attr in required):
|
|
64
|
+
return # unfitted, or missing state that makes predict fail cleanly
|
|
65
|
+
name = _name(model)
|
|
66
|
+
n_support = _int_vector(model._n_support, f"{name}._n_support")
|
|
67
|
+
support = _int_vector(model.support_, f"{name}.support_")
|
|
68
|
+
nr_class = n_support.shape[0]
|
|
69
|
+
is_classifier = isinstance(model, BaseSVC)
|
|
70
|
+
if nr_class < 2 or (not is_classifier and nr_class != 2):
|
|
71
|
+
_fail(f"{name}._n_support has {nr_class} entries")
|
|
72
|
+
precomputed = getattr(model, "kernel", None) == "precomputed"
|
|
73
|
+
|
|
74
|
+
sv = model.support_vectors_
|
|
75
|
+
if precomputed:
|
|
76
|
+
n_sv = support.shape[0]
|
|
77
|
+
shape_fit = np.asarray(getattr(model, "shape_fit_", ()))
|
|
78
|
+
if shape_fit.ndim != 1 or shape_fit.shape[0] < 1:
|
|
79
|
+
_fail(f"{name}.shape_fit_ is missing or malformed")
|
|
80
|
+
if ((support < 0) | (support >= shape_fit[0])).any():
|
|
81
|
+
_fail(
|
|
82
|
+
f"{name}.support_ indexes training samples outside [0, {int(shape_fit[0])})"
|
|
83
|
+
)
|
|
84
|
+
else:
|
|
85
|
+
if sv.ndim != 2:
|
|
86
|
+
_fail(f"{name}.support_vectors_ must be 2-D, got shape {sv.shape}")
|
|
87
|
+
n_sv = sv.shape[0]
|
|
88
|
+
if support.shape[0] != n_sv:
|
|
89
|
+
_fail(
|
|
90
|
+
f"{name} has {n_sv} support vectors but {support.shape[0]} support_ entries"
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
if is_classifier and ((n_support < 0).any() or int(n_support.sum()) != n_sv):
|
|
94
|
+
_fail(
|
|
95
|
+
f"{name}._n_support is {n_support.tolist()}, but there are {n_sv} support vectors"
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
dual = model._dual_coef_
|
|
99
|
+
if dual.ndim != 2 or dual.shape != (nr_class - 1, n_sv):
|
|
100
|
+
_fail(
|
|
101
|
+
f"{name}._dual_coef_ has shape {dual.shape}, expected {(nr_class - 1, n_sv)}"
|
|
102
|
+
)
|
|
103
|
+
if sp.issparse(dual) and dual.nnz != dual.shape[0] * dual.shape[1]:
|
|
104
|
+
# The sparse predict path passes `_dual_coef_.data` to libsvm as dense coefficients.
|
|
105
|
+
_fail(
|
|
106
|
+
f"{name}._dual_coef_ must store all {dual.shape[0] * dual.shape[1]} coefficients"
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
n_pairs = nr_class * (nr_class - 1) // 2
|
|
110
|
+
intercept = np.asarray(model._intercept_)
|
|
111
|
+
if intercept.ndim != 1 or intercept.shape[0] != n_pairs:
|
|
112
|
+
_fail(f"{name}._intercept_ has shape {intercept.shape}, expected ({n_pairs},)")
|
|
113
|
+
for attr in ("_probA", "_probB"):
|
|
114
|
+
prob = getattr(model, attr, None)
|
|
115
|
+
if prob is None:
|
|
116
|
+
continue
|
|
117
|
+
prob = np.asarray(prob)
|
|
118
|
+
if prob.size and (prob.ndim != 1 or prob.shape[0] != n_pairs):
|
|
119
|
+
_fail(f"{name}.{attr} has shape {prob.shape}, expected ({n_pairs},)")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _validate_kmeans(model: Any) -> None:
|
|
123
|
+
"""The Cython label assignment loops over `X`'s columns and indexes the centers with them
|
|
124
|
+
(and vice versa), so every center must be exactly `n_features_in_` wide."""
|
|
125
|
+
width = _n_features_in(model)
|
|
126
|
+
name = _name(model)
|
|
127
|
+
centers = np.asarray(model.cluster_centers_)
|
|
128
|
+
if centers.ndim != 2 or centers.shape[0] < 1 or centers.shape[1] != width:
|
|
129
|
+
_fail(
|
|
130
|
+
f"{name}.cluster_centers_ has shape {centers.shape}, expected (n, {width})"
|
|
131
|
+
)
|
|
132
|
+
if isinstance(model, BisectingKMeans):
|
|
133
|
+
# predict walks the bisecting tree and labels against each node's own centers.
|
|
134
|
+
stack = [getattr(model, "_bisecting_tree", None)]
|
|
135
|
+
while stack:
|
|
136
|
+
node = stack.pop()
|
|
137
|
+
if node is None:
|
|
138
|
+
continue
|
|
139
|
+
# (width,) when fitted on dense data, (1, width) on sparse; predict vstacks them.
|
|
140
|
+
center = np.asarray(node.center)
|
|
141
|
+
if center.shape not in ((width,), (1, width)):
|
|
142
|
+
_fail(
|
|
143
|
+
f"{name} tree node center has shape {center.shape}, expected ({width},)"
|
|
144
|
+
)
|
|
145
|
+
stack.extend((getattr(node, "left", None), getattr(node, "right", None)))
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _validate_neighbors(model: NeighborsBase) -> None:
|
|
149
|
+
"""Brute-force search computes distances over `X`'s width while reading `_fit_X` rows."""
|
|
150
|
+
fit_X = getattr(model, "_fit_X", None)
|
|
151
|
+
if fit_X is None or not hasattr(model, "n_features_in_"):
|
|
152
|
+
return
|
|
153
|
+
width = _n_features_in(model)
|
|
154
|
+
if fit_X.ndim != 2 or fit_X.shape[1] != width:
|
|
155
|
+
_fail(f"{_name(model)}._fit_X has shape {fit_X.shape}, expected (n, {width})")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _validate_gradient_boosting(model: BaseGradientBoosting) -> None:
|
|
159
|
+
"""
|
|
160
|
+
`predict_stages` adds tree `k`'s output into column `k` of the init estimator's raw
|
|
161
|
+
predictions, for `k < estimators_.shape[1]`, without bounds checks: the two widths must
|
|
162
|
+
match. The init width depends on `init_` (and the loss), so it's measured by running the
|
|
163
|
+
init step on one row of zeros, exactly as predict does.
|
|
164
|
+
"""
|
|
165
|
+
estimators = getattr(model, "estimators_", None)
|
|
166
|
+
if estimators is None:
|
|
167
|
+
return
|
|
168
|
+
name = _name(model)
|
|
169
|
+
estimators = np.asarray(estimators, dtype=object)
|
|
170
|
+
if estimators.ndim != 2 or estimators.shape[0] < 1 or estimators.shape[1] < 1:
|
|
171
|
+
_fail(
|
|
172
|
+
f"{name}.estimators_ has shape {estimators.shape}, expected (n_stages, K)"
|
|
173
|
+
)
|
|
174
|
+
width = _n_features_in(model)
|
|
175
|
+
try:
|
|
176
|
+
init_width = model._raw_predict_init(np.zeros((1, width))).shape[1]
|
|
177
|
+
except DeserializationError:
|
|
178
|
+
raise
|
|
179
|
+
except Exception as e:
|
|
180
|
+
raise DeserializationError(
|
|
181
|
+
f"{name}'s init step fails on a valid input ({type(e).__name__}: {e}); {_CORRUPT}."
|
|
182
|
+
) from e
|
|
183
|
+
if init_width != estimators.shape[1]:
|
|
184
|
+
_fail(
|
|
185
|
+
f"{name} has {estimators.shape[1]} trees per stage, but its init step outputs "
|
|
186
|
+
f"{init_width} columns"
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _validate_birch(model: Birch) -> None:
|
|
191
|
+
"""`partial_fit` (via `_get_leaves`) walks `next_leaf_` from `dummy_leaf_` until `None`;
|
|
192
|
+
a cycle in the chain makes it loop forever."""
|
|
193
|
+
node = getattr(getattr(model, "dummy_leaf_", None), "next_leaf_", None)
|
|
194
|
+
seen = set()
|
|
195
|
+
while node is not None:
|
|
196
|
+
if id(node) in seen:
|
|
197
|
+
_fail(f"{_name(model)} leaf chain has a cycle")
|
|
198
|
+
if not getattr(node, "is_leaf", False):
|
|
199
|
+
_fail(f"{_name(model)} leaf chain links to a non-leaf node")
|
|
200
|
+
seen.add(id(node))
|
|
201
|
+
node = getattr(node, "next_leaf_", None)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def validate_fitted_state(model: Any) -> None:
|
|
205
|
+
"""After an estimator's attributes are all set (and derived ones rebuilt)."""
|
|
206
|
+
if isinstance(model, BaseLibSVM):
|
|
207
|
+
_validate_libsvm(model)
|
|
208
|
+
if isinstance(model, (KMeans, MiniBatchKMeans, BisectingKMeans)) and hasattr(
|
|
209
|
+
model, "cluster_centers_"
|
|
210
|
+
):
|
|
211
|
+
_validate_kmeans(model)
|
|
212
|
+
if isinstance(model, NeighborsBase):
|
|
213
|
+
_validate_neighbors(model)
|
|
214
|
+
if isinstance(model, BaseGradientBoosting):
|
|
215
|
+
_validate_gradient_boosting(model)
|
|
216
|
+
if isinstance(model, Birch):
|
|
217
|
+
_validate_birch(model)
|
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Structural checks on tree state loaded from a file.
|
|
3
|
+
|
|
4
|
+
scikit-learn's Cython code walks `Tree` and `TreePredictor` node arrays without bounds checks,
|
|
5
|
+
so a crafted file with out-of-range or backward child/feature indices can make `predict` crash
|
|
6
|
+
the process, loop forever or read memory outside the arrays (returning garbage predictions).
|
|
7
|
+
These checks reject such files at load, with `DeserializationError`, before any of that code
|
|
8
|
+
runs.
|
|
9
|
+
|
|
10
|
+
Two levels, because some invariants need context the node arrays don't have:
|
|
11
|
+
|
|
12
|
+
- Per tree (`validate_tree_header`, `validate_tree_node_count`, `validate_tree`,
|
|
13
|
+
`validate_tree_predictor`): every internal node's children have a higher index than the node
|
|
14
|
+
itself and are below the node count (which also rules out cycles), leaves use the sentinels
|
|
15
|
+
scikit-learn writes, and indices into side arrays (bitsets) are in range. They run on the
|
|
16
|
+
arrays the Cython code actually reads, after construction, so dtype tricks in the file can't
|
|
17
|
+
get past them.
|
|
18
|
+
- Per estimator (`validate_feature_widths`): split features must index columns the input `X`
|
|
19
|
+
is guaranteed to have. scikit-learn checks `X` against the estimator's `n_features_in_` only
|
|
20
|
+
when that attribute exists, and ensembles (forests, gradient boosting, IsolationForest) pass
|
|
21
|
+
`X` to their trees with `check_input=False`, so the bound has to come from the estimator that
|
|
22
|
+
validates `X`, not from the tree's own `n_features`.
|
|
23
|
+
|
|
24
|
+
All checks are vectorized: loading a large forest stays fast.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from typing import Any, Optional
|
|
28
|
+
|
|
29
|
+
import numpy as np
|
|
30
|
+
from sklearn.ensemble import (
|
|
31
|
+
BaseEnsemble,
|
|
32
|
+
HistGradientBoostingClassifier,
|
|
33
|
+
HistGradientBoostingRegressor,
|
|
34
|
+
IsolationForest,
|
|
35
|
+
)
|
|
36
|
+
from sklearn.ensemble._bagging import BaseBagging
|
|
37
|
+
from sklearn.ensemble._forest import BaseForest
|
|
38
|
+
from sklearn.ensemble._gb import BaseGradientBoosting
|
|
39
|
+
from sklearn.ensemble._hist_gradient_boosting.predictor import TreePredictor
|
|
40
|
+
from sklearn.tree._tree import Tree
|
|
41
|
+
|
|
42
|
+
from openmodels.exceptions import DeserializationError
|
|
43
|
+
|
|
44
|
+
# scikit-learn's sentinel for "no child" (sklearn.tree._tree.TREE_LEAF).
|
|
45
|
+
_TREE_LEAF = -1
|
|
46
|
+
|
|
47
|
+
_CORRUPT = "the file is corrupt or was crafted"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _fail(message: str) -> None:
|
|
51
|
+
raise DeserializationError(f"{message}; {_CORRUPT}.")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _as_int(value: Any, what: str) -> int:
|
|
55
|
+
"""`value` as an int, rejecting bools, floats and anything else that isn't an integer."""
|
|
56
|
+
if isinstance(value, np.ndarray) and value.ndim == 0:
|
|
57
|
+
value = value[()]
|
|
58
|
+
if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, np.integer)):
|
|
59
|
+
_fail(f"{what} must be an integer, got {value!r}")
|
|
60
|
+
return int(value)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _check_children(
|
|
64
|
+
left: np.ndarray, right: np.ndarray, internal: np.ndarray, what: str
|
|
65
|
+
) -> None:
|
|
66
|
+
"""
|
|
67
|
+
For every internal node i: i < left[i] < n and i < right[i] < n. Children always follow
|
|
68
|
+
their parent in scikit-learn's node arrays (both the depth-first and best-first builders
|
|
69
|
+
append a node's children after it), so this holds for every fitted tree, and it makes
|
|
70
|
+
every walk from the root strictly increasing: no out-of-range read, no cycle.
|
|
71
|
+
"""
|
|
72
|
+
n_nodes = left.shape[0]
|
|
73
|
+
idx = np.flatnonzero(internal)
|
|
74
|
+
child_left = left[idx].astype(np.int64)
|
|
75
|
+
child_right = right[idx].astype(np.int64)
|
|
76
|
+
bad = (
|
|
77
|
+
(child_left <= idx)
|
|
78
|
+
| (child_left >= n_nodes)
|
|
79
|
+
| (child_right <= idx)
|
|
80
|
+
| (child_right >= n_nodes)
|
|
81
|
+
)
|
|
82
|
+
if bad.any():
|
|
83
|
+
i = int(idx[np.argmax(bad)])
|
|
84
|
+
_fail(
|
|
85
|
+
f"{what}: node {i} has children ({int(left[i])}, {int(right[i])}), but children "
|
|
86
|
+
f"must come after their parent and be below the node count {n_nodes}"
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def validate_tree_header(n_features: Any, n_outputs: Any, n_classes: Any) -> None:
|
|
91
|
+
"""Check the `Tree(n_features, n_classes, n_outputs)` constructor arguments, which
|
|
92
|
+
`Tree.__cinit__` copies without bounds checks (it reads `n_classes[k]` for each output).
|
|
93
|
+
"""
|
|
94
|
+
n_features = _as_int(n_features, "Tree n_features")
|
|
95
|
+
n_outputs = _as_int(n_outputs, "Tree n_outputs")
|
|
96
|
+
if n_features < 1 or n_outputs < 1:
|
|
97
|
+
_fail(
|
|
98
|
+
f"Tree has n_features={n_features} and n_outputs={n_outputs}, both must be >= 1"
|
|
99
|
+
)
|
|
100
|
+
classes = np.asarray(n_classes)
|
|
101
|
+
if (
|
|
102
|
+
classes.ndim != 1
|
|
103
|
+
or classes.shape[0] != n_outputs
|
|
104
|
+
or not np.issubdtype(classes.dtype, np.integer)
|
|
105
|
+
or (classes < 1).any()
|
|
106
|
+
):
|
|
107
|
+
_fail(
|
|
108
|
+
f"Tree n_classes must be {n_outputs} positive integer(s) (one per output), got "
|
|
109
|
+
f"{n_classes!r}"
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def validate_tree_node_count(state: dict, nodes: np.ndarray) -> None:
|
|
114
|
+
"""
|
|
115
|
+
Before `Tree.__setstate__`: the stated node count and the values array must match the node
|
|
116
|
+
array. Some scikit-learn versions take `node_count` from the state as is, and the tree's
|
|
117
|
+
array viewsn (`children_left`, ...) then span `node_count` nodes of a smaller buffer.
|
|
118
|
+
"""
|
|
119
|
+
if nodes.ndim != 1 or nodes.shape[0] < 1:
|
|
120
|
+
_fail(f"Tree nodes must be a non-empty 1-D array, got shape {nodes.shape}")
|
|
121
|
+
if "node_count" in state:
|
|
122
|
+
node_count = _as_int(state["node_count"], "Tree node_count")
|
|
123
|
+
if node_count != nodes.shape[0]:
|
|
124
|
+
_fail(
|
|
125
|
+
f"Tree node_count is {node_count}, but the file has {nodes.shape[0]} nodes"
|
|
126
|
+
)
|
|
127
|
+
# scikit-learn checks the full shape too, but with version-dependent wording; checking the
|
|
128
|
+
# node dimension here keeps the error the same on every supported version.
|
|
129
|
+
if "values" in state:
|
|
130
|
+
values = np.asarray(state["values"])
|
|
131
|
+
if values.ndim < 1 or values.shape[0] != nodes.shape[0]:
|
|
132
|
+
_fail(
|
|
133
|
+
f"Tree values has shape {values.shape}, but the file has {nodes.shape[0]} nodes"
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def validate_tree(tree: Tree) -> None:
|
|
138
|
+
"""Check a `Tree` after `__setstate__`, on the arrays its Cython code reads."""
|
|
139
|
+
if tree.node_count < 1:
|
|
140
|
+
_fail("Tree has no nodes")
|
|
141
|
+
left = np.asarray(tree.children_left)
|
|
142
|
+
right = np.asarray(tree.children_right)
|
|
143
|
+
feature = np.asarray(tree.feature)
|
|
144
|
+
|
|
145
|
+
internal = left != _TREE_LEAF
|
|
146
|
+
# Traversal stops at a node whose left child is TREE_LEAF; scikit-learn always sets both.
|
|
147
|
+
leaves = ~internal
|
|
148
|
+
if (right[leaves] != _TREE_LEAF).any():
|
|
149
|
+
i = int(np.flatnonzero(leaves & (right != _TREE_LEAF))[0])
|
|
150
|
+
_fail(f"Tree node {i} has a left child but no right child (or vice versa)")
|
|
151
|
+
_check_children(left, right, internal, "Tree")
|
|
152
|
+
|
|
153
|
+
split_features = feature[internal]
|
|
154
|
+
bad = (split_features < 0) | (split_features >= tree.n_features)
|
|
155
|
+
if bad.any():
|
|
156
|
+
i = int(np.flatnonzero(internal)[np.argmax(bad)])
|
|
157
|
+
_fail(
|
|
158
|
+
f"Tree node {i} splits on feature {int(feature[i])}, outside the tree's "
|
|
159
|
+
f"{tree.n_features} features"
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def validate_tree_predictor(predictor: TreePredictor) -> None:
|
|
164
|
+
"""Check a HistGradientBoosting `TreePredictor` after construction, on the arrays its
|
|
165
|
+
Cython code reads. Feature indices are checked against the estimator's width later, in
|
|
166
|
+
`validate_feature_widths`."""
|
|
167
|
+
nodes = predictor.nodes
|
|
168
|
+
if nodes.ndim != 1 or nodes.shape[0] < 1:
|
|
169
|
+
_fail(f"TreePredictor nodes must be a non-empty 1-D array, got {nodes.shape}")
|
|
170
|
+
|
|
171
|
+
internal = nodes["is_leaf"] == 0
|
|
172
|
+
_check_children(nodes["left"], nodes["right"], internal, "TreePredictor")
|
|
173
|
+
|
|
174
|
+
feature_idx = nodes["feature_idx"]
|
|
175
|
+
if (feature_idx[internal] < 0).any():
|
|
176
|
+
i = int(np.flatnonzero(internal & (feature_idx < 0))[0])
|
|
177
|
+
_fail(
|
|
178
|
+
f"TreePredictor node {i} splits on negative feature {int(feature_idx[i])}"
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
# Categorical splits look up row `bitset_idx` in both bitset arrays (the column is a
|
|
182
|
+
# uint8 category // 32, so always < 8).
|
|
183
|
+
categorical = internal & (nodes["is_categorical"] != 0)
|
|
184
|
+
if categorical.any():
|
|
185
|
+
for name in ("binned_left_cat_bitsets", "raw_left_cat_bitsets"):
|
|
186
|
+
bitsets = getattr(predictor, name)
|
|
187
|
+
if bitsets.ndim != 2 or bitsets.shape[1] != 8:
|
|
188
|
+
_fail(
|
|
189
|
+
f"TreePredictor {name} must have shape (n, 8), got {bitsets.shape}"
|
|
190
|
+
)
|
|
191
|
+
n_bitsets = min(
|
|
192
|
+
predictor.binned_left_cat_bitsets.shape[0],
|
|
193
|
+
predictor.raw_left_cat_bitsets.shape[0],
|
|
194
|
+
)
|
|
195
|
+
bitset_idx = nodes["bitset_idx"].astype(np.int64)
|
|
196
|
+
bad = categorical & (bitset_idx >= n_bitsets)
|
|
197
|
+
if bad.any():
|
|
198
|
+
i = int(np.flatnonzero(bad)[0])
|
|
199
|
+
_fail(
|
|
200
|
+
f"TreePredictor node {i} uses categorical bitset {int(bitset_idx[i])}, but "
|
|
201
|
+
f"there are only {n_bitsets}"
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _n_features_in(model: Any) -> int:
|
|
206
|
+
"""The estimator's input width, which scikit-learn checks `X` against. Required: without
|
|
207
|
+
it, scikit-learn silently accepts an `X` of any width."""
|
|
208
|
+
if not hasattr(model, "n_features_in_"):
|
|
209
|
+
_fail(
|
|
210
|
+
f"{type(model).__name__} has tree state but no n_features_in_, so the width of "
|
|
211
|
+
f"its input can't be checked"
|
|
212
|
+
)
|
|
213
|
+
width = _as_int(model.n_features_in_, f"{type(model).__name__}.n_features_in_")
|
|
214
|
+
if width < 1:
|
|
215
|
+
_fail(f"{type(model).__name__}.n_features_in_ is {width}, must be >= 1")
|
|
216
|
+
return width
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _sub_estimator_width(est: Any, owner: Any) -> Optional[int]:
|
|
220
|
+
"""A sub-estimator's `n_features_in_`, required when it holds a tree (its own check in
|
|
221
|
+
`validate_feature_widths` already ran when it was loaded)."""
|
|
222
|
+
if isinstance(getattr(est, "tree_", None), Tree):
|
|
223
|
+
return _n_features_in(est)
|
|
224
|
+
if hasattr(est, "n_features_in_"):
|
|
225
|
+
return _as_int(est.n_features_in_, f"{type(owner).__name__} sub-estimator")
|
|
226
|
+
return None
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _validate_hist_gradient_boosting(model: Any) -> None:
|
|
230
|
+
predictors = getattr(model, "_predictors", None)
|
|
231
|
+
if not predictors:
|
|
232
|
+
return
|
|
233
|
+
flat = [p for iteration in predictors for p in iteration]
|
|
234
|
+
if not all(isinstance(p, TreePredictor) for p in flat):
|
|
235
|
+
_fail(
|
|
236
|
+
f"{type(model).__name__}._predictors must hold only TreePredictor objects"
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
# The predictors read `X` after `_preprocess_X`: validated against n_features_in_ when
|
|
240
|
+
# there's no preprocessor, otherwise the preprocessor's output.
|
|
241
|
+
width = _n_features_in(model)
|
|
242
|
+
preprocessor = getattr(model, "_preprocessor", None)
|
|
243
|
+
if preprocessor is not None:
|
|
244
|
+
try:
|
|
245
|
+
width = len(preprocessor.get_feature_names_out())
|
|
246
|
+
except Exception as e:
|
|
247
|
+
raise DeserializationError(
|
|
248
|
+
f"Can't determine the output width of {type(model).__name__}._preprocessor "
|
|
249
|
+
f"({type(e).__name__}: {e}); {_CORRUPT}."
|
|
250
|
+
) from e
|
|
251
|
+
|
|
252
|
+
is_categorical = None
|
|
253
|
+
bin_mapper = getattr(model, "_bin_mapper", None)
|
|
254
|
+
if (
|
|
255
|
+
bin_mapper is not None
|
|
256
|
+
and getattr(bin_mapper, "is_categorical_", None) is not None
|
|
257
|
+
):
|
|
258
|
+
is_categorical = np.asarray(bin_mapper.is_categorical_, dtype=bool)
|
|
259
|
+
|
|
260
|
+
for predictor in flat:
|
|
261
|
+
nodes = predictor.nodes
|
|
262
|
+
internal = nodes["is_leaf"] == 0
|
|
263
|
+
feature_idx = nodes["feature_idx"]
|
|
264
|
+
bad = internal & (feature_idx >= width)
|
|
265
|
+
if bad.any():
|
|
266
|
+
i = int(np.flatnonzero(bad)[0])
|
|
267
|
+
_fail(
|
|
268
|
+
f"{type(model).__name__} tree node {i} splits on feature "
|
|
269
|
+
f"{int(feature_idx[i])}, but the input has {width} features"
|
|
270
|
+
)
|
|
271
|
+
# A categorical split also reads `f_idx_map[feature_idx]`, built from
|
|
272
|
+
# `_bin_mapper.is_categorical_`, whose entries index the known-categories bitsets
|
|
273
|
+
# only for categorical features.
|
|
274
|
+
categorical = internal & (nodes["is_categorical"] != 0)
|
|
275
|
+
if categorical.any():
|
|
276
|
+
features = feature_idx[categorical]
|
|
277
|
+
if (
|
|
278
|
+
is_categorical is None
|
|
279
|
+
or (features >= is_categorical.shape[0]).any()
|
|
280
|
+
or not is_categorical[features].all()
|
|
281
|
+
):
|
|
282
|
+
_fail(
|
|
283
|
+
f"{type(model).__name__} has a categorical split on a feature its bin "
|
|
284
|
+
f"mapper doesn't mark as categorical"
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _validate_ensemble(model: BaseEnsemble) -> None:
|
|
289
|
+
estimators = getattr(model, "estimators_", None)
|
|
290
|
+
if estimators is None:
|
|
291
|
+
return
|
|
292
|
+
flat = list(np.asarray(estimators, dtype=object).ravel())
|
|
293
|
+
if not any(isinstance(getattr(e, "tree_", None), Tree) for e in flat):
|
|
294
|
+
return
|
|
295
|
+
width = _n_features_in(model)
|
|
296
|
+
|
|
297
|
+
if isinstance(model, IsolationForest):
|
|
298
|
+
# Each tree sees X[:, features], or all of X when _max_features equals X's width.
|
|
299
|
+
max_features = _as_int(
|
|
300
|
+
getattr(model, "_max_features", None), "IsolationForest._max_features"
|
|
301
|
+
)
|
|
302
|
+
if not 1 <= max_features <= width:
|
|
303
|
+
_fail(
|
|
304
|
+
f"IsolationForest._max_features is {max_features}, must be in [1, {width}]"
|
|
305
|
+
)
|
|
306
|
+
for est in flat:
|
|
307
|
+
if _sub_estimator_width(est, model) != max_features:
|
|
308
|
+
_fail(
|
|
309
|
+
f"IsolationForest has a tree with {getattr(est, 'n_features_in_', None)} "
|
|
310
|
+
f"features, but _max_features is {max_features}"
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
if isinstance(model, BaseBagging):
|
|
314
|
+
features_list = getattr(model, "estimators_features_", None)
|
|
315
|
+
for est, features in zip(flat, [] if features_list is None else features_list):
|
|
316
|
+
features = np.asarray(features)
|
|
317
|
+
if features.ndim != 1 or not np.issubdtype(features.dtype, np.integer):
|
|
318
|
+
_fail(
|
|
319
|
+
f"{type(model).__name__}.estimators_features_ must be 1-D int arrays"
|
|
320
|
+
)
|
|
321
|
+
if ((features < 0) | (features >= width)).any():
|
|
322
|
+
_fail(
|
|
323
|
+
f"{type(model).__name__}.estimators_features_ indexes features outside "
|
|
324
|
+
f"[0, {width})"
|
|
325
|
+
)
|
|
326
|
+
sub_width = _sub_estimator_width(est, model)
|
|
327
|
+
if sub_width is not None and sub_width != features.shape[0]:
|
|
328
|
+
_fail(
|
|
329
|
+
f"{type(model).__name__} has a sub-estimator with {sub_width} features "
|
|
330
|
+
f"trained on {features.shape[0]} selected features"
|
|
331
|
+
)
|
|
332
|
+
elif isinstance(model, (BaseForest, BaseGradientBoosting)):
|
|
333
|
+
# These validate X against their own n_features_in_ and call the trees with
|
|
334
|
+
# check_input=False (or read tree_ directly, in gradient boosting's predict_stages).
|
|
335
|
+
for est in flat:
|
|
336
|
+
sub_width = _sub_estimator_width(est, model)
|
|
337
|
+
if sub_width != width:
|
|
338
|
+
_fail(
|
|
339
|
+
f"{type(model).__name__} has {width} input features, but one of its "
|
|
340
|
+
f"trees has {sub_width}"
|
|
341
|
+
)
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def validate_feature_widths(model: Any) -> None:
|
|
345
|
+
"""
|
|
346
|
+
After an estimator's attributes are all set: every split feature must be a column of the
|
|
347
|
+
`X` scikit-learn will pass the tree. Sub-estimators are loaded (and checked) before their
|
|
348
|
+
ensemble, so each level only checks its own link.
|
|
349
|
+
"""
|
|
350
|
+
tree = getattr(model, "tree_", None)
|
|
351
|
+
if isinstance(tree, Tree):
|
|
352
|
+
width = _n_features_in(model)
|
|
353
|
+
if tree.n_features != width:
|
|
354
|
+
_fail(
|
|
355
|
+
f"{type(model).__name__} has {width} input features, but its tree has "
|
|
356
|
+
f"{tree.n_features}"
|
|
357
|
+
)
|
|
358
|
+
if isinstance(
|
|
359
|
+
model, (HistGradientBoostingClassifier, HistGradientBoostingRegressor)
|
|
360
|
+
):
|
|
361
|
+
_validate_hist_gradient_boosting(model)
|
|
362
|
+
if isinstance(model, BaseEnsemble):
|
|
363
|
+
_validate_ensemble(model)
|
|
@@ -75,6 +75,14 @@ from sklearn.neighbors._base import NeighborsBase
|
|
|
75
75
|
from sklearn.model_selection._search import BaseSearchCV
|
|
76
76
|
|
|
77
77
|
from openmodels.exceptions import DeserializationError, UnsupportedEstimatorError
|
|
78
|
+
from openmodels.serializers.sklearn._state_validation import validate_fitted_state
|
|
79
|
+
from openmodels.serializers.sklearn._tree_validation import (
|
|
80
|
+
validate_feature_widths,
|
|
81
|
+
validate_tree,
|
|
82
|
+
validate_tree_header,
|
|
83
|
+
validate_tree_node_count,
|
|
84
|
+
validate_tree_predictor,
|
|
85
|
+
)
|
|
78
86
|
from openmodels.protocols import ModelSerializer
|
|
79
87
|
from openmodels.serializers.base import (
|
|
80
88
|
NumpySerializerMixin,
|
|
@@ -932,7 +940,7 @@ class SklearnSerializer(
|
|
|
932
940
|
"center_dtype": str(center.dtype),
|
|
933
941
|
"indices": self.convert_to_serializable(indices),
|
|
934
942
|
"indices_dtype": str(indices.dtype),
|
|
935
|
-
"score": tree.score,
|
|
943
|
+
"score": self.convert_to_serializable(tree.score),
|
|
936
944
|
"label": getattr(tree, "label", None),
|
|
937
945
|
"left": self._serialize_bisecting_tree(tree.left) if tree.left else None,
|
|
938
946
|
"right": self._serialize_bisecting_tree(tree.right) if tree.right else None,
|
|
@@ -1213,7 +1221,12 @@ class SklearnSerializer(
|
|
|
1213
1221
|
"""
|
|
1214
1222
|
Deserializes a dictionary representation of a tree back to a sklearn.tree._tree.Tree object.
|
|
1215
1223
|
|
|
1224
|
+
The node arrays are validated (see `_tree_validation`): scikit-learn walks them without
|
|
1225
|
+
bounds checks, so a crafted file could otherwise crash or hang `predict`.
|
|
1216
1226
|
"""
|
|
1227
|
+
validate_tree_header(
|
|
1228
|
+
tree_data["n_features"], tree_data["n_outputs"], tree_data["n_classes"]
|
|
1229
|
+
)
|
|
1217
1230
|
tree = Tree(
|
|
1218
1231
|
tree_data["n_features"],
|
|
1219
1232
|
np.array(tree_data["n_classes"], dtype=np.intp),
|
|
@@ -1228,13 +1241,17 @@ class SklearnSerializer(
|
|
|
1228
1241
|
tuple(field) for field in tree_data["nodes_dtype"] if field[0] != ""
|
|
1229
1242
|
]
|
|
1230
1243
|
nodes_dtype = np.dtype(nodes_dtype_descr)
|
|
1231
|
-
if isinstance(value, list) and isinstance(value[0], list):
|
|
1244
|
+
if isinstance(value, list) and value and isinstance(value[0], list):
|
|
1232
1245
|
value = [tuple(row) for row in value]
|
|
1233
1246
|
state["nodes"] = np.array(value, dtype=nodes_dtype)
|
|
1234
1247
|
else:
|
|
1235
1248
|
state[key] = np.array(value)
|
|
1236
1249
|
|
|
1250
|
+
if "nodes" not in state:
|
|
1251
|
+
raise DeserializationError("Tree state has no nodes.")
|
|
1252
|
+
validate_tree_node_count(state, state["nodes"])
|
|
1237
1253
|
tree.__setstate__(state)
|
|
1254
|
+
validate_tree(tree)
|
|
1238
1255
|
return tree
|
|
1239
1256
|
|
|
1240
1257
|
def _serialize_tree_predictor(self, predictor: TreePredictor) -> Dict[str, Any]:
|
|
@@ -1285,11 +1302,13 @@ class SklearnSerializer(
|
|
|
1285
1302
|
binned_left_cat_bitsets = ensure_2d_uint32(data["binned_left_cat_bitsets"])
|
|
1286
1303
|
raw_left_cat_bitsets = ensure_2d_uint32(data["raw_left_cat_bitsets"])
|
|
1287
1304
|
|
|
1288
|
-
|
|
1305
|
+
predictor = TreePredictor(
|
|
1289
1306
|
nodes=nodes,
|
|
1290
1307
|
binned_left_cat_bitsets=binned_left_cat_bitsets,
|
|
1291
1308
|
raw_left_cat_bitsets=raw_left_cat_bitsets,
|
|
1292
1309
|
)
|
|
1310
|
+
validate_tree_predictor(predictor)
|
|
1311
|
+
return predictor
|
|
1293
1312
|
|
|
1294
1313
|
def _serialize_loss(self, value: BaseLoss) -> Dict[str, Any]:
|
|
1295
1314
|
"""
|
|
@@ -1920,6 +1939,10 @@ class SklearnSerializer(
|
|
|
1920
1939
|
self._resolve_birch_leaf_links()
|
|
1921
1940
|
self._rebuild_neighbors_tree(model)
|
|
1922
1941
|
self._rebuild_kernel_density_tree(model)
|
|
1942
|
+
# Before anything below reads the loaded state (e.g. n_features_in_).
|
|
1943
|
+
validate_feature_widths(model)
|
|
1923
1944
|
self._rebuild_derived_attributes(model)
|
|
1945
|
+
# After the rebuild: the gradient boosting check runs the init step, which needs _loss.
|
|
1946
|
+
validate_fitted_state(model)
|
|
1924
1947
|
|
|
1925
1948
|
return model
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "openmodels"
|
|
3
|
-
version = "0.2.
|
|
3
|
+
version = "0.2.4"
|
|
4
4
|
description = "Export scikit-learn model files to JSON for sharing or deploying predictive models with peace of mind."
|
|
5
5
|
authors = [
|
|
6
6
|
{ name = "Alejandro Gutierrez", email = "a.gutierrez@g-npd.com" },
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|