fprcal 0.1.0__py3-none-any.whl

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.
fprcal/__init__.py ADDED
@@ -0,0 +1,28 @@
1
+ # Copyright 2026 Cisco Systems, Inc. and its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ """FPR-based model calibration using sklearn IsotonicRegression."""
18
+
19
+ from importlib.metadata import version as _distribution_version
20
+
21
+ from fprcal.calibration import (
22
+ fit_calibration_pipeline,
23
+ fpr_to_calibrated,
24
+ )
25
+
26
+ __all__ = ["__version__", "fit_calibration_pipeline", "fpr_to_calibrated"]
27
+
28
+ __version__ = _distribution_version("fprcal")
fprcal/calibration.py ADDED
@@ -0,0 +1,269 @@
1
+ # Copyright 2026 Cisco Systems, Inc. and its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ """FPR-based calibration using sklearn Pipeline.
18
+
19
+ Two-step fitting, single-step inference:
20
+ 1. Fit temporary IsotonicRegression: FPR -> score (discarded after fitting).
21
+ 2. Fit final IsotonicRegression: score -> calibrated (kept in pipeline).
22
+
23
+ The final pipeline stores about ``n_knots`` (score, calibrated) knots regardless
24
+ of training set size.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from typing import Literal
30
+
31
+ import numpy as np
32
+ from numpy.typing import NDArray
33
+ from sklearn.isotonic import IsotonicRegression
34
+ from sklearn.pipeline import Pipeline
35
+ from sklearn.preprocessing import MinMaxScaler
36
+
37
+ SCORE_MAX: float = 0.99
38
+ PlottingPosition = Literal["filliben", "mean"]
39
+
40
+ # FPR-to-calibrated mapping knots (piecewise linear in log10(FPR) space).
41
+ _FPR_CAL_KNOTS: list[tuple[int, float]] = [
42
+ (0, 0.0), # 100% FPR -> cal=0.0
43
+ (-1, 0.1), # 10% FPR -> cal=0.1
44
+ (-2, 0.3), # 1% FPR -> cal=0.3
45
+ (-3, 0.5), # 0.1% FPR -> cal=0.5
46
+ (-4, 0.7), # 0.01% FPR -> cal=0.7
47
+ (-5, 0.85), # 0.001% FPR -> cal=0.85
48
+ (-6, 0.95), # 0.0001% FPR -> cal=0.95
49
+ (-10, 0.99), # ~0% FPR -> cal=0.99
50
+ ]
51
+
52
+ _sorted_idx = np.argsort([k[0] for k in _FPR_CAL_KNOTS])
53
+ _LOG_FPR_KNOTS: NDArray[np.float64] = np.array(
54
+ [_FPR_CAL_KNOTS[i][0] for i in _sorted_idx], dtype=np.float64
55
+ )
56
+ _CAL_KNOTS: NDArray[np.float64] = np.array(
57
+ [_FPR_CAL_KNOTS[i][1] for i in _sorted_idx], dtype=np.float64
58
+ )
59
+ _FPR_KNOTS: NDArray[np.float64] = 10.0**_LOG_FPR_KNOTS
60
+
61
+
62
+ def fpr_to_calibrated(fpr: NDArray[np.float64] | float) -> NDArray[np.float64]:
63
+ """Map FPR values to calibrated [0, 1] scores via the fixed log-scale anchors.
64
+
65
+ Parameters
66
+ ----------
67
+ fpr : array-like or float
68
+ False positive rate in ``[0, 1]``. Values outside this range are clipped
69
+ to ``[1e-10, 1.0]`` before interpolation.
70
+
71
+ Returns
72
+ -------
73
+ ndarray
74
+ Calibrated scores in ``[0, 0.99]``. The anchors are: FPR=1 -> 0.0,
75
+ FPR=0.1 -> 0.1, FPR=0.01 -> 0.3, FPR=0.001 -> 0.5, FPR=0.0001 -> 0.7,
76
+ FPR=1e-5 -> 0.85, FPR=1e-6 -> 0.95, FPR=1e-10 -> 0.99.
77
+ """
78
+ fpr_arr = np.asarray(fpr, dtype=np.float64)
79
+ log_fpr = np.log10(np.clip(fpr_arr, 1e-10, 1.0))
80
+ return np.interp(log_fpr, _LOG_FPR_KNOTS, _CAL_KNOTS)
81
+
82
+
83
+ def _sample_fpr_values(n_total: int = 1000) -> NDArray[np.float64]:
84
+ """Sample FPR values including all explicit knots, with log-spaced fill between.
85
+
86
+ Returns FPR values (not log) sorted in increasing order. Covers the full
87
+ log-anchor contract range from 1e-10 to 1.0 so the second isotonic has
88
+ knots across every decade the contract defines.
89
+ """
90
+ # Explicit knot FPRs covering every decade the contract defines.
91
+ explicit_fprs = [1e-10, 1e-9, 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1.0]
92
+
93
+ n_explicit = len(explicit_fprs)
94
+ n_fill = n_total - n_explicit
95
+ n_gaps = n_explicit - 1
96
+ points_per_gap = n_fill // n_gaps
97
+
98
+ all_fprs: list[float] = []
99
+ for i in range(n_gaps):
100
+ fpr_lo = explicit_fprs[i]
101
+ fpr_hi = explicit_fprs[i + 1]
102
+ fill = np.logspace(np.log10(fpr_lo), np.log10(fpr_hi), points_per_gap + 2)[1:-1]
103
+ all_fprs.append(fpr_lo)
104
+ all_fprs.extend(fill)
105
+ all_fprs.append(explicit_fprs[-1])
106
+
107
+ return np.array(sorted(set(all_fprs)), dtype=np.float64)
108
+
109
+
110
+ def _extrapolate_score(fpr: float, fpr1: float, score1: float, fpr2: float, score2: float) -> float:
111
+ """Linear extrapolation from two (FPR, score) points."""
112
+ slope = (score2 - score1) / (fpr2 - fpr1)
113
+ return score1 + slope * (fpr - fpr1)
114
+
115
+
116
+ def _plotting_positions(n: int, method: PlottingPosition) -> NDArray[np.float64]:
117
+ """Return upper-tail FPR plotting positions for sorted scores.
118
+
119
+ The returned array aligns with scores sorted in ascending order. Entry ``i``
120
+ is the plotting-position FPR for ``sorted_scores[i]`` under the inclusive
121
+ threshold convention ``score >= threshold``.
122
+ """
123
+ if n < 2:
124
+ raise ValueError("At least two benign scores are required for calibration")
125
+
126
+ rank_from_top = n - np.arange(n, dtype=np.float64)
127
+
128
+ if method == "mean":
129
+ return rank_from_top / (n + 1)
130
+
131
+ if method == "filliben":
132
+ positions = (rank_from_top - 0.3175) / (n + 0.365)
133
+ endpoint = 0.5 ** (1.0 / n)
134
+ positions[0] = endpoint
135
+ positions[-1] = 1.0 - endpoint
136
+ return positions
137
+
138
+ raise ValueError("plotting_position must be 'filliben' or 'mean'")
139
+
140
+
141
+ def fit_calibration_pipeline(
142
+ benign_scores: NDArray[np.float64],
143
+ n_knots: int = 10000,
144
+ *,
145
+ keep_debug: bool = False,
146
+ plotting_position: PlottingPosition = "filliben",
147
+ ) -> Pipeline:
148
+ """Fit a whole-curve FPR calibration pipeline from benign scores.
149
+
150
+ The pipeline maps raw detector scores in ``[0, 1]`` to calibrated values in
151
+ ``[0, 0.99]``, where every calibrated value has a stable FPR meaning
152
+ (``0.5 = 0.1% FPR``, ``0.7 = 0.01%``, and so on).
153
+
154
+ Two-step fitting:
155
+
156
+ 1. Fit a temporary ``IsotonicRegression`` on the benign empirical CDF to get
157
+ ``FPR -> score``.
158
+ 2. Sample ~``n_knots`` FPR values on a log-spaced base grid, add the first
159
+ spline's fitted edge FPRs, and compute ``(score, calibrated)`` pairs.
160
+ 3. Fit the final ``IsotonicRegression`` on those pairs as ``score -> calibrated``.
161
+
162
+ Parameters
163
+ ----------
164
+ benign_scores : ndarray
165
+ Scores from benign/negative samples, in ``[0, 1]``.
166
+ n_knots : int, optional
167
+ Approximate number of knots to store in the final pipeline. Default 10000.
168
+ keep_debug : bool, optional
169
+ When True, attach the first-pass ``fpr_to_score_`` isotonic and the
170
+ sampled FPR/score arrays to the returned Pipeline for plotting. These
171
+ attributes serialize under ``joblib.dump`` and inflate artifact size
172
+ with ``len(benign_scores)``, so the default is False for production use.
173
+ plotting_position : {"filliben", "mean"}, optional
174
+ FPR coordinate assigned to each sorted benign threshold in the temporary
175
+ FPR-to-score spline. ``"filliben"`` uses median-centered order-statistic
176
+ plotting positions and is the default. ``"mean"`` uses the mean-centered
177
+ ``k/(n+1)`` positions.
178
+
179
+ Returns
180
+ -------
181
+ sklearn.pipeline.Pipeline
182
+ Fitted sklearn Pipeline with ``MinMaxScaler`` and ``IsotonicRegression``
183
+ stages. Call ``pipeline.predict(scores.reshape(-1, 1))`` to calibrate.
184
+
185
+ Raises
186
+ ------
187
+ ValueError
188
+ If any benign score falls outside ``[0, 1]``.
189
+ """
190
+ benign_scores = np.asarray(benign_scores, dtype=np.float64).ravel()
191
+
192
+ if np.any(benign_scores < 0) or np.any(benign_scores > 1):
193
+ raise ValueError(
194
+ f"Scores must be in [0, 1], got [{benign_scores.min()}, {benign_scores.max()}]"
195
+ )
196
+
197
+ # Fit the rescaler on the input domain [0, 1] rather than on the
198
+ # observed calibration range. This makes the rescaler a pure
199
+ # ``raw * SCORE_MAX`` map, so inference scores above calib.max (but
200
+ # still in [0, 1]) land inside the isotonic's training range rather
201
+ # than clipping to calibrated 1.0. Isotonic is invariant to monotone
202
+ # rescale, so calibrated outputs for scores in [0, calib.max] are
203
+ # unchanged; scores in (calib.max, 1.0] now get honest calibrated
204
+ # values instead of the "flag nothing" terminal.
205
+ rescaler = MinMaxScaler(feature_range=(0, SCORE_MAX))
206
+ rescaler.fit(np.array([[0.0], [1.0]]))
207
+ scores_scaled = rescaler.transform(benign_scores.reshape(-1, 1)).ravel()
208
+
209
+ # Empirical CDF: (FPR, score) pairs.
210
+ # Evaluation counts still use the inclusive convention
211
+ # FPR(threshold) = P(score >= threshold). The first spline maps ordered
212
+ # thresholds to population FPR coordinates, so it uses a plotting position
213
+ # for each rank.
214
+ sorted_scores = np.sort(scores_scaled)
215
+ n = len(sorted_scores)
216
+ fprs = _plotting_positions(n, plotting_position)
217
+
218
+ # Step 1: temporary IsotonicRegression (FPR -> score).
219
+ fpr_to_score = IsotonicRegression(increasing=False, out_of_bounds="clip")
220
+ fpr_to_score.fit(fprs, sorted_scores)
221
+
222
+ min_fpr = float(fprs[-1])
223
+ fpr1, fpr2 = fprs[-2], fprs[-1]
224
+ score1, score2 = sorted_scores[-2], sorted_scores[-1]
225
+
226
+ # Step 2: sample FPR values, compute (score, calibrated) pairs.
227
+ sampled_fprs = _sample_fpr_values(n_knots)
228
+ first_spline_edge_fprs = np.array([fprs[0], fpr1, fpr2], dtype=np.float64)
229
+ sampled_fprs = np.unique(np.concatenate((sampled_fprs, first_spline_edge_fprs)))
230
+
231
+ knot_scores: list[float] = []
232
+ knot_calibrated: list[float] = []
233
+
234
+ for fpr in sampled_fprs:
235
+ if fpr >= min_fpr:
236
+ score = float(fpr_to_score.predict([[fpr]])[0])
237
+ else:
238
+ score = _extrapolate_score(fpr, fpr1, score1, fpr2, score2)
239
+ score = float(np.clip(score, 0, SCORE_MAX))
240
+
241
+ log_fpr = np.log10(max(fpr, 1e-10))
242
+ calibrated = float(np.interp(log_fpr, _LOG_FPR_KNOTS, _CAL_KNOTS))
243
+
244
+ knot_scores.append(score)
245
+ knot_calibrated.append(calibrated)
246
+
247
+ knot_scores_arr = np.array(knot_scores, dtype=np.float64)
248
+ knot_calibrated_arr = np.array(knot_calibrated, dtype=np.float64)
249
+
250
+ # Boundary pairs for the final rescaled-score-to-calibrated-score fit.
251
+ # Valid raw inputs are rescaled to at most SCORE_MAX and do not reach x=1.0.
252
+ knot_scores_arr = np.append(knot_scores_arr, [SCORE_MAX, 1.0])
253
+ knot_calibrated_arr = np.append(knot_calibrated_arr, [0.99, 1.0])
254
+
255
+ # Step 3: final IsotonicRegression (score -> calibrated).
256
+ score_to_cal = IsotonicRegression(increasing=True, out_of_bounds="clip")
257
+ score_to_cal.fit(knot_scores_arr, knot_calibrated_arr)
258
+
259
+ pipeline = Pipeline([("rescale", rescaler), ("isotonic", score_to_cal)])
260
+ setattr(pipeline, "plotting_position_", plotting_position) # noqa: B010
261
+
262
+ if keep_debug:
263
+ # Debug artifacts for plotting; attached only when keep_debug=True so
264
+ # production pipelines serialize to a bounded size via joblib.dump.
265
+ setattr(pipeline, "fpr_to_score_", fpr_to_score) # noqa: B010
266
+ setattr(pipeline, "sampled_fprs_", sampled_fprs) # noqa: B010
267
+ setattr(pipeline, "sampled_scores_", knot_scores_arr[:-2]) # noqa: B010
268
+
269
+ return pipeline
@@ -0,0 +1,298 @@
1
+ Metadata-Version: 2.4
2
+ Name: fprcal
3
+ Version: 0.1.0
4
+ Summary: Stable low-FPR calibration for detection model scores across model releases.
5
+ Project-URL: Homepage, https://github.com/cisco-ai-defense/fpr-model-calibration
6
+ Project-URL: Repository, https://github.com/cisco-ai-defense/fpr-model-calibration
7
+ Project-URL: Issues, https://github.com/cisco-ai-defense/fpr-model-calibration/issues
8
+ Project-URL: Changelog, https://github.com/cisco-ai-defense/fpr-model-calibration/blob/main/CHANGELOG.md
9
+ Author-email: Konstantin Berlin <berlink@cisco.com>
10
+ License: Apache License
11
+ Version 2.0, January 2004
12
+ http://www.apache.org/licenses/
13
+
14
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
15
+
16
+ 1. Definitions.
17
+
18
+ "License" shall mean the terms and conditions for use, reproduction,
19
+ and distribution as defined by Sections 1 through 9 of this document.
20
+
21
+ "Licensor" shall mean the copyright owner or entity authorized by
22
+ the copyright owner that is granting the License.
23
+
24
+ "Legal Entity" shall mean the union of the acting entity and all
25
+ other entities that control, are controlled by, or are under common
26
+ control with that entity. For the purposes of this definition,
27
+ "control" means (i) the power, direct or indirect, to cause the
28
+ direction or management of such entity, whether by contract or
29
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
30
+ outstanding shares, or (iii) beneficial ownership of such entity.
31
+
32
+ "You" (or "Your") shall mean an individual or Legal Entity
33
+ exercising permissions granted by this License.
34
+
35
+ "Source" form shall mean the preferred form for making modifications,
36
+ including but not limited to software source code, documentation
37
+ source, and configuration files.
38
+
39
+ "Object" form shall mean any form resulting from mechanical
40
+ transformation or translation of a Source form, including but
41
+ not limited to compiled object code, generated documentation,
42
+ and conversions to other media types.
43
+
44
+ "Work" shall mean the work of authorship, whether in Source or
45
+ Object form, made available under the License, as indicated by a
46
+ copyright notice that is included in or attached to the work
47
+ (an example is provided in the Appendix below).
48
+
49
+ "Derivative Works" shall mean any work, whether in Source or Object
50
+ form, that is based on (or derived from) the Work and for which the
51
+ editorial revisions, annotations, elaborations, or other modifications
52
+ represent, as a whole, an original work of authorship. For the purposes
53
+ of this License, Derivative Works shall not include works that remain
54
+ separable from, or merely link (or bind by name) to the interfaces of,
55
+ the Work and Derivative Works thereof.
56
+
57
+ "Contribution" shall mean any work of authorship, including
58
+ the original version of the Work and any modifications or additions
59
+ to that Work or Derivative Works thereof, that is intentionally
60
+ submitted to Licensor for inclusion in the Work by the copyright owner
61
+ or by an individual or Legal Entity authorized to submit on behalf of
62
+ the copyright owner. For the purposes of this definition, "submitted"
63
+ means any form of electronic, verbal, or written communication sent
64
+ to the Licensor or its representatives, including but not limited to
65
+ communication on electronic mailing lists, source code control systems,
66
+ and issue tracking systems that are managed by, or on behalf of, the
67
+ Licensor for the purpose of discussing and improving the Work, but
68
+ excluding communication that is conspicuously marked or otherwise
69
+ designated in writing by the copyright owner as "Not a Contribution."
70
+
71
+ "Contributor" shall mean Licensor and any individual or Legal Entity
72
+ on behalf of whom a Contribution has been received by Licensor and
73
+ subsequently incorporated within the Work.
74
+
75
+ 2. Grant of Copyright License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ copyright license to reproduce, prepare Derivative Works of,
79
+ publicly display, publicly perform, sublicense, and distribute the
80
+ Work and such Derivative Works in Source or Object form.
81
+
82
+ 3. Grant of Patent License. Subject to the terms and conditions of
83
+ this License, each Contributor hereby grants to You a perpetual,
84
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
85
+ (except as stated in this section) patent license to make, have made,
86
+ use, offer to sell, sell, import, and otherwise transfer the Work,
87
+ where such license applies only to those patent claims licensable
88
+ by such Contributor that are necessarily infringed by their
89
+ Contribution(s) alone or by combination of their Contribution(s)
90
+ with the Work to which such Contribution(s) was submitted. If You
91
+ institute patent litigation against any entity (including a
92
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
93
+ or a Contribution incorporated within the Work constitutes direct
94
+ or contributory patent infringement, then any patent licenses
95
+ granted to You under this License for that Work shall terminate
96
+ as of the date such litigation is filed.
97
+
98
+ 4. Redistribution. You may reproduce and distribute copies of the
99
+ Work or Derivative Works thereof in any medium, with or without
100
+ modifications, and in Source or Object form, provided that You
101
+ meet the following conditions:
102
+
103
+ (a) You must give any other recipients of the Work or
104
+ Derivative Works a copy of this License; and
105
+
106
+ (b) You must cause any modified files to carry prominent notices
107
+ stating that You changed the files; and
108
+
109
+ (c) You must retain, in the Source form of any Derivative Works
110
+ that You distribute, all copyright, patent, trademark, and
111
+ attribution notices from the Source form of the Work,
112
+ excluding those notices that do not pertain to any part of
113
+ the Derivative Works; and
114
+
115
+ (d) If the Work includes a "NOTICE" text file as part of its
116
+ distribution, then any Derivative Works that You distribute must
117
+ include a readable copy of the attribution notices contained
118
+ within such NOTICE file, excluding those notices that do not
119
+ pertain to any part of the Derivative Works, in at least one
120
+ of the following places: within a NOTICE text file distributed
121
+ as part of the Derivative Works; within the Source form or
122
+ documentation, if provided along with the Derivative Works; or,
123
+ within a display generated by the Derivative Works, if and
124
+ wherever such third-party notices normally appear. The contents
125
+ of the NOTICE file are for informational purposes only and
126
+ do not modify the License. You may add Your own attribution
127
+ notices within Derivative Works that You distribute, alongside
128
+ or as an addendum to the NOTICE text from the Work, provided
129
+ that such additional attribution notices cannot be construed
130
+ as modifying the License.
131
+
132
+ You may add Your own copyright statement to Your modifications and
133
+ may provide additional or different license terms and conditions
134
+ for use, reproduction, or distribution of Your modifications, or
135
+ for any such Derivative Works as a whole, provided Your use,
136
+ reproduction, and distribution of the Work otherwise complies with
137
+ the conditions stated in this License.
138
+
139
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
140
+ any Contribution intentionally submitted for inclusion in the Work
141
+ by You to the Licensor shall be under the terms and conditions of
142
+ this License, without any additional terms or conditions.
143
+ Notwithstanding the above, nothing herein shall supersede or modify
144
+ the terms of any separate license agreement you may have executed
145
+ with Licensor regarding such Contributions.
146
+
147
+ 6. Trademarks. This License does not grant permission to use the trade
148
+ names, trademarks, service marks, or product names of the Licensor,
149
+ except as required for reasonable and customary use in describing the
150
+ origin of the Work and reproducing the content of the NOTICE file.
151
+
152
+ 7. Disclaimer of Warranty. Unless required by applicable law or
153
+ agreed to in writing, Licensor provides the Work (and each
154
+ Contributor provides its Contributions) on an "AS IS" BASIS,
155
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
156
+ implied, including, without limitation, any warranties or conditions
157
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
158
+ PARTICULAR PURPOSE. You are solely responsible for determining the
159
+ appropriateness of using or redistributing the Work and assume any
160
+ risks associated with Your exercise of permissions under this License.
161
+
162
+ 8. Limitation of Liability. In no event and under no legal theory,
163
+ whether in tort (including negligence), contract, or otherwise,
164
+ unless required by applicable law (such as deliberate and grossly
165
+ negligent acts) or agreed to in writing, shall any Contributor be
166
+ liable to You for damages, including any direct, indirect, special,
167
+ incidental, or consequential damages of any character arising as a
168
+ result of this License or out of the use or inability to use the
169
+ Work (including but not limited to damages for loss of goodwill,
170
+ work stoppage, computer failure or malfunction, or any and all
171
+ other commercial damages or losses), even if such Contributor
172
+ has been advised of the possibility of such damages.
173
+
174
+ 9. Accepting Warranty or Additional Liability. While redistributing
175
+ the Work or Derivative Works thereof, You may choose to offer,
176
+ and charge a fee for, acceptance of support, warranty, indemnity,
177
+ or other liability obligations and/or rights consistent with this
178
+ License. However, in accepting such obligations, You may act only
179
+ on Your own behalf and on Your sole responsibility, not on behalf
180
+ of any other Contributor, and only if You agree to indemnify,
181
+ defend, and hold each Contributor harmless for any liability
182
+ incurred by, or claims asserted against, such Contributor by reason
183
+ of your accepting any such warranty or additional liability.
184
+
185
+ END OF TERMS AND CONDITIONS
186
+
187
+ APPENDIX: How to apply the Apache License to your work.
188
+
189
+ To apply the Apache License to your work, attach the following
190
+ boilerplate notice, with the fields enclosed by brackets "[]"
191
+ replaced with your own identifying information. (Don't include
192
+ the brackets!) The text should be enclosed in the appropriate
193
+ comment syntax for the file format. We also recommend that a
194
+ file or class name and description of purpose be included on the
195
+ same "printed page" as the copyright notice for easier
196
+ identification within third-party archives.
197
+
198
+ Copyright [2025] [CISCO - AI DEFENSE]
199
+
200
+ Licensed under the Apache License, Version 2.0 (the "License");
201
+ you may not use this file except in compliance with the License.
202
+ You may obtain a copy of the License at
203
+
204
+ http://www.apache.org/licenses/LICENSE-2.0
205
+
206
+ Unless required by applicable law or agreed to in writing, software
207
+ distributed under the License is distributed on an "AS IS" BASIS,
208
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
209
+ See the License for the specific language governing permissions and
210
+ limitations under the License.
211
+ License-File: LICENSE
212
+ Keywords: calibration,detector,false-positive-rate,isotonic,ml,security
213
+ Classifier: Development Status :: 4 - Beta
214
+ Classifier: Intended Audience :: Developers
215
+ Classifier: Intended Audience :: Science/Research
216
+ Classifier: License :: OSI Approved :: Apache Software License
217
+ Classifier: Operating System :: OS Independent
218
+ Classifier: Programming Language :: Python :: 3
219
+ Classifier: Programming Language :: Python :: 3.12
220
+ Classifier: Programming Language :: Python :: 3.13
221
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
222
+ Classifier: Topic :: Security
223
+ Requires-Python: >=3.12
224
+ Requires-Dist: joblib>=1.4
225
+ Requires-Dist: numpy>=2.2
226
+ Requires-Dist: scikit-learn>=1.5
227
+ Provides-Extra: dev
228
+ Requires-Dist: matplotlib>=3.9; extra == 'dev'
229
+ Requires-Dist: pandas>=2.2; extra == 'dev'
230
+ Requires-Dist: pip-audit>=2.9; extra == 'dev'
231
+ Requires-Dist: pytest-cov>=6.0; extra == 'dev'
232
+ Requires-Dist: pytest>=8.3; extra == 'dev'
233
+ Requires-Dist: ruff>=0.6; extra == 'dev'
234
+ Requires-Dist: scipy>=1.13; extra == 'dev'
235
+ Requires-Dist: ty>=0.0.34; extra == 'dev'
236
+ Provides-Extra: examples
237
+ Requires-Dist: matplotlib>=3.9; extra == 'examples'
238
+ Requires-Dist: pandas>=2.2; extra == 'examples'
239
+ Requires-Dist: scipy>=1.13; extra == 'examples'
240
+ Description-Content-Type: text/markdown
241
+
242
+ # FPRCal
243
+
244
+ [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
245
+
246
+ Stable low-FPR calibration for detection model scores across model releases, with a fixed log-scale interpretability contract (`0.5 = 0.1% FPR`, `0.7 = 0.01%`, `0.85 = 0.001%`).
247
+
248
+ ## Why
249
+
250
+ Raw scores from ML detectors drift across model releases and are not comparable across detector categories. Downstream product rules break on every retrain. This package calibrates detector scores to FPR on benign traffic, then applies a fixed log-scale transform so every calibrated value has the same FPR meaning across model versions and detector categories.
251
+
252
+ ## Install
253
+
254
+ ```bash
255
+ python -m pip install fprcal
256
+ ```
257
+
258
+ Requires Python 3.12+, numpy, scikit-learn, joblib.
259
+
260
+ For an editable development install, use `python -m pip install -e ".[dev]"`.
261
+
262
+ ## Usage
263
+
264
+ ```python
265
+ from fprcal import fit_calibration_pipeline
266
+ import joblib
267
+
268
+ pipeline = fit_calibration_pipeline(benign_scores, n_knots=10000)
269
+ joblib.dump(pipeline, "calibration.pkl")
270
+
271
+ # In production:
272
+ pipeline = joblib.load("calibration.pkl")
273
+ calibrated = pipeline.predict(raw_scores.reshape(-1, 1))
274
+ ```
275
+
276
+ The first-pass FPR-to-threshold spline uses Filliben median-centered plotting
277
+ positions by default. Pass `plotting_position="mean"` to use the mean-centered
278
+ `k/(n+1)` positions instead.
279
+
280
+ ## Demo
281
+
282
+ Reproduce the evaluation figure on the Credit Card Fraud Detection dataset (OpenML, 284K rows, 0.172% positives):
283
+
284
+ ```bash
285
+ # One-time: download the data, train both detectors, save holdout scores
286
+ python examples/generate_credit_card_roc.py
287
+
288
+ # Fit on the calibration subset and evaluate its held-out complement
289
+ python examples/calibration_demo.py
290
+ ```
291
+
292
+ Writes `examples/credit_card_validation.png`. See [examples/credit_card_readme.md](examples/credit_card_readme.md) for dataset provenance.
293
+
294
+ ## License
295
+
296
+ Apache License 2.0. See [LICENSE](LICENSE).
297
+
298
+ Maintainers can find the release procedure in [RELEASING.md](RELEASING.md).
@@ -0,0 +1,6 @@
1
+ fprcal/__init__.py,sha256=Ug1fy2Yiy4g-IVYz_aZoU7yDTBrS5zlyeKewR_LVBzY,988
2
+ fprcal/calibration.py,sha256=u6FlFV-geweqFJRtNQGeOLqg5jXRVlqhh9g6qSRisJQ,10837
3
+ fprcal-0.1.0.dist-info/METADATA,sha256=_E7L-UU0cBXvwEyepiaPsU6hAYMcx0-6E-czTzjDANY,16782
4
+ fprcal-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
5
+ fprcal-0.1.0.dist-info/licenses/LICENSE,sha256=2FwHuu9ECdXJ05xv5XL7D7fpbMLAefQDvRGWC7cojEM,11351
6
+ fprcal-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2025] [CISCO - AI DEFENSE]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.