File size: 2,529 Bytes
ecaa1ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"""The label-noise model: per-stratum Beta posteriors for the perturbation.

The uncertainty interval a benchmark run reports comes from perturbing the released
labels. Two error rates drive it, both estimated per confidence stratum from the audit:
``alpha`` (a marked node the audit rejected -- a false positive to remove) and ``gamma``
(an unmarked node the audit added -- an omission to introduce). Each is a Beta(1+a, 1+b)
posterior over its rate; a draw samples a rate per stratum and flips labels by it.

``noise.json`` carries both rates, produced by the pipeline's ``scripts/noise.py`` from
the same audit assets the evaluation notebook uses:

    {"bins": 3,
     "alpha": {"0": [a, b], "1": [a, b], "2": [a, b]},
     "gamma": {"0": [a, b], "1": [a, b], "2": [a, b]}}
"""

from __future__ import annotations

import json
from pathlib import Path

import numpy as np


class NoiseModel:
    """Per-stratum Beta posteriors for the node-level alpha and gamma rates."""

    def __init__(self, bins: int, alpha: dict[int, tuple[int, int]],
                 gamma: dict[int, tuple[int, int]]) -> None:
        self._bins = bins
        self._strata = list(range(bins))
        self._alpha = {int(k): tuple(v) for k, v in alpha.items()}
        self._gamma = {int(k): tuple(v) for k, v in gamma.items()}

    @classmethod
    def load(cls, path: str | Path) -> "NoiseModel":
        """Load the noise model from a noise.json at *path*."""
        document = json.loads(Path(path).read_text(encoding="utf-8"))
        bins = int(document.get("bins", 3))
        return cls(bins, document["alpha"], document["gamma"])

    @property
    def bins(self) -> int:
        """The number of confidence strata."""
        return self._bins

    def index(self) -> dict[int, int]:
        """Map a stratum id to its row in the ``alpha_beta``/``gamma_beta`` arrays."""
        return {stratum: row for row, stratum in enumerate(self._strata)}

    def alpha_beta(self) -> np.ndarray:
        """The (strata, 2) Beta(1+a, 1+b) parameters of the alpha rate per stratum."""
        return self._beta(self._alpha)

    def gamma_beta(self) -> np.ndarray:
        """The (strata, 2) Beta(1+a, 1+b) parameters of the gamma rate per stratum."""
        return self._beta(self._gamma)

    def _beta(self, counts: dict[int, tuple[int, int]]) -> np.ndarray:
        rows = []
        for stratum in self._strata:
            a, b = counts.get(stratum, (0, 0))
            rows.append((1 + a, 1 + b))
        return np.asarray(rows, dtype=float)