"""Goodness-of-fit tests on the root p-values of a Membership Circuit.
The functions of this module criticize a fitted circuit. Their input is the vector of root p-values
of ``n`` independent rows that are known inliers, that is rows of the data distribution the circuit
is meant to describe. If the circuit fits these rows and the combination rules are valid, the
p-values are super-uniform: ``P(p <= t) <= t`` for every ``t``. A circuit that does not fit shows as
too many small p-values. Both tests are one-sided against such an excess of small p-values:
- :func:`binomial_gof` compares the number of p-values at or below one level ``alpha`` with the
binomial distribution ``Bin(n, alpha)``.
- :func:`ks_gof` compares the empirical distribution function of the p-values with the uniform
distribution function (one-sided Kolmogorov-Smirnov test).
How to read the results:
- A **small** result means that the null hypothesis "the rows are samples of the circuit" does not
hold: the circuit misfits these rows. A large result is not a proof of fit. It only says that the
test found no excess of small p-values.
- A conservative combination rule moves the root p-values up. It can therefore hide a misfit, but it
cannot cause a false alarm. With ``MaxP`` or the harmonic mean rules the tests have less power
than with ``Fisher``.
- The Kolmogorov-Smirnov test assumes a continuous null distribution. Ties make it conservative.
Root p-values have ties when many rows get ``p = 1`` after clipping and when discrete leaves use
exact p-values. Use the binomial test at one level ``alpha``, chosen before looking at the
p-values, as the primary statistic and the Kolmogorov-Smirnov test as the secondary one.
- :func:`gof_report` lists the binomial test at several levels. These values are not corrected for
the selection of the level: the smallest of them is not a valid p-value.
- Use held-out rows. Rows that were used to fit the circuit give optimistic (too large) p-values, so
a misfit can go unnoticed on them.
- Pass the p-values in ``float64``, as the membership pass returns them. The count ``p <= alpha`` is
taken in ``float64``, and a p-value that went through ``float32`` is no longer the same number:
the ``float32`` value nearest to 0.05 is about 0.05000000075, which is above 0.05 and is not
counted at ``alpha = 0.05``.
The functions do not need the circuit. They work on any vector of p-values.
"""
from __future__ import annotations
from collections.abc import Iterable, Sequence
from numbers import Real
import numpy as np
import torch
from scipy.stats import binom, ksone
from torch import Tensor
from spflow.exceptions import InvalidParameterError, InvalidTypeError, ShapeError
def _real_array(pvalues: Tensor | np.ndarray | Sequence[float]) -> np.ndarray:
"""Return the input as a NumPy array and check that it holds real numbers."""
if isinstance(pvalues, Tensor):
# The cast to float64 would drop the imaginary part with nothing but a warning.
if pvalues.is_complex():
raise InvalidTypeError(f"pvalues must hold real numbers, got a tensor of dtype {pvalues.dtype}.")
return pvalues.detach().to("cpu", torch.float64).numpy()
try:
values = np.asarray(pvalues)
except ValueError as error:
# NumPy refuses nested sequences whose parts differ in length.
raise ShapeError(
"pvalues could not be converted to an array: nested sequences must have equal lengths."
) from error
except (TypeError, RuntimeError) as error:
# torch refuses tensors inside a sequence if they require grad or are not on the CPU.
raise InvalidTypeError(
f"pvalues could not be converted to an array, got {type(pvalues).__name__}. Pass a tensor, a "
"NumPy array or a sequence of numbers; join a sequence of tensors with torch.cat."
) from error
# A forced conversion to float64 would parse strings as numbers and turn None into NaN, which
# then disappears with the non-finite entries. Kinds: float, signed, unsigned, boolean.
if values.dtype.kind not in "fiub":
raise InvalidTypeError(
f"pvalues must hold real numbers, got {type(pvalues).__name__} with NumPy dtype {values.dtype}."
)
return values
def _validated_pvalues(pvalues: Tensor | np.ndarray | Sequence[float]) -> np.ndarray:
"""Return the finite p-values as a flat ``float64`` array and check that they lie in [0, 1]."""
values = _real_array(pvalues).astype(np.float64, copy=False).reshape(-1)
values = values[np.isfinite(values)]
if values.size == 0:
raise InvalidParameterError("pvalues must contain at least one finite entry, got none.")
smallest, largest = float(values.min()), float(values.max())
if smallest < 0.0 or largest > 1.0:
raise InvalidParameterError(
f"pvalues must lie in [0, 1], got finite values between {smallest} and {largest}."
)
return values
def _validated_alpha(alpha: float) -> float:
"""Return ``alpha`` as a Python float and check that it lies in the open interval (0, 1)."""
if not isinstance(alpha, Real):
raise InvalidTypeError(f"alpha must be a real number, got {type(alpha).__name__}.")
# The negated comparison also rejects NaN.
if not 0.0 < alpha < 1.0:
raise InvalidParameterError(f"alpha must lie in the open interval (0, 1), got {alpha}.")
return float(alpha)
def _validated_alphas(alphas: Sequence[float]) -> list[float]:
"""Return the levels of a report as Python floats and check each of them."""
# A string is iterable, but as characters. A bare number is the likely slip, because
# binomial_gof takes a single level in the same position.
if isinstance(alphas, (str, bytes)) or not isinstance(alphas, Iterable):
raise InvalidTypeError(
f"alphas must be a sequence of levels, got {type(alphas).__name__}. Pass one level as (alpha,)."
)
return [_validated_alpha(alpha) for alpha in alphas]
def _count_at_most(values: np.ndarray, alpha: float) -> int:
"""Count the p-values at or below ``alpha``."""
return int(np.count_nonzero(values <= alpha))
def _binomial_upper_tail(count: int, n: int, alpha: float) -> float:
"""Return ``P(Bin(n, alpha) >= count)``."""
# The survival function at count - 1 is this tail itself. Taking it as 1 - cdf would lose all
# digits of a small result, which is the interesting case here.
return float(binom.sf(count - 1, n, alpha))
def _ks_upper_tail(values: np.ndarray) -> float:
"""Return the one-sided Kolmogorov-Smirnov p-value of ``D+`` against the uniform distribution."""
n = int(values.size)
largest = float(values.max())
if largest <= 1.0 / n:
# No p-value is above 1/n. Then D+ = 1 - largest, and the tail is the probability that n
# uniform numbers are all at most ``largest``. The tail depends on 1 - D+, which the
# subtraction i/n - p loses: through D+, a result of 1e-40 comes out as an exact 0.
# abs: -0.0 passes the range check, and (-0.0) ** n is -0.0 for odd n.
return abs(largest) ** n
d_plus = float(np.max(np.arange(1, n + 1) / n - np.sort(values)))
if d_plus <= 0.0:
return 1.0
return float(ksone.sf(d_plus, n))
[docs]
def binomial_gof(pvalues: Tensor | np.ndarray | Sequence[float], alpha: float = 0.05) -> float:
"""Test root p-values for an excess of values at or below one level (exact binomial test).
With ``k`` the number of p-values ``<= alpha`` among ``n``, the result is the upper tail
``P(Bin(n, alpha) >= k)``. The test is one-sided: only too many small p-values count against the
circuit.
A **small** result means that the rows are not samples of the circuit (the circuit misfits these
rows). A large result is not a proof of fit. A conservative combination rule can hide a misfit
but cannot cause a false alarm. This is the primary goodness-of-fit statistic, at one level
``alpha`` that is chosen before looking at the p-values. Results at several levels are not
corrected for the selection of the level.
Use the p-values of held-out rows: rows that were used to fit the circuit give optimistic (too
large) p-values. Pass ``float64`` p-values: a ``float32`` 0.05 is slightly above 0.05 and is not
counted at ``alpha = 0.05``.
Args:
pvalues: Root p-values of independent rows, as a tensor (any device), a NumPy array or a
sequence of floats of any shape. The input is flattened and non-finite entries are
removed.
alpha: Level in the open interval (0, 1) at which the p-values are counted.
Returns:
The p-value of the goodness-of-fit test, as a Python float.
Raises:
InvalidParameterError: If ``alpha`` is not in (0, 1), if ``pvalues`` has no finite entry or
if a finite entry lies outside [0, 1].
InvalidTypeError: If ``alpha`` is not a real number, or if ``pvalues`` does not hold real
numbers (for example strings, ``None`` or complex numbers) or cannot be converted to an
array (for example a sequence of tensors that require grad).
ShapeError: If ``pvalues`` is a nested sequence whose parts differ in length.
"""
alpha = _validated_alpha(alpha)
values = _validated_pvalues(pvalues)
return _binomial_upper_tail(_count_at_most(values, alpha), int(values.size), alpha)
[docs]
def ks_gof(pvalues: Tensor | np.ndarray | Sequence[float]) -> float:
"""Test root p-values against the uniform distribution (one-sided Kolmogorov-Smirnov test).
The statistic is ``D+ = max_i (i / n - p_(i))`` with ``p_(i)`` the i-th smallest p-value. It
measures how far the empirical distribution function rises above the uniform one, so the test is
one-sided: only too many small p-values count against the circuit. The result is 1.0 if
``D+ <= 0`` and otherwise the upper tail of the exact finite-sample distribution of ``D+``
(``scipy.stats.ksone``). If no p-value is above ``1 / n``, this tail equals ``p_(n) ** n`` and
is computed in that form, which keeps its relative precision when all p-values are tiny.
A **small** result means that the rows are not samples of the circuit (the circuit misfits these
rows). A large result is not a proof of fit. A conservative combination rule can hide a misfit
but cannot cause a false alarm.
The test assumes a continuous null distribution and is conservative with ties, for example many
rows with ``p = 1`` after clipping or exact p-values of discrete leaves. Treat it as the
secondary statistic and :func:`binomial_gof` at one pre-chosen level as the primary one.
Use the p-values of held-out rows: rows that were used to fit the circuit give optimistic (too
large) p-values. The exact distribution takes about a second for one million p-values.
Args:
pvalues: Root p-values of independent rows, as a tensor (any device), a NumPy array or a
sequence of floats of any shape. The input is flattened and non-finite entries are
removed.
Returns:
The p-value of the goodness-of-fit test, as a Python float.
Raises:
InvalidParameterError: If ``pvalues`` has no finite entry or if a finite entry lies outside
[0, 1].
InvalidTypeError: If ``pvalues`` does not hold real numbers (for example strings, ``None``
or complex numbers) or cannot be converted to an array (for example a sequence of
tensors that require grad).
ShapeError: If ``pvalues`` is a nested sequence whose parts differ in length.
"""
return _ks_upper_tail(_validated_pvalues(pvalues))
[docs]
def gof_report(
pvalues: Tensor | np.ndarray | Sequence[float],
alphas: Sequence[float] = (0.01, 0.05, 0.1),
) -> dict[str, float | int]:
"""Summarize the goodness of fit of root p-values at several levels.
The report holds :func:`ks_gof` and, for every level, the number and the rate of p-values at or
below the level and :func:`binomial_gof` at the level. Both tests are one-sided against an
excess of small p-values. A **small** value means that the rows are not samples of the circuit
(the circuit misfits these rows); large values are not a proof of fit. A conservative
combination rule can hide a misfit but cannot cause a false alarm.
The binomial values at the different levels are not corrected for the selection of the level.
Decide on one level before looking at the report and read the binomial test at that level as the
primary statistic. The Kolmogorov-Smirnov test is the secondary statistic, because it assumes a
continuous null distribution and is conservative with ties (many rows with ``p = 1`` after
clipping, exact p-values of discrete leaves).
Use the p-values of held-out rows: rows that were used to fit the circuit give optimistic (too
large) p-values. Pass ``float64`` p-values: a ``float32`` 0.05 is slightly above 0.05 and is not
counted at the level 0.05.
Args:
pvalues: Root p-values of independent rows, as a tensor (any device), a NumPy array or a
sequence of floats of any shape. The input is flattened and non-finite entries are
removed.
alphas: Levels in the open interval (0, 1), as a sequence. One level is ``(alpha,)``.
Returns:
A flat dictionary with the keys ``"n"`` (number of finite p-values, int), ``"ks_gof"``
(float) and, for every level, ``"count_at_{alpha}"`` (int), ``"rate_at_{alpha}"`` (float)
and ``"binomial_gof_at_{alpha}"`` (float). The level in a key is the shortest decimal form
of the float, for example ``"count_at_0.05"``.
Raises:
InvalidParameterError: If a level is not in (0, 1), if ``pvalues`` has no finite entry or if
a finite entry lies outside [0, 1].
InvalidTypeError: If ``alphas`` is a string or not iterable (for example a single number),
if a level is not a real number, or if ``pvalues`` does not hold real numbers (for
example strings, ``None`` or complex numbers) or cannot be converted to an array (for
example a sequence of tensors that require grad).
ShapeError: If ``pvalues`` is a nested sequence whose parts differ in length.
"""
levels = _validated_alphas(alphas)
values = _validated_pvalues(pvalues)
n = int(values.size)
report: dict[str, float | int] = {"n": n, "ks_gof": _ks_upper_tail(values)}
for alpha in levels:
count = _count_at_most(values, alpha)
report[f"count_at_{alpha}"] = count
report[f"rate_at_{alpha}"] = count / n
report[f"binomial_gof_at_{alpha}"] = _binomial_upper_tail(count, n, alpha)
return report