fbcert 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fbcert-1.0.0/.gitignore +8 -0
- fbcert-1.0.0/CITATION.cff +49 -0
- fbcert-1.0.0/LICENSE +21 -0
- fbcert-1.0.0/PKG-INFO +192 -0
- fbcert-1.0.0/README.md +148 -0
- fbcert-1.0.0/fbcert/__init__.py +18 -0
- fbcert-1.0.0/fbcert/__main__.py +127 -0
- fbcert-1.0.0/fbcert/_validation.py +79 -0
- fbcert-1.0.0/fbcert/binary.py +533 -0
- fbcert-1.0.0/fbcert/multiclass.py +511 -0
- fbcert-1.0.0/fbcert/py.typed +0 -0
- fbcert-1.0.0/fbcert/results.py +141 -0
- fbcert-1.0.0/pyproject.toml +82 -0
fbcert-1.0.0/.gitignore
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
cff-version: 1.2.0
|
|
2
|
+
message: "Please cite the paper when using this code."
|
|
3
|
+
type: software
|
|
4
|
+
title: "fbcert: finite-batch support tests for label-shift EM"
|
|
5
|
+
version: 1.0.0
|
|
6
|
+
license: MIT
|
|
7
|
+
url: "https://github.com/MaxwellNi/fbcert"
|
|
8
|
+
repository-code: "https://github.com/MaxwellNi/fbcert"
|
|
9
|
+
authors:
|
|
10
|
+
- family-names: Ni
|
|
11
|
+
given-names: Pin
|
|
12
|
+
affiliation: "University of Luxembourg; University College London"
|
|
13
|
+
email: ni.pin@uni.lu
|
|
14
|
+
orcid: "https://orcid.org/0000-0003-4516-1249"
|
|
15
|
+
- family-names: Altmeier
|
|
16
|
+
given-names: Angela
|
|
17
|
+
affiliation: University of Luxembourg
|
|
18
|
+
email: angela.altmeier@uni.lu
|
|
19
|
+
orcid: "https://orcid.org/0009-0007-5690-7372"
|
|
20
|
+
- family-names: Fisch
|
|
21
|
+
given-names: Christian
|
|
22
|
+
affiliation: University of Luxembourg
|
|
23
|
+
email: christian.fisch@uni.lu
|
|
24
|
+
orcid: "https://orcid.org/0000-0003-3609-7193"
|
|
25
|
+
preferred-citation:
|
|
26
|
+
type: conference-paper
|
|
27
|
+
title: "Certify Before Recalibrating: Exact Support Tests for Label-Shift EM in Rare Web Streams"
|
|
28
|
+
authors:
|
|
29
|
+
- family-names: Ni
|
|
30
|
+
given-names: Pin
|
|
31
|
+
orcid: "https://orcid.org/0000-0003-4516-1249"
|
|
32
|
+
- family-names: Altmeier
|
|
33
|
+
given-names: Angela
|
|
34
|
+
orcid: "https://orcid.org/0009-0007-5690-7372"
|
|
35
|
+
- family-names: Fisch
|
|
36
|
+
given-names: Christian
|
|
37
|
+
orcid: "https://orcid.org/0000-0003-3609-7193"
|
|
38
|
+
year: 2027
|
|
39
|
+
doi: "10.1145/3862322.3863596"
|
|
40
|
+
url: "https://doi.org/10.1145/3862322.3863596"
|
|
41
|
+
collection-title: "Proceedings of the Twentieth ACM International Conference on Web Search and Data Mining (WSDM ’27)"
|
|
42
|
+
publisher:
|
|
43
|
+
name: "ACM"
|
|
44
|
+
conference:
|
|
45
|
+
name: "WSDM ’27"
|
|
46
|
+
city: "Hong Kong"
|
|
47
|
+
country: CN
|
|
48
|
+
date-start: 2027-02-15
|
|
49
|
+
date-end: 2027-02-19
|
fbcert-1.0.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Pin Ni, Angela Altmeier, and Christian Fisch
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
fbcert-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: fbcert
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Tell from a batch of scores whether the label-shift likelihood puts its optimum above a chosen floor.
|
|
5
|
+
Project-URL: Repository, https://github.com/MaxwellNi/fbcert
|
|
6
|
+
Project-URL: Paper, https://doi.org/10.1145/3862322.3863596
|
|
7
|
+
Project-URL: Issues, https://github.com/MaxwellNi/fbcert/issues
|
|
8
|
+
Author-email: Pin Ni <ni.pin@uni.lu>, Angela Altmeier <angela.altmeier@uni.lu>, Christian Fisch <christian.fisch@uni.lu>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: event rates,expectation maximization,label shift,quantification
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.10
|
|
23
|
+
Requires-Dist: numpy<3,>=1.24
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: build>=1.2; extra == 'dev'
|
|
26
|
+
Requires-Dist: ruff==0.15.1; extra == 'dev'
|
|
27
|
+
Requires-Dist: twine>=6; extra == 'dev'
|
|
28
|
+
Provides-Extra: figures
|
|
29
|
+
Requires-Dist: matplotlib==3.10.8; extra == 'figures'
|
|
30
|
+
Provides-Extra: quantifiers
|
|
31
|
+
Requires-Dist: clarabel==0.11.1; extra == 'quantifiers'
|
|
32
|
+
Requires-Dist: cvxpy==1.7.5; extra == 'quantifiers'
|
|
33
|
+
Provides-Extra: recurrent
|
|
34
|
+
Requires-Dist: torch==2.10.0; extra == 'recurrent'
|
|
35
|
+
Provides-Extra: reproduction
|
|
36
|
+
Requires-Dist: joblib==1.5.3; extra == 'reproduction'
|
|
37
|
+
Requires-Dist: lightgbm==4.6.0; extra == 'reproduction'
|
|
38
|
+
Requires-Dist: numpy==1.26.4; extra == 'reproduction'
|
|
39
|
+
Requires-Dist: pandas==2.3.3; extra == 'reproduction'
|
|
40
|
+
Requires-Dist: pyarrow==23.0.1; extra == 'reproduction'
|
|
41
|
+
Requires-Dist: scikit-learn==1.5.1; extra == 'reproduction'
|
|
42
|
+
Requires-Dist: scipy==1.15.3; extra == 'reproduction'
|
|
43
|
+
Description-Content-Type: text/markdown
|
|
44
|
+
|
|
45
|
+
# fbcert
|
|
46
|
+
|
|
47
|
+
Tell from a batch of scores whether the label-shift likelihood puts its optimum above a chosen floor.
|
|
48
|
+
|
|
49
|
+
Pin Ni, Angela Altmeier and Christian Fisch. *Certify Before Recalibrating: Exact Support Tests for Label-Shift EM in Rare Web Streams*. WSDM '27, to appear. [DOI 10.1145/3862322.3863596](https://doi.org/10.1145/3862322.3863596) · [Mathematical supplement](https://github.com/MaxwellNi/fbcert/blob/v1.0.0/paper/mathematical_supplement.pdf) · [Empirical supplement](https://github.com/MaxwellNi/fbcert/blob/v1.0.0/paper/empirical_supplement.pdf)
|
|
50
|
+
|
|
51
|
+
A classifier can rank cases well and still predict the wrong number of events. When prevalence changes, label-shift EM estimates a new rate from the scores. For rare events, that estimate can fall to zero. Given the source prevalence and a minimum rate you care about, one pass over the scores determines which side of that floor the likelihood favors.
|
|
52
|
+
|
|
53
|
+
## Installation
|
|
54
|
+
|
|
55
|
+
Install the library and its command line with pip.
|
|
56
|
+
|
|
57
|
+
```sh
|
|
58
|
+
pip install fbcert
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
For the study programs and example files, install from the repository checkout.
|
|
62
|
+
|
|
63
|
+
```sh
|
|
64
|
+
git clone https://github.com/MaxwellNi/fbcert
|
|
65
|
+
cd fbcert
|
|
66
|
+
pip install .
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
The library depends on NumPy. To draw the paper's figures, add Matplotlib and install the [figure fonts](https://github.com/MaxwellNi/fbcert/blob/v1.0.0/docs/reproducing.md#figures).
|
|
70
|
+
|
|
71
|
+
```sh
|
|
72
|
+
pip install '.[figures]'
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Install `reproduction` for the fitting programs. The recurrent comparator also needs `recurrent`. The comparison with the `abstention` package needs that package and the `quantifiers` extra. The [version table](https://github.com/MaxwellNi/fbcert/blob/v1.0.0/docs/reproducing.md#software-versions) lists the versions used in the study and in the rebuild.
|
|
76
|
+
|
|
77
|
+
## Quick start
|
|
78
|
+
|
|
79
|
+
The source event rate was 1% and the workload floor is 0.5%. The CSV needs a header named `score` and one probability per row in that column.
|
|
80
|
+
|
|
81
|
+
```sh
|
|
82
|
+
csv=$(mktemp)
|
|
83
|
+
printf '%s\n' score 0.001 0.002 0.004 0.007 0.013 0.029 > "$csv"
|
|
84
|
+
fbcert "$csv" --source-prior 0.01 --floor 0.005
|
|
85
|
+
rm "$csv"
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
The command prints this JSON report.
|
|
89
|
+
|
|
90
|
+
```json
|
|
91
|
+
{
|
|
92
|
+
"n": 6,
|
|
93
|
+
"source_prior": 0.01,
|
|
94
|
+
"mu": 0.9422780735594726,
|
|
95
|
+
"decision": {
|
|
96
|
+
"floor": 0.005,
|
|
97
|
+
"support": -0.062555139576431,
|
|
98
|
+
"side": "below",
|
|
99
|
+
"numerical_tolerance": 1e-12
|
|
100
|
+
},
|
|
101
|
+
"optimum": {
|
|
102
|
+
"kind": "zero",
|
|
103
|
+
"lower": 0.0,
|
|
104
|
+
"upper": 0.0,
|
|
105
|
+
"unique": true
|
|
106
|
+
},
|
|
107
|
+
"em": {
|
|
108
|
+
"prevalence": 1.6131924435684172e-07,
|
|
109
|
+
"iterations": 183,
|
|
110
|
+
"converged": true,
|
|
111
|
+
"movement": 9.882098080347236e-09,
|
|
112
|
+
"tolerance": 1e-08,
|
|
113
|
+
"max_iter": 1000
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
The negative slope at the floor puts the optimum below 0.5%. The EM-map slope at zero, `mu`, equals the mean relative odds. In exact arithmetic a nonflat likelihood has its optimum at zero whenever this mean is at most one. If the reported mean rounds to one, read `optimum.kind` for the boundary decision. When rounding prevents a definite sign at the floor, the command reports `decision.side` as `unresolved`. The function `fbcert.exact_support` evaluates the same slope in exact rational arithmetic.
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
from fbcert import BinaryBatch
|
|
122
|
+
|
|
123
|
+
scores = [0.001, 0.002, 0.004, 0.007, 0.013, 0.029]
|
|
124
|
+
batch = BinaryBatch(scores, source_prior=0.01)
|
|
125
|
+
print(batch.mu, batch.decide(floor=0.005).side, batch.optimum().kind)
|
|
126
|
+
# 0.9422780735594726 below zero
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
For several classes, an excluded class can still improve a fit. Here the second class has zero target weight. The returned step gives it positive weight and supplies a lower bound on the gain in log likelihood.
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
from fbcert import MulticlassBatch
|
|
133
|
+
|
|
134
|
+
scores = [[0.20, 0.50, 0.30], [0.10, 0.60, 0.30]]
|
|
135
|
+
batch = MulticlassBatch(scores, source_prior=[0.4, 0.3, 0.3])
|
|
136
|
+
q = [0.5, 0.0, 0.5]
|
|
137
|
+
print(batch.diagnostics(q).global_gap_upper_bound)
|
|
138
|
+
print(batch.escape(q, excluded=1).improvement_lower_bound)
|
|
139
|
+
# 3.4222222222222243
|
|
140
|
+
# 0.23113207547169537
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
For examples that read the scores from the CSV files in the repository, see the [reproduction guide](https://github.com/MaxwellNi/fbcert/blob/v1.0.0/docs/reproducing.md#score-files).
|
|
144
|
+
|
|
145
|
+
## Reproducing the paper
|
|
146
|
+
|
|
147
|
+
| Task | Command from the repository root | Inputs and runtime |
|
|
148
|
+
|---|---|---|
|
|
149
|
+
| Check all 1,335 registered claims | `python -m scripts.check_claims` | Bundled records, seconds |
|
|
150
|
+
| Run the tests | `python -m unittest discover -s tests` | NumPy for the core tests. Fitting tests need `reproduction`. Add `recurrent` for the recurrent tests, or `quantifiers` and the `abstention` package for the comparison tests. |
|
|
151
|
+
| Draw the three figures | `python -m scripts.draw_figures` | Bundled records, Matplotlib and Linux Libertine, seconds |
|
|
152
|
+
| Rebuild from the raw archives | Follow the commands in the reproduction guide below. Use `python -m scripts.study_pipeline --list-stages` to preview the stages. | GLEIF, SEC Form D and Kickstarter archives. About 8 hours elapsed and 25 CPU-hours in the reference run. |
|
|
153
|
+
|
|
154
|
+
Starting from the raw archives on Intel Xeon Gold 6132 processors, the study programs regenerated 54 of 56 records in full. A further record combines three measured checks with three observations from data collection. The last record supplies the study settings.
|
|
155
|
+
|
|
156
|
+
Of the 1,331 values registered for that run, 1,315 matched at printed precision. Fourteen differences came from the logistic comparator, and two were numerical residuals within their stated bounds. On the pooled registry development data, the four predictors kept the same ordering by PR-AUC, log loss and Brier score. The [reproduction guide](https://github.com/MaxwellNi/fbcert/blob/v1.0.0/docs/reproducing.md) gives the commands, timings and precision criteria.
|
|
157
|
+
|
|
158
|
+
## Repository layout
|
|
159
|
+
|
|
160
|
+
| Path | Contents |
|
|
161
|
+
|---|---|
|
|
162
|
+
| `fbcert/`, `examples/` | Library, command line and sample score batches |
|
|
163
|
+
| `records/`, `claims/` | Numerical results, their field definitions and the expressions for printed values |
|
|
164
|
+
| `scripts/` | Obtain and verify source archives, evaluate predictions, rebuild the study, check the published values, draw the figures and replay the result tables |
|
|
165
|
+
| `data/`, `experiments/` | Input manifests and fitting programs |
|
|
166
|
+
| `paper/` | Mathematical and empirical supplements |
|
|
167
|
+
| `tests/`, `docs/` | Test suite, reproduction guide and data guide |
|
|
168
|
+
|
|
169
|
+
## Data
|
|
170
|
+
|
|
171
|
+
The study uses GLEIF registry publications, SEC Form D filings and a Web Robots Kickstarter snapshot. The manifests identify the source files. Obtain the raw files from the sources listed in the [data guide](https://github.com/MaxwellNi/fbcert/blob/v1.0.0/docs/data.md). The repository contains aggregate results and model-fitting code.
|
|
172
|
+
|
|
173
|
+
## Scope
|
|
174
|
+
|
|
175
|
+
The test locates the likelihood optimum for the batch. One registry estimate passed at a floor of half the mean of the last three observed rates and still overestimated the event rate by 688%. In the paper's replay, acting on the test did not improve prediction. Files from the first four days of the registry holdout had been parsed for counts, including event counts, before the design was final.
|
|
176
|
+
|
|
177
|
+
## Citation
|
|
178
|
+
|
|
179
|
+
```bibtex
|
|
180
|
+
@inproceedings{ni2027certify,
|
|
181
|
+
author = {Ni, Pin and Altmeier, Angela and Fisch, Christian},
|
|
182
|
+
title = {Certify Before Recalibrating: Exact Support Tests for Label-Shift {EM} in Rare Web Streams},
|
|
183
|
+
booktitle = {Proceedings of the Twentieth ACM International Conference on Web Search and Data Mining},
|
|
184
|
+
year = {2027},
|
|
185
|
+
doi = {10.1145/3862322.3863596},
|
|
186
|
+
publisher = {Association for Computing Machinery}
|
|
187
|
+
}
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
## License
|
|
191
|
+
|
|
192
|
+
This repository is released under the [MIT License](https://github.com/MaxwellNi/fbcert/blob/v1.0.0/LICENSE). Source data remain subject to their providers' terms.
|
fbcert-1.0.0/README.md
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
# fbcert
|
|
2
|
+
|
|
3
|
+
Tell from a batch of scores whether the label-shift likelihood puts its optimum above a chosen floor.
|
|
4
|
+
|
|
5
|
+
Pin Ni, Angela Altmeier and Christian Fisch. *Certify Before Recalibrating: Exact Support Tests for Label-Shift EM in Rare Web Streams*. WSDM '27, to appear. [DOI 10.1145/3862322.3863596](https://doi.org/10.1145/3862322.3863596) · [Mathematical supplement](https://github.com/MaxwellNi/fbcert/blob/v1.0.0/paper/mathematical_supplement.pdf) · [Empirical supplement](https://github.com/MaxwellNi/fbcert/blob/v1.0.0/paper/empirical_supplement.pdf)
|
|
6
|
+
|
|
7
|
+
A classifier can rank cases well and still predict the wrong number of events. When prevalence changes, label-shift EM estimates a new rate from the scores. For rare events, that estimate can fall to zero. Given the source prevalence and a minimum rate you care about, one pass over the scores determines which side of that floor the likelihood favors.
|
|
8
|
+
|
|
9
|
+
## Installation
|
|
10
|
+
|
|
11
|
+
Install the library and its command line with pip.
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
pip install fbcert
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
For the study programs and example files, install from the repository checkout.
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
git clone https://github.com/MaxwellNi/fbcert
|
|
21
|
+
cd fbcert
|
|
22
|
+
pip install .
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
The library depends on NumPy. To draw the paper's figures, add Matplotlib and install the [figure fonts](https://github.com/MaxwellNi/fbcert/blob/v1.0.0/docs/reproducing.md#figures).
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
pip install '.[figures]'
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Install `reproduction` for the fitting programs. The recurrent comparator also needs `recurrent`. The comparison with the `abstention` package needs that package and the `quantifiers` extra. The [version table](https://github.com/MaxwellNi/fbcert/blob/v1.0.0/docs/reproducing.md#software-versions) lists the versions used in the study and in the rebuild.
|
|
32
|
+
|
|
33
|
+
## Quick start
|
|
34
|
+
|
|
35
|
+
The source event rate was 1% and the workload floor is 0.5%. The CSV needs a header named `score` and one probability per row in that column.
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
csv=$(mktemp)
|
|
39
|
+
printf '%s\n' score 0.001 0.002 0.004 0.007 0.013 0.029 > "$csv"
|
|
40
|
+
fbcert "$csv" --source-prior 0.01 --floor 0.005
|
|
41
|
+
rm "$csv"
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
The command prints this JSON report.
|
|
45
|
+
|
|
46
|
+
```json
|
|
47
|
+
{
|
|
48
|
+
"n": 6,
|
|
49
|
+
"source_prior": 0.01,
|
|
50
|
+
"mu": 0.9422780735594726,
|
|
51
|
+
"decision": {
|
|
52
|
+
"floor": 0.005,
|
|
53
|
+
"support": -0.062555139576431,
|
|
54
|
+
"side": "below",
|
|
55
|
+
"numerical_tolerance": 1e-12
|
|
56
|
+
},
|
|
57
|
+
"optimum": {
|
|
58
|
+
"kind": "zero",
|
|
59
|
+
"lower": 0.0,
|
|
60
|
+
"upper": 0.0,
|
|
61
|
+
"unique": true
|
|
62
|
+
},
|
|
63
|
+
"em": {
|
|
64
|
+
"prevalence": 1.6131924435684172e-07,
|
|
65
|
+
"iterations": 183,
|
|
66
|
+
"converged": true,
|
|
67
|
+
"movement": 9.882098080347236e-09,
|
|
68
|
+
"tolerance": 1e-08,
|
|
69
|
+
"max_iter": 1000
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
The negative slope at the floor puts the optimum below 0.5%. The EM-map slope at zero, `mu`, equals the mean relative odds. In exact arithmetic a nonflat likelihood has its optimum at zero whenever this mean is at most one. If the reported mean rounds to one, read `optimum.kind` for the boundary decision. When rounding prevents a definite sign at the floor, the command reports `decision.side` as `unresolved`. The function `fbcert.exact_support` evaluates the same slope in exact rational arithmetic.
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
from fbcert import BinaryBatch
|
|
78
|
+
|
|
79
|
+
scores = [0.001, 0.002, 0.004, 0.007, 0.013, 0.029]
|
|
80
|
+
batch = BinaryBatch(scores, source_prior=0.01)
|
|
81
|
+
print(batch.mu, batch.decide(floor=0.005).side, batch.optimum().kind)
|
|
82
|
+
# 0.9422780735594726 below zero
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
For several classes, an excluded class can still improve a fit. Here the second class has zero target weight. The returned step gives it positive weight and supplies a lower bound on the gain in log likelihood.
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
from fbcert import MulticlassBatch
|
|
89
|
+
|
|
90
|
+
scores = [[0.20, 0.50, 0.30], [0.10, 0.60, 0.30]]
|
|
91
|
+
batch = MulticlassBatch(scores, source_prior=[0.4, 0.3, 0.3])
|
|
92
|
+
q = [0.5, 0.0, 0.5]
|
|
93
|
+
print(batch.diagnostics(q).global_gap_upper_bound)
|
|
94
|
+
print(batch.escape(q, excluded=1).improvement_lower_bound)
|
|
95
|
+
# 3.4222222222222243
|
|
96
|
+
# 0.23113207547169537
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
For examples that read the scores from the CSV files in the repository, see the [reproduction guide](https://github.com/MaxwellNi/fbcert/blob/v1.0.0/docs/reproducing.md#score-files).
|
|
100
|
+
|
|
101
|
+
## Reproducing the paper
|
|
102
|
+
|
|
103
|
+
| Task | Command from the repository root | Inputs and runtime |
|
|
104
|
+
|---|---|---|
|
|
105
|
+
| Check all 1,335 registered claims | `python -m scripts.check_claims` | Bundled records, seconds |
|
|
106
|
+
| Run the tests | `python -m unittest discover -s tests` | NumPy for the core tests. Fitting tests need `reproduction`. Add `recurrent` for the recurrent tests, or `quantifiers` and the `abstention` package for the comparison tests. |
|
|
107
|
+
| Draw the three figures | `python -m scripts.draw_figures` | Bundled records, Matplotlib and Linux Libertine, seconds |
|
|
108
|
+
| Rebuild from the raw archives | Follow the commands in the reproduction guide below. Use `python -m scripts.study_pipeline --list-stages` to preview the stages. | GLEIF, SEC Form D and Kickstarter archives. About 8 hours elapsed and 25 CPU-hours in the reference run. |
|
|
109
|
+
|
|
110
|
+
Starting from the raw archives on Intel Xeon Gold 6132 processors, the study programs regenerated 54 of 56 records in full. A further record combines three measured checks with three observations from data collection. The last record supplies the study settings.
|
|
111
|
+
|
|
112
|
+
Of the 1,331 values registered for that run, 1,315 matched at printed precision. Fourteen differences came from the logistic comparator, and two were numerical residuals within their stated bounds. On the pooled registry development data, the four predictors kept the same ordering by PR-AUC, log loss and Brier score. The [reproduction guide](https://github.com/MaxwellNi/fbcert/blob/v1.0.0/docs/reproducing.md) gives the commands, timings and precision criteria.
|
|
113
|
+
|
|
114
|
+
## Repository layout
|
|
115
|
+
|
|
116
|
+
| Path | Contents |
|
|
117
|
+
|---|---|
|
|
118
|
+
| `fbcert/`, `examples/` | Library, command line and sample score batches |
|
|
119
|
+
| `records/`, `claims/` | Numerical results, their field definitions and the expressions for printed values |
|
|
120
|
+
| `scripts/` | Obtain and verify source archives, evaluate predictions, rebuild the study, check the published values, draw the figures and replay the result tables |
|
|
121
|
+
| `data/`, `experiments/` | Input manifests and fitting programs |
|
|
122
|
+
| `paper/` | Mathematical and empirical supplements |
|
|
123
|
+
| `tests/`, `docs/` | Test suite, reproduction guide and data guide |
|
|
124
|
+
|
|
125
|
+
## Data
|
|
126
|
+
|
|
127
|
+
The study uses GLEIF registry publications, SEC Form D filings and a Web Robots Kickstarter snapshot. The manifests identify the source files. Obtain the raw files from the sources listed in the [data guide](https://github.com/MaxwellNi/fbcert/blob/v1.0.0/docs/data.md). The repository contains aggregate results and model-fitting code.
|
|
128
|
+
|
|
129
|
+
## Scope
|
|
130
|
+
|
|
131
|
+
The test locates the likelihood optimum for the batch. One registry estimate passed at a floor of half the mean of the last three observed rates and still overestimated the event rate by 688%. In the paper's replay, acting on the test did not improve prediction. Files from the first four days of the registry holdout had been parsed for counts, including event counts, before the design was final.
|
|
132
|
+
|
|
133
|
+
## Citation
|
|
134
|
+
|
|
135
|
+
```bibtex
|
|
136
|
+
@inproceedings{ni2027certify,
|
|
137
|
+
author = {Ni, Pin and Altmeier, Angela and Fisch, Christian},
|
|
138
|
+
title = {Certify Before Recalibrating: Exact Support Tests for Label-Shift {EM} in Rare Web Streams},
|
|
139
|
+
booktitle = {Proceedings of the Twentieth ACM International Conference on Web Search and Data Mining},
|
|
140
|
+
year = {2027},
|
|
141
|
+
doi = {10.1145/3862322.3863596},
|
|
142
|
+
publisher = {Association for Computing Machinery}
|
|
143
|
+
}
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
## License
|
|
147
|
+
|
|
148
|
+
This repository is released under the [MIT License](https://github.com/MaxwellNi/fbcert/blob/v1.0.0/LICENSE). Source data remain subject to their providers' terms.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Finite-batch support tests for label-shift EM."""
|
|
2
|
+
|
|
3
|
+
from .binary import BinaryBatch, exact_support
|
|
4
|
+
from .multiclass import MulticlassBatch
|
|
5
|
+
from .results import Decision, Diagnostics, EMFit, EscapeStep, Optimum
|
|
6
|
+
|
|
7
|
+
__version__ = "1.0.0"
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"BinaryBatch",
|
|
11
|
+
"Decision",
|
|
12
|
+
"Diagnostics",
|
|
13
|
+
"EMFit",
|
|
14
|
+
"EscapeStep",
|
|
15
|
+
"MulticlassBatch",
|
|
16
|
+
"Optimum",
|
|
17
|
+
"exact_support",
|
|
18
|
+
]
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Command line for a fixed batch of binary scores."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import csv
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from tempfile import NamedTemporaryFile
|
|
10
|
+
|
|
11
|
+
from . import BinaryBatch, __version__
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _read_scores(path: Path) -> list[float]:
|
|
15
|
+
with path.open(encoding="utf-8-sig", newline="") as stream:
|
|
16
|
+
rows = csv.DictReader(stream, strict=True)
|
|
17
|
+
if (rows.fieldnames or []).count("score") != 1:
|
|
18
|
+
raise ValueError("scores CSV must have exactly one column named 'score'")
|
|
19
|
+
values = []
|
|
20
|
+
for row in rows:
|
|
21
|
+
try:
|
|
22
|
+
value = float(row["score"])
|
|
23
|
+
except (TypeError, ValueError):
|
|
24
|
+
raise ValueError(
|
|
25
|
+
f"score on CSV line {rows.line_num} must be a number"
|
|
26
|
+
) from None
|
|
27
|
+
if not 0 < value < 1:
|
|
28
|
+
raise ValueError(
|
|
29
|
+
f"score on CSV line {rows.line_num} must be strictly between 0 and 1, got {value}"
|
|
30
|
+
)
|
|
31
|
+
values.append(value)
|
|
32
|
+
return values
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _write_report(path: Path, report: str) -> None:
|
|
36
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
37
|
+
temporary = None
|
|
38
|
+
try:
|
|
39
|
+
with NamedTemporaryFile(
|
|
40
|
+
"w", encoding="utf-8", dir=path.parent, delete=False
|
|
41
|
+
) as stream:
|
|
42
|
+
temporary = Path(stream.name)
|
|
43
|
+
stream.write(report)
|
|
44
|
+
# Publish the complete report only if this name is still free.
|
|
45
|
+
# Both paths are on the same filesystem and have the same owner.
|
|
46
|
+
os.link(temporary, path)
|
|
47
|
+
finally:
|
|
48
|
+
if temporary is not None:
|
|
49
|
+
temporary.unlink(missing_ok=True)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def main(argv: Sequence[str] | None = None) -> None:
|
|
53
|
+
"""Print the binary support decision, optimum and EM fit for a CSV score column."""
|
|
54
|
+
parser = argparse.ArgumentParser(
|
|
55
|
+
prog="fbcert",
|
|
56
|
+
description="Test whether the label-shift likelihood optimum exceeds a workload floor.",
|
|
57
|
+
)
|
|
58
|
+
parser.add_argument(
|
|
59
|
+
"--version", action="version", version=f"%(prog)s {__version__}"
|
|
60
|
+
)
|
|
61
|
+
parser.add_argument(
|
|
62
|
+
"scores",
|
|
63
|
+
type=Path,
|
|
64
|
+
help="CSV with a header and one 'score' column of probabilities in (0, 1).",
|
|
65
|
+
)
|
|
66
|
+
parser.add_argument(
|
|
67
|
+
"--source-prior", type=float, required=True, help="Source event rate in (0, 1)."
|
|
68
|
+
)
|
|
69
|
+
parser.add_argument(
|
|
70
|
+
"--floor", type=float, required=True, help="Workload floor in (0, 1)."
|
|
71
|
+
)
|
|
72
|
+
parser.add_argument(
|
|
73
|
+
"--initial", type=float, help="Starting EM prevalence (default: source prior)."
|
|
74
|
+
)
|
|
75
|
+
parser.add_argument(
|
|
76
|
+
"--decision-tolerance",
|
|
77
|
+
type=float,
|
|
78
|
+
default=1e-12,
|
|
79
|
+
help="Absolute numerical tolerance on the mean support (default: %(default)s).",
|
|
80
|
+
)
|
|
81
|
+
parser.add_argument(
|
|
82
|
+
"--em-tolerance",
|
|
83
|
+
type=float,
|
|
84
|
+
default=1e-8,
|
|
85
|
+
help="Stop EM when the change in prevalence falls below this value (default: %(default)s).",
|
|
86
|
+
)
|
|
87
|
+
parser.add_argument(
|
|
88
|
+
"--max-iter",
|
|
89
|
+
type=int,
|
|
90
|
+
default=1000,
|
|
91
|
+
help="Maximum number of EM updates (default: %(default)s).",
|
|
92
|
+
)
|
|
93
|
+
parser.add_argument(
|
|
94
|
+
"--output",
|
|
95
|
+
type=Path,
|
|
96
|
+
help="New file for the JSON report (default: standard output).",
|
|
97
|
+
)
|
|
98
|
+
args = parser.parse_args(argv)
|
|
99
|
+
try:
|
|
100
|
+
if args.output is not None and os.path.lexists(args.output):
|
|
101
|
+
raise FileExistsError(f"output already exists: {args.output}")
|
|
102
|
+
scores = _read_scores(args.scores)
|
|
103
|
+
batch = BinaryBatch(scores, args.source_prior)
|
|
104
|
+
em = batch.em(
|
|
105
|
+
args.source_prior if args.initial is None else args.initial,
|
|
106
|
+
args.em_tolerance,
|
|
107
|
+
args.max_iter,
|
|
108
|
+
)
|
|
109
|
+
report = {
|
|
110
|
+
"n": len(scores),
|
|
111
|
+
"source_prior": batch.source_prior,
|
|
112
|
+
"mu": batch.mu,
|
|
113
|
+
"decision": batch.decide(args.floor, args.decision_tolerance).to_dict(),
|
|
114
|
+
"optimum": batch.optimum().to_dict(),
|
|
115
|
+
"em": em.to_dict(),
|
|
116
|
+
}
|
|
117
|
+
rendered = json.dumps(report, indent=2, allow_nan=False) + "\n"
|
|
118
|
+
if args.output is None:
|
|
119
|
+
print(rendered, end="")
|
|
120
|
+
else:
|
|
121
|
+
_write_report(args.output, rendered)
|
|
122
|
+
except (OSError, csv.Error, ValueError) as error:
|
|
123
|
+
parser.error(str(error))
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
if __name__ == "__main__":
|
|
127
|
+
main()
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Numeric input domains shared by the score-batch classes."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import operator
|
|
5
|
+
from decimal import Decimal
|
|
6
|
+
from numbers import Real
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
from numpy.typing import ArrayLike, NDArray
|
|
10
|
+
|
|
11
|
+
FloatArray = NDArray[np.float64]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def real_array(values: ArrayLike, name: str) -> FloatArray:
|
|
15
|
+
"""Copy real numeric input to a rectangular binary64 array."""
|
|
16
|
+
try:
|
|
17
|
+
# Keep the types of Python sequences until validation; NumPy otherwise
|
|
18
|
+
# converts a Boolean mixed with numbers to an integer or a float.
|
|
19
|
+
if isinstance(values, np.ndarray):
|
|
20
|
+
array = np.asarray(values)
|
|
21
|
+
else:
|
|
22
|
+
array = np.asarray(values, dtype=object)
|
|
23
|
+
if array.dtype.kind == "O":
|
|
24
|
+
if any(
|
|
25
|
+
isinstance(v, (bool, np.bool_)) or not isinstance(v, (Real, Decimal))
|
|
26
|
+
for v in array.flat
|
|
27
|
+
):
|
|
28
|
+
raise ValueError
|
|
29
|
+
elif array.dtype.kind not in "iuf":
|
|
30
|
+
raise ValueError
|
|
31
|
+
with np.errstate(over="ignore", invalid="ignore"):
|
|
32
|
+
return np.array(array, dtype=np.float64, copy=True)
|
|
33
|
+
except (TypeError, ValueError, OverflowError):
|
|
34
|
+
raise ValueError(
|
|
35
|
+
f"{name} must contain real numbers in a rectangular array"
|
|
36
|
+
) from None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def read_only(array: FloatArray) -> FloatArray:
|
|
40
|
+
"""Copy an array onto immutable storage."""
|
|
41
|
+
return np.frombuffer(array.tobytes(), dtype=np.float64).reshape(array.shape)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def real_number(value: float, name: str) -> float:
|
|
45
|
+
"""Return a finite real scalar."""
|
|
46
|
+
if isinstance(value, (bool, np.bool_)) or not isinstance(value, (Real, Decimal)):
|
|
47
|
+
raise ValueError(f"{name} must be a finite real number, got {value!r}")
|
|
48
|
+
try:
|
|
49
|
+
number = float(value)
|
|
50
|
+
except OverflowError:
|
|
51
|
+
raise ValueError(f"{name} exceeds floating-point range") from None
|
|
52
|
+
if not math.isfinite(number):
|
|
53
|
+
raise ValueError(f"{name} must be finite, got {number}")
|
|
54
|
+
return number
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def probability(value: float, name: str, *, interior: bool = False) -> float:
|
|
58
|
+
"""Validate a scalar probability on the closed or open unit interval."""
|
|
59
|
+
number = real_number(value, name)
|
|
60
|
+
if interior and not 0 < number < 1:
|
|
61
|
+
raise ValueError(f"{name} must be strictly between 0 and 1, got {number}")
|
|
62
|
+
if not 0 <= number <= 1:
|
|
63
|
+
raise ValueError(f"{name} must be in [0, 1], got {number}")
|
|
64
|
+
return number
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def integer(value: int, name: str, minimum: int) -> int:
|
|
68
|
+
"""Validate an integer argument against its lower bound."""
|
|
69
|
+
if isinstance(value, (bool, np.bool_)):
|
|
70
|
+
raise ValueError(f"{name} must be an integer >= {minimum}, got {value!r}")
|
|
71
|
+
try:
|
|
72
|
+
number = operator.index(value)
|
|
73
|
+
except TypeError:
|
|
74
|
+
raise ValueError(
|
|
75
|
+
f"{name} must be an integer >= {minimum}, got {value!r}"
|
|
76
|
+
) from None
|
|
77
|
+
if number < minimum:
|
|
78
|
+
raise ValueError(f"{name} must be an integer >= {minimum}, got {number}")
|
|
79
|
+
return number
|