proxyml-core 0.1.0__tar.gz → 0.2.1__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.
Files changed (27) hide show
  1. {proxyml_core-0.1.0 → proxyml_core-0.2.1}/PKG-INFO +1 -1
  2. {proxyml_core-0.1.0 → proxyml_core-0.2.1}/pyproject.toml +1 -1
  3. {proxyml_core-0.1.0 → proxyml_core-0.2.1}/src/proxyml_core/__init__.py +7 -0
  4. {proxyml_core-0.1.0 → proxyml_core-0.2.1}/src/proxyml_core/export.py +69 -0
  5. {proxyml_core-0.1.0 → proxyml_core-0.2.1}/src/proxyml_core/modeling/__init__.py +2 -0
  6. {proxyml_core-0.1.0 → proxyml_core-0.2.1}/src/proxyml_core/modeling/estimators.py +5 -0
  7. proxyml_core-0.2.1/src/proxyml_core/modeling/scoring.py +27 -0
  8. {proxyml_core-0.1.0 → proxyml_core-0.2.1}/src/proxyml_core.egg-info/PKG-INFO +1 -1
  9. {proxyml_core-0.1.0 → proxyml_core-0.2.1}/src/proxyml_core.egg-info/SOURCES.txt +2 -0
  10. {proxyml_core-0.1.0 → proxyml_core-0.2.1}/tests/test_export.py +93 -0
  11. {proxyml_core-0.1.0 → proxyml_core-0.2.1}/tests/test_modeling_estimators.py +26 -0
  12. proxyml_core-0.2.1/tests/test_modeling_scoring.py +37 -0
  13. {proxyml_core-0.1.0 → proxyml_core-0.2.1}/LICENSE +0 -0
  14. {proxyml_core-0.1.0 → proxyml_core-0.2.1}/README.md +0 -0
  15. {proxyml_core-0.1.0 → proxyml_core-0.2.1}/setup.cfg +0 -0
  16. {proxyml_core-0.1.0 → proxyml_core-0.2.1}/src/proxyml_core/_version.py +0 -0
  17. {proxyml_core-0.1.0 → proxyml_core-0.2.1}/src/proxyml_core/modeling/extract.py +0 -0
  18. {proxyml_core-0.1.0 → proxyml_core-0.2.1}/src/proxyml_core/modeling/preprocess.py +0 -0
  19. {proxyml_core-0.1.0 → proxyml_core-0.2.1}/src/proxyml_core/schema.py +0 -0
  20. {proxyml_core-0.1.0 → proxyml_core-0.2.1}/src/proxyml_core.egg-info/dependency_links.txt +0 -0
  21. {proxyml_core-0.1.0 → proxyml_core-0.2.1}/src/proxyml_core.egg-info/requires.txt +0 -0
  22. {proxyml_core-0.1.0 → proxyml_core-0.2.1}/src/proxyml_core.egg-info/top_level.txt +0 -0
  23. {proxyml_core-0.1.0 → proxyml_core-0.2.1}/tests/test_dependency_boundaries.py +0 -0
  24. {proxyml_core-0.1.0 → proxyml_core-0.2.1}/tests/test_export_version_contract.py +0 -0
  25. {proxyml_core-0.1.0 → proxyml_core-0.2.1}/tests/test_modeling_extract.py +0 -0
  26. {proxyml_core-0.1.0 → proxyml_core-0.2.1}/tests/test_modeling_preprocess.py +0 -0
  27. {proxyml_core-0.1.0 → proxyml_core-0.2.1}/tests/test_schema.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: proxyml-core
3
- Version: 0.1.0
3
+ Version: 0.2.1
4
4
  Summary: Shared schema types, export contract, and modeling code for proxyml and its backend.
5
5
  Author-email: ProxyML <contact@proxyml.ai>
6
6
  License: Apache License
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "proxyml-core"
3
- version = "0.1.0"
3
+ version = "0.2.1"
4
4
  description = "Shared schema types, export contract, and modeling code for proxyml and its backend."
5
5
  readme = "README.md"
6
6
  license = {file = "LICENSE"}
@@ -1,3 +1,5 @@
1
+ from importlib.metadata import version as _pkg_version
2
+
1
3
  from proxyml_core._version import (
2
4
  EXPORT_SCHEMA_VERSION,
3
5
  IncompatibleExportVersionError,
@@ -9,6 +11,7 @@ from proxyml_core.export import (
9
11
  PerClassCoefficients,
10
12
  PerClassIntercept,
11
13
  SurrogateExport,
14
+ feature_importances_from_export,
12
15
  predict_from_export,
13
16
  score_export,
14
17
  )
@@ -23,7 +26,10 @@ from proxyml_core.schema import (
23
26
  NumericOrdinalFeature,
24
27
  )
25
28
 
29
+ __version__ = _pkg_version("proxyml-core")
30
+
26
31
  __all__ = [
32
+ "__version__",
27
33
  "Feature",
28
34
  "FeatureSchema",
29
35
  "FeatureValidationError",
@@ -39,6 +45,7 @@ __all__ = [
39
45
  "ExportError",
40
46
  "score_export",
41
47
  "predict_from_export",
48
+ "feature_importances_from_export",
42
49
  "EXPORT_SCHEMA_VERSION",
43
50
  "IncompatibleExportVersionError",
44
51
  "check_compatible",
@@ -236,3 +236,72 @@ def predict_from_export(
236
236
  prob = 1.0 / (1.0 + math.exp(-score))
237
237
  classes = export.classes or ["0", "1"]
238
238
  return classes[1] if prob >= 0.5 else classes[0]
239
+
240
+
241
+ def _entry_importance(entry: FeatureExportEntry, class_index: int | None) -> tuple[float, float]:
242
+ """Return (coefficient, abs_coefficient) for one feature, one class (or the whole model if not multiclass).
243
+
244
+ Categorical (OHE) features collapse to mean(abs(category_coefficients)) — sign
245
+ isn't meaningful across one-hot columns, so ``coefficient`` and ``abs_coefficient``
246
+ are the same value. Other feature types keep the signed coefficient.
247
+ """
248
+ if entry.type == "categorical":
249
+ coefs = (
250
+ entry.per_class_coefficients[class_index].category_coefficients
251
+ if class_index is not None
252
+ else entry.category_coefficients
253
+ ) or []
254
+ mean_abs = sum(abs(c) for c in coefs) / len(coefs) if coefs else 0.0
255
+ return mean_abs, mean_abs
256
+ coef = (
257
+ entry.per_class_coefficients[class_index].coefficient
258
+ if class_index is not None
259
+ else entry.coefficient
260
+ ) or 0.0
261
+ return coef, abs(coef)
262
+
263
+
264
+ def feature_importances_from_export(export: SurrogateExport) -> dict[str, Any]:
265
+ """Compute per-feature importances directly from a ``SurrogateExport`` — pure arithmetic,
266
+ no fitted sklearn model needed. Lets a report render challenger importances without
267
+ ever loading a live ``Pipeline``, unlike a server-trained surrogate's report path.
268
+
269
+ Mirrors the collapsing/aggregation rules a live-model extraction would use: OHE
270
+ categorical coefficients collapse via mean(abs(...)); multiclass features aggregate
271
+ mean(abs(...)) across per-class coefficients for the top-level list.
272
+
273
+ Returns ``{"feature_importances": [{"feature","coefficient","abs_coefficient"}, ...],
274
+ "per_class_importances": [{"class_label","importances":[...]}, ...] | None}``,
275
+ each list sorted by ``abs_coefficient`` descending.
276
+ """
277
+ is_multiclass = export.per_class_intercepts is not None
278
+
279
+ if not is_multiclass:
280
+ rows = []
281
+ for entry in export.features:
282
+ coef, abs_coef = _entry_importance(entry, None)
283
+ rows.append({"feature": entry.name, "coefficient": coef, "abs_coefficient": abs_coef})
284
+ rows.sort(key=lambda e: -e["abs_coefficient"])
285
+ return {"feature_importances": rows, "per_class_importances": None}
286
+
287
+ per_class = []
288
+ for i, pci in enumerate(export.per_class_intercepts):
289
+ rows = []
290
+ for entry in export.features:
291
+ coef, abs_coef = _entry_importance(entry, i)
292
+ rows.append({"feature": entry.name, "coefficient": coef, "abs_coefficient": abs_coef})
293
+ rows.sort(key=lambda e: -e["abs_coefficient"])
294
+ per_class.append({"class_label": pci.class_label, "importances": rows})
295
+
296
+ feat_abs: dict[str, list[float]] = {}
297
+ for cp in per_class:
298
+ for entry in cp["importances"]:
299
+ feat_abs.setdefault(entry["feature"], []).append(entry["abs_coefficient"])
300
+ feature_importances = sorted(
301
+ (
302
+ {"feature": f, "coefficient": sum(vals) / len(vals), "abs_coefficient": sum(vals) / len(vals)}
303
+ for f, vals in feat_abs.items()
304
+ ),
305
+ key=lambda e: -e["abs_coefficient"],
306
+ )
307
+ return {"feature_importances": feature_importances, "per_class_importances": per_class}
@@ -8,6 +8,7 @@ from proxyml_core.modeling.estimators import (
8
8
  )
9
9
  from proxyml_core.modeling.extract import extract_export_data
10
10
  from proxyml_core.modeling.preprocess import build_preprocessor
11
+ from proxyml_core.modeling.scoring import score_predictions
11
12
 
12
13
  __all__ = [
13
14
  "build_preprocessor",
@@ -18,4 +19,5 @@ __all__ = [
18
19
  "extract_hyperparameters",
19
20
  "to_json_safe",
20
21
  "extract_export_data",
22
+ "score_predictions",
21
23
  ]
@@ -47,6 +47,10 @@ def binarize_if_probabilities(predictions: np.ndarray) -> np.ndarray:
47
47
  if predictions.dtype.kind not in "iuf": # not int/uint/float — already discrete labels
48
48
  return predictions
49
49
  as_float = predictions.astype(float)
50
+ if not np.all(np.isfinite(as_float)):
51
+ # Casting NaN/inf to int is undefined — silently mis-binarizes to 0
52
+ # instead of raising, so reject it explicitly instead.
53
+ raise ValueError("predictions must not contain NaN or infinite values")
50
54
  if np.all(as_float == as_float.astype(int)):
51
55
  return predictions
52
56
  return (as_float >= 0.5).astype(int)
@@ -60,6 +64,7 @@ def get_default_classifier() -> BaseEstimator:
60
64
  max_iter=500,
61
65
  cv=5,
62
66
  n_jobs=-1,
67
+ scoring="accuracy",
63
68
  use_legacy_attributes=False,
64
69
  )
65
70
 
@@ -0,0 +1,27 @@
1
+ """Score predictions against labels. Requires ``proxyml-core[modeling]``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal
6
+
7
+ import numpy as np
8
+ from sklearn.metrics import f1_score, r2_score
9
+
10
+
11
+ def score_predictions(
12
+ y_true: np.ndarray, y_pred: np.ndarray, *, task: Literal["classification", "regression"]
13
+ ) -> dict[str, float]:
14
+ """Score predictions against ground truth with a fixed, reproducible metric set.
15
+
16
+ Classification returns weighted F1 + accuracy; regression returns R².
17
+ Shared by ``train_challenger()`` (scoring its own held-out split) and
18
+ ``score_champion()`` (scoring a champion's predictions against the same
19
+ real labels), so both sides of a champion-vs-challenger comparison are
20
+ computed with identical code.
21
+ """
22
+ if task == "classification":
23
+ return {
24
+ "f1": float(f1_score(y_true, y_pred, average="weighted", zero_division=0)),
25
+ "accuracy": float((np.asarray(y_true) == np.asarray(y_pred)).mean()),
26
+ }
27
+ return {"r2": float(r2_score(y_true, y_pred))}
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: proxyml-core
3
- Version: 0.1.0
3
+ Version: 0.2.1
4
4
  Summary: Shared schema types, export contract, and modeling code for proxyml and its backend.
5
5
  Author-email: ProxyML <contact@proxyml.ai>
6
6
  License: Apache License
@@ -14,10 +14,12 @@ src/proxyml_core/modeling/__init__.py
14
14
  src/proxyml_core/modeling/estimators.py
15
15
  src/proxyml_core/modeling/extract.py
16
16
  src/proxyml_core/modeling/preprocess.py
17
+ src/proxyml_core/modeling/scoring.py
17
18
  tests/test_dependency_boundaries.py
18
19
  tests/test_export.py
19
20
  tests/test_export_version_contract.py
20
21
  tests/test_modeling_estimators.py
21
22
  tests/test_modeling_extract.py
22
23
  tests/test_modeling_preprocess.py
24
+ tests/test_modeling_scoring.py
23
25
  tests/test_schema.py
@@ -10,6 +10,7 @@ from proxyml_core.export import (
10
10
  PerClassCoefficients,
11
11
  PerClassIntercept,
12
12
  SurrogateExport,
13
+ feature_importances_from_export,
13
14
  predict_from_export,
14
15
  score_export,
15
16
  )
@@ -158,3 +159,95 @@ def test_from_dict_accepts_older_version():
158
159
  d = export.to_dict()
159
160
  d["export_schema_version"] = EXPORT_SCHEMA_VERSION # same/older is fine
160
161
  SurrogateExport.from_dict(d) # should not raise
162
+
163
+
164
+ def test_feature_importances_from_export_binary():
165
+ export = _regression_export()
166
+ result = feature_importances_from_export(export)
167
+ assert result["per_class_importances"] is None
168
+ importances = {e["feature"]: e for e in result["feature_importances"]}
169
+ # continuous: signed coefficient preserved
170
+ assert importances["x"]["coefficient"] == pytest.approx(3.0)
171
+ assert importances["x"]["abs_coefficient"] == pytest.approx(3.0)
172
+ # categorical (OHE): mean(abs(category_coefficients)) -> mean(0.5, 0.5) = 0.5
173
+ assert importances["c"]["coefficient"] == pytest.approx(0.5)
174
+ assert importances["c"]["abs_coefficient"] == pytest.approx(0.5)
175
+ # sorted by abs_coefficient descending
176
+ assert [e["feature"] for e in result["feature_importances"]] == ["x", "c"]
177
+
178
+
179
+ def test_feature_importances_from_export_negative_coefficient_stays_signed():
180
+ export = SurrogateExport(
181
+ task="regression",
182
+ intercept=0.0,
183
+ features=[
184
+ FeatureExportEntry(name="x", type="continuous", scaler_mean=0.0, scaler_scale=1.0, coefficient=-4.0)
185
+ ],
186
+ )
187
+ result = feature_importances_from_export(export)
188
+ entry = result["feature_importances"][0]
189
+ assert entry["coefficient"] == pytest.approx(-4.0)
190
+ assert entry["abs_coefficient"] == pytest.approx(4.0)
191
+
192
+
193
+ def test_feature_importances_from_export_multiclass():
194
+ export = SurrogateExport(
195
+ task="classification",
196
+ classes=["a", "b"],
197
+ per_class_intercepts=[
198
+ PerClassIntercept(class_label="a", intercept=0.0),
199
+ PerClassIntercept(class_label="b", intercept=0.0),
200
+ ],
201
+ features=[
202
+ FeatureExportEntry(
203
+ name="x",
204
+ type="continuous",
205
+ scaler_mean=0.0,
206
+ scaler_scale=1.0,
207
+ per_class_coefficients=[
208
+ PerClassCoefficients(class_label="a", coefficient=2.0),
209
+ PerClassCoefficients(class_label="b", coefficient=-6.0),
210
+ ],
211
+ )
212
+ ],
213
+ )
214
+ result = feature_importances_from_export(export)
215
+ assert result["per_class_importances"] is not None
216
+ per_class = {cp["class_label"]: cp["importances"] for cp in result["per_class_importances"]}
217
+ assert per_class["a"][0]["coefficient"] == pytest.approx(2.0)
218
+ assert per_class["b"][0]["coefficient"] == pytest.approx(-6.0)
219
+ # top-level aggregate: mean(abs(2.0), abs(-6.0)) = 4.0
220
+ top = result["feature_importances"][0]
221
+ assert top["feature"] == "x"
222
+ assert top["coefficient"] == pytest.approx(4.0)
223
+ assert top["abs_coefficient"] == pytest.approx(4.0)
224
+
225
+
226
+ def test_feature_importances_from_export_multiclass_categorical_collapses_via_mean_abs():
227
+ export = SurrogateExport(
228
+ task="classification",
229
+ classes=["a", "b"],
230
+ per_class_intercepts=[
231
+ PerClassIntercept(class_label="a", intercept=0.0),
232
+ PerClassIntercept(class_label="b", intercept=0.0),
233
+ ],
234
+ features=[
235
+ FeatureExportEntry(
236
+ name="c",
237
+ type="categorical",
238
+ ohe_categories=["x", "y"],
239
+ per_class_coefficients=[
240
+ PerClassCoefficients(class_label="a", category_coefficients=[1.0, -3.0]),
241
+ PerClassCoefficients(class_label="b", category_coefficients=[0.0, 0.0]),
242
+ ],
243
+ )
244
+ ],
245
+ )
246
+ result = feature_importances_from_export(export)
247
+ per_class = {cp["class_label"]: cp["importances"] for cp in result["per_class_importances"]}
248
+ # class "a": mean(abs(1.0), abs(-3.0)) = 2.0
249
+ assert per_class["a"][0]["coefficient"] == pytest.approx(2.0)
250
+ assert per_class["a"][0]["abs_coefficient"] == pytest.approx(2.0)
251
+ assert per_class["b"][0]["coefficient"] == pytest.approx(0.0)
252
+ # top-level: mean(2.0, 0.0) = 1.0
253
+ assert result["feature_importances"][0]["coefficient"] == pytest.approx(1.0)
@@ -1,4 +1,7 @@
1
+ import warnings
2
+
1
3
  import numpy as np
4
+ import pytest
2
5
 
3
6
  from proxyml_core.modeling.estimators import (
4
7
  binarize_if_probabilities,
@@ -40,6 +43,18 @@ def test_binarize_if_probabilities_passes_through_object_labels():
40
43
  assert list(out) == ["yes", "no"]
41
44
 
42
45
 
46
+ def test_binarize_if_probabilities_rejects_nan():
47
+ # Casting NaN to int is undefined and previously silently mis-binarized
48
+ # to 0 instead of raising — must fail loudly instead.
49
+ with pytest.raises(ValueError, match="NaN or infinite"):
50
+ binarize_if_probabilities(np.array([0.1, 0.6, np.nan, 0.5]))
51
+
52
+
53
+ def test_binarize_if_probabilities_rejects_inf():
54
+ with pytest.raises(ValueError, match="NaN or infinite"):
55
+ binarize_if_probabilities(np.array([0.1, 0.6, np.inf, 0.5]))
56
+
57
+
43
58
  def test_to_json_safe_handles_numpy_types():
44
59
  assert to_json_safe(np.array([1, 2, 3])) == [1, 2, 3]
45
60
  assert to_json_safe(np.float64(1.5)) == 1.5
@@ -57,6 +72,17 @@ def test_extract_hyperparameters_includes_cv_selected_values():
57
72
  assert isinstance(params["alpha_"], float)
58
73
 
59
74
 
75
+ def test_get_default_classifier_fits_without_sklearn_deprecation_warnings():
76
+ # scoring="accuracy" and use_legacy_attributes=False pin today's sklearn
77
+ # defaults explicitly, so upgrading sklearn can't silently change fit
78
+ # behavior and users don't see FutureWarning noise on every fit.
79
+ X = np.random.RandomState(0).normal(size=(50, 3))
80
+ y = (X[:, 0] > 0).astype(int)
81
+ with warnings.catch_warnings():
82
+ warnings.simplefilter("error", FutureWarning)
83
+ get_default_classifier().fit(X, y)
84
+
85
+
60
86
  def test_get_default_classifier_and_regressor_are_fittable():
61
87
  X = np.random.RandomState(0).normal(size=(50, 3))
62
88
  y_class = (X[:, 0] > 0).astype(int)
@@ -0,0 +1,37 @@
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from proxyml_core.modeling.scoring import score_predictions
5
+
6
+
7
+ def test_score_predictions_classification_shape():
8
+ y_true = np.array([0, 1, 0, 1, 1])
9
+ y_pred = np.array([0, 1, 0, 0, 1])
10
+ result = score_predictions(y_true, y_pred, task="classification")
11
+ assert set(result) == {"f1", "accuracy"}
12
+ assert result["accuracy"] == pytest.approx(4 / 5)
13
+
14
+
15
+ def test_score_predictions_classification_perfect_score():
16
+ y_true = np.array([0, 1, 1, 0])
17
+ y_pred = np.array([0, 1, 1, 0])
18
+ result = score_predictions(y_true, y_pred, task="classification")
19
+ assert result["f1"] == pytest.approx(1.0)
20
+ assert result["accuracy"] == pytest.approx(1.0)
21
+
22
+
23
+ def test_score_predictions_regression_shape():
24
+ y_true = np.array([1.0, 2.0, 3.0, 4.0])
25
+ y_pred = np.array([1.0, 2.0, 3.0, 4.0])
26
+ result = score_predictions(y_true, y_pred, task="regression")
27
+ assert set(result) == {"r2"}
28
+ assert result["r2"] == pytest.approx(1.0)
29
+
30
+
31
+ def test_score_predictions_classification_handles_zero_division():
32
+ # All one class, predictions also all one class -> f1_score's zero_division=0
33
+ # guards against a warning/exception when a class is never predicted.
34
+ y_true = np.array([1, 1, 1, 1])
35
+ y_pred = np.array([1, 1, 1, 1])
36
+ result = score_predictions(y_true, y_pred, task="classification")
37
+ assert result["accuracy"] == pytest.approx(1.0)
File without changes
File without changes
File without changes