Membership Circuits (MCs)¶
A Membership Circuit turns a smooth and decomposable probabilistic circuit into a hypothesis test. For every data row it tests the membership hypothesis “this row is a sample of the circuit” and returns a p-value. A small p-value is evidence against the hypothesis, for example because the row is an anomaly or comes from another distribution.
Reference¶
Membership Circuits are described in:
B. Wittelsbach, A. Skryagin, J. Seng, M. Willig and K. Kersting (2026), Membership Circuits: Tractable Membership Testing via Probabilistic Circuits, ICML 2026 Workshop on Hypothesis Testing.
The combination rules are described in:
R. A. Fisher (1932), Statistical Methods for Research Workers, 4th edition (Fisher’s method).
R. J. Simes (1986), An improved Bonferroni procedure for multiple tests of significance, Biometrika 73(3).
V. Vovk and R. Wang (2020), Combining p-values via averaging, Biometrika 107(4) (arithmetic and harmonic mean under arbitrary dependence, multiplier of the harmonic mean).
V. Vovk, B. Wang and R. Wang (2022), Admissible ways of merging p-values under arbitrary dependence, Annals of Statistics 50(1) (Harmonic* and grid harmonic rule, multiplier 2 for two p-values).
Overview¶
The p-value of a row is computed in one bottom-up pass over the circuit:
A leaf turns its observed value into a univariate p-value from its cumulative distribution function (left, right or two-sided).
A product node merges the p-values of its children with a product rule. The children of a product node are independent under the circuit, so rules for independent p-values (Fisher, Simes) are valid here, as are rules that are valid under arbitrary dependence.
A sum node merges the p-values of its children with a sum rule. A row comes from one child only, and only the p-value of that child is known to be valid. The sum rules are valid in this situation.
Every inner node clips its result to \([0, 1]\). The p-value of the root is the result.
The result is a valid p-value: under the membership hypothesis the probability that it falls below a level \(\varepsilon\) is at most \(\varepsilon\). Most rules are conservative, some more than others; the choice of the rules decides the power of the test.
Combination Rules¶
A spflow.zoo.mc.MembershipTestConfig holds one sum rule and one product rule. Both are required; there are no defaults.
Rule |
Node type |
Formula and validity |
|---|---|---|
sum |
\(K \sum_i w_i p_i\); valid at sum nodes. |
|
sum |
\(S \sum_i \sqrt{w_i}\, p_i\) with \(S = \sum_j \sqrt{w_j}\); valid at sum nodes, with the smallest valid constant \(S^2 \le K\). |
|
sum |
\(c \sum_i a_i p_i\) with coefficients from a callable; valid if \(c \ge \sum_i w_i / a_i\), which is checked. |
|
sum, product |
\(\max_i p_i\); valid at every node, very conservative. |
|
product |
\(-2 \sum_i \log p_i\) against \(\chi^2_{2k}\); valid for independent children, exact if their p-values are uniform. |
|
product |
\(\min_i (k / i)\, p_{(i)}\); valid for independent children. |
|
product |
\(k\, p_{(1)}\); valid under any dependence. |
|
product |
\(a_k\) times the harmonic mean; valid under any dependence. |
|
product |
Harmonic* rule, never larger than the harmonic mean rule; valid under any dependence. Under evaluation. |
|
product |
Grid harmonic rule; valid under any dependence. Under evaluation, and more expensive than the other rules. |
Missing Values¶
NaN marks a missing value. A row with missing values is tested on its observed variables only: a node whose variables are all missing is left out, a product node merges its observed children, and a row without any observed value gets the p-value 1. The result equals the p-value under the circuit in which the missing variables are marginalized out. It is a valid test of the observed part of the row only if the missingness does not depend on the values of the row.
Discrete Leaves¶
The p-value of a discrete leaf has three modes (discrete_mode):
"exact": the tail probability includes the probability of the observed value. Valid and conservative."midp": half of the probability of the observed value is counted. The mid-p value is not a valid p-value in general."randomized": a uniform random fraction of the probability of the observed value is counted. The p-value of the leaf is then exactly uniform, at the price of a decision that depends on a random number. Passseedfor reproducible results.
Goodness of Fit¶
The p-values of held-out rows also tell whether the circuit fits the data: if the rows are samples of the circuit, small p-values are not more frequent than under the uniform distribution. spflow.zoo.mc.binomial_gof() and spflow.zoo.mc.ks_gof() test this, and spflow.zoo.mc.gof_report() collects both. A small result means misfit. A large result is no proof of fit, because a conservative combination rule can hide a misfit. Rows that were used to fit the circuit give optimistic p-values and should not be used.
Supported Modules¶
The pass supports Sum, Product, Cat, ElementwiseSum, ElementwiseProduct, OuterProduct, Factorize, RepetitionMixingLayer, the split modules as the input of ElementwiseProduct or OuterProduct, and spflow.zoo.rat.RatSPN. The supported leaf families are Normal, LogNormal, Exponential, Gamma, Laplace, Uniform, Histogram, Bernoulli, Categorical, Poisson, Geometric, Binomial and Hypergeometric. Every other module or leaf raises an UnsupportedOperationError.
Minimal Example¶
import torch
from spflow.meta import Scope
from spflow.modules.leaves import Normal
from spflow.modules.products import Product
from spflow.modules.sums import Sum
from spflow.zoo.mc import (
ArithmeticMeanSqrtW,
HarmonicMean,
MembershipCircuit,
MembershipTestConfig,
gof_report,
)
# A mixture of two product nodes over two variables.
def normal(variable, loc, scale):
return Normal(scope=Scope([variable]), loc=torch.tensor([[[loc]]]), scale=torch.tensor([[[scale]]]))
circuit = Sum(
inputs=[
Product(inputs=[normal(0, 0.0, 1.0), normal(1, 1.0, 2.0)]),
Product(inputs=[normal(0, 4.0, 1.0), normal(1, -2.0, 1.0)]),
],
weights=[0.3, 0.7],
)
config = MembershipTestConfig(sum_rule=ArithmeticMeanSqrtW(), product_rule=HarmonicMean())
mc = MembershipCircuit(circuit, config)
x = torch.tensor(
[
[0.1, 1.5], # typical for the first component
[9.0, 9.0], # far away from both components
[4.2, float("nan")], # second variable missing
]
)
p = mc(x) # one p-value per row, shape (3,)
# Goodness of fit on rows that were not used for training (here: samples of the circuit).
held_out = circuit.sample(num_samples=2000)
report = gof_report(mc(held_out))
Calling mc(x) returns p-values, not log-likelihoods; the log-likelihood of the wrapped circuit is available as mc.log_likelihood(x). The function spflow.zoo.mc.membership_pvalues() computes the same p-values without a wrapper.
API Reference¶
Membership Circuit¶
- class spflow.zoo.mc.MembershipCircuit(module, config, *, validate=True)[source]¶
Bases:
WrapperWrap a probabilistic circuit as a test of the membership hypothesis.
The null hypothesis of a row is that it is a sample of the distribution of the wrapped circuit. Calling the wrapper on data returns one p-value per row; a small p-value is evidence against the hypothesis, for example because the row is an anomaly. The p-values are computed by
spflow.zoo.mc.membership_pvalues(), where the supported modules, the treatment of missing values and the accuracy are described.forwardreturns p-values and not log-likelihoods, unlike every other SPFlow module:mc(data)ismc.pvalues(data). The log-likelihood of the wrapped circuit stays available asmc.log_likelihood(data). Sampling, expectation-maximization and structural marginalization are delegated to the wrapped circuit, so the wrapper can be trained like the circuit itself.- module¶
The wrapped circuit.
- config¶
Test configuration: sum rule, product rule, test side and discrete mode.
- __init__(module, config, *, validate=True)[source]¶
Initialize the wrapper.
- Parameters:
module (
Module) – Circuit with a single root node. It is not copied: later changes of its parameters change the p-values.config (
MembershipTestConfig) – Test configuration.validate (
bool) – IfTrue, the p-value pass runs on a small probe (one complete row, and one row per variable in which only that variable is observed), so that an unsupported module or leaf, a root that is not a single node, a sum node whose children have different scopes and invalid sum-rule coefficients raise here and not at the first use. The time is that of a pass over as many rows as the circuit has variables, plus one. The rows are evaluated in several passes, so that the memory does not grow with the square of the number of variables.
- Raises:
InvalidTypeError – If
moduleis not a module orconfigis not aMembershipTestConfig.ShapeError – With
validate, if the circuit does not have a single root node.StructureError – With
validate, if the children of a sum node have different scopes.UnsupportedOperationError – With
validate, if the circuit contains a module or a leaf that is not supported.InvalidWeightsError – With
validate, if the weights of a sum module are not finite.InvalidParameterError – With
validate, if the coefficients of the sum rule are not valid. Degenerate leaf parameters are found only if they show at the probe value 0.
- forward(data, *, seed=None)[source]¶
Return the membership p-values of the rows of
data, seepvalues().This differs from the other SPFlow modules, whose forward pass is the log-likelihood.
- Return type:
- marginalize(marg_rvs, prune=True, cache=None)[source]¶
Marginalize variables out of the wrapped circuit and wrap the result with the same test.
The structural marginalization is that of the wrapped circuit and has its limits: several layer modules do not implement it. Missing values in the data (NaN) need no structural marginalization and work for every supported circuit.
- Parameters:
- Return type:
- Returns:
Membership circuit over the remaining variables, or
Noneif no variable remains. It is validated when it is built if and only if this wrapper was.
- pvalues(data, *, seed=None)[source]¶
Compute the membership p-value of every row of
data.- Parameters:
data (
Tensor) – Rows to test, of shape(N, D); columnjholds variablej. NaN marks a missing value: the row is then tested on its observed variables only. The missingness must be independent of the values.seed (
int|None) – Seed of the random numbers ofdiscrete_mode="randomized";Noneuses the global random number generator of torch. Two calls with the same seed use the same numbers: evaluate a data set in one call, or use another seed for every batch. Ignored in the other modes, apart from the check of its type and range.
- Return type:
- Returns:
P-values of shape
(N,)infloat64, without gradients. Seespflow.zoo.mc.membership_pvalues()for the details and the exceptions.
- sample(num_samples=None, data=None, is_mpe=False, cache=None, return_leaf_params=False)[source]¶
Sample from the wrapped circuit.
The call goes to the public
sampleof the wrapped circuit and not to its_samplehook, because a circuit such asRatSPNprepares the sampling context insample.- Parameters:
data (
Tensor|None) – Tensor with NaN at the entries to sample; other entries are evidence.is_mpe (
bool) – IfTrue, return the most probable values instead of random samples.cache (
Cache|None) – Optional cache for intermediate results.return_leaf_params (
bool) – IfTrue, also return the leaf parameters of the samples.
- Return type:
- Returns:
Samples of shape
(N, D), with the leaf-parameter records if requested.
- spflow.zoo.mc.membership_pvalues(model, data, config, *, seed=None)[source]¶
Compute the membership p-value of every row of
dataunder a circuit.The null hypothesis of a row is that it is a sample of the distribution of
model. A small p-value is evidence against it. The p-value is valid (its probability to fall below a level is at most that level under the null hypothesis) if the rules ofconfigare valid for their node type; all rules of this package are, except thatdiscrete_mode="midp"gives no guarantee.The pass runs in
float64and without gradients, whatever the dtype of the model. The model is not moved, cast or modified. The parameters are read as they are: the accuracy of the p-values of afloat32model is limited by its rounded parameters, seespflow.zoo.mc.leaf_pvalues().Supported modules:
Sum,RepetitionMixingLayer,ElementwiseSum,Product,ElementwiseProduct,OuterProduct,Factorize,Cat, the three split modules as the direct input ofElementwiseProductorOuterProduct,RatSPNand the leaf families ofspflow.zoo.mc.leaf_pvalues(). The circuit must be smooth and decomposable. ARepetitionMixingLayerover an input with a single repetition counts one child per weight; its p-value is valid, but up to K times larger than that of the input.- Parameters:
model (
Module) – Circuit with a single root node, that is with output shape(1, 1, 1).data (
Tensor) – Rows to test, of shape(N, D)with one column per variable; columnjholds variablejof the scope of the model. NaN marks a missing value: the row is then tested on its observed variables only (marginal semantics). The missingness must be independent of the values. A row without any observed value gets the p-value 1.config (
MembershipTestConfig) – Test configuration: sum rule, product rule, test side and discrete mode.seed (
int|None) – Seed of the random numbers ofdiscrete_mode="randomized". One number is drawn per row and column ofdata(also for columns outside the scope of the model), on the CPU, so that the result does not depend on the device or on the structure of the circuit. It does depend on the position of a row indataand on the number of columns. Two calls with the same seed use the same numbers: evaluate a data set in one call, or use another seed for every batch.Noneuses the global random number generator of torch. Ignored in the other modes, apart from the check of its type and range.
- Return type:
- Returns:
P-values of shape
(N,)infloat64, in[0, 1], on the device of the model and without gradients.- Raises:
InvalidTypeError – If
modelis not a module,configis not aMembershipTestConfig,datais not a real-valued tensor (for example interval evidence),seedis not an integer, or a combination rule returns something else than afloat64tensor.ShapeError – If
datais not two-dimensional or has fewer columns than the scope of the model needs, if the model does not have a single root node, if the shapes of the inputs of a module do not fit together, or if a combination rule does not return one p-value per node.StructureError – If the children of a sum node do not have the same scope, so that a row with missing values is missing for some children only (the sum is not smooth).
UnsupportedOperationError – If the circuit contains a module or a leaf that is not supported.
InvalidWeightsError – If the weights of a sum module are not finite.
InvalidParameterError – If
seedlies outside[-2**63, 2**64 - 1], if a leaf has degenerate parameters, if the coefficients of the sum rule fail their validity check or if a p-value is NaN.
- class spflow.zoo.mc.MembershipTestConfig(sum_rule, product_rule, side='both', discrete_mode='exact')[source]¶
Bases:
objectConfiguration of a membership test.
- sum_rule¶
Combination rule used at every sum node.
- product_rule¶
Combination rule used at every product node.
- side¶
Test side of every leaf.
"left"rejects small values,"right"rejects large values and"both"rejects values in either tail.
- discrete_mode¶
P-value definition at discrete leaves.
"exact"is valid and conservative."midp"counts half of the observed atom and is not a valid p-value in general."randomized"is exactly uniform under the leaf distribution, at the price of a random decision.
- Raises:
InvalidTypeError – If
sum_ruleis not aSumCombinationorproduct_ruleis not aProductCombination, or if thenameof a rule is not a non-empty string.InvalidParameterError – If
sideordiscrete_modehas an unknown value.
- name()[source]¶
Return a stable identifier of the configuration.
- Return type:
- Returns:
"{side}_S_{sum rule}_P_{product rule}", followed by"_D_{discrete_mode}"if the discrete mode is not"exact".
- product_rule: ProductCombination¶
- sum_rule: SumCombination¶
Sum Rules¶
- class spflow.zoo.mc.ArithmeticMeanK[source]¶
Bases:
WeightedArithmeticMeanAM-k rule: the weighted mean of the child p-values times the number of children.
Formula:
p = K * sum_i w_i * p_i, theWeightedArithmeticMeanwitham_k_coefficients().Kcounts every child of the sum node, also a child with weight zero.Validity: valid at sum nodes under the mixture null, for any dependence between the children.
- class spflow.zoo.mc.ArithmeticMeanSqrtW[source]¶
Bases:
WeightedArithmeticMeanAM-sqrtW rule: arithmetic mean with square-root coefficients and the smallest valid constant.
Formula:
p = S * sum_i sqrt(w_i) * p_iwithS = sum_j sqrt(w_j), theWeightedArithmeticMeanwitham_sqrtw_coefficients(). The constantS^2is at mostK; the rule equals AM-k for uniform weights and tends to the p-value of the dominant child if one weight tends to 1.Validity: valid at sum nodes under the mixture null, for any dependence between the children.
- class spflow.zoo.mc.WeightedArithmeticMean(coefficients, name, check_validity=True)[source]¶
Bases:
SumCombinationWeighted arithmetic mean of the child p-values with coefficients from a callable.
Formula:
p = c * sum_i a_i * p_iwith(a, c) = coefficients(weights, context). The coefficient function is called once per call ofcombine(), that is once per sum module and not once per row.Validity: under the model null a row comes from child
iwith probabilityw_i, and only the p-value of that child is known to be valid. The rule is a valid test in this situation, without any assumption on the dependence between the children, ifc >= sum_i w_i / a_iwitha_i > 0whereverw_i > 0: given componentithe result is at leastc * a_i * p_i, so it falls belowepswith probability at mosteps / (c * a_i), and the mixture overigives at mosteps * sum_i w_i / (c * a_i) <= eps. Withcheck_validity=Truethis inequality is tested (with a relative tolerance of 1e-9) on every call.- coefficients¶
Function
(weights, context) -> (a, c).weightsare the normalized mixture weights of shape(..., K)infloat64,aare non-negative coefficients of the same shape andcis a positive constant per sum node of shape(...).
- name¶
Stable short identifier of the rule.
- __init__(coefficients, name, check_validity=True)[source]¶
Initialize the rule.
- Parameters:
coefficients (
Callable[[Tensor,SumNodeContext],tuple[Tensor,Tensor]]) – Function(weights, context) -> (a, c), see the class documentation.name (
str) – Stable short identifier of the rule, used in configuration names.check_validity (
bool) – IfTrue,combine()raises when the coefficients violate the validity conditionc >= sum_i w_i / a_i. Switch it off only for a null hypothesis that differs from the mixture null on purpose. The check never changes the result.
- Raises:
InvalidTypeError – If
coefficientsis not callable ornameis not a string.InvalidParameterError – If
nameis empty.
- combine(p, *, weights=None, observed=None, context=None)[source]¶
Return
c * sum_i a_i * p_ifor each sum node.- Parameters:
p (
Tensor) – Child p-values with the children on the last axis, shape(..., K).weights (
Tensor|None) – Normalized mixture weights of shape(..., K). Required.observed (
Tensor|None) – Boolean mask, broadcastable top. A sum node has either all children observed or none, so the mask only selects the rows without any observed child, which give exactly 1. Rows with some observed children are merged over allKchildren.Nonemeans that all entries are observed.context (
SumNodeContext|None) – Information about the sum nodes for the coefficient function. Defaults toSumNodeContext(num_children=K).
- Return type:
- Returns:
Merged p-values in
float64, not clipped, with the leading axes ofpbroadcast againstweights.shape[:-1].- Raises:
InvalidParameterError – If
weightsis missing, or ifcheck_validityis set and the coefficients violate the validity condition.InvalidTypeError – If
observedis not a boolean tensor or the coefficient function does not return a tuple of two tensors.ShapeError – If
weightsorobserveddoes not fit top, or the coefficients do not have the shapesweights.shapeandweights.shape[:-1].
- spflow.zoo.mc.am_k_coefficients(weights, context)[source]¶
Return the coefficients of the AM-k rule:
a_i = w_iandc = K.sum_i w_i / a_iis the number of children with a positive weight, so the validity condition holds with equality if all weights are positive. A child with weight zero is counted inK.- Parameters:
weights (
Tensor) – Normalized mixture weights with the children on the last axis, shape(..., K).context (
SumNodeContext) – Information about the sum nodes;context.num_childrenisK.
- Return type:
- Returns:
Tuple
(a, c)withaof shape(..., K)andcof shape(...).
- spflow.zoo.mc.am_sqrtw_coefficients(weights, context)[source]¶
Return the coefficients of the AM-sqrtW rule:
a_i = sqrt(w_i) / Sandc = S^2.S = sum_j sqrt(w_j). Among all coefficients that sum to 1 these give the smallest constant that satisfies the validity condition,c = sum_i w_i / a_i = S^2 <= K. The coefficients and the constant belong together:a = wwithc = S^2is not valid.- Parameters:
weights (
Tensor) – Normalized mixture weights with the children on the last axis, shape(..., K).context (
SumNodeContext) – Information about the sum nodes. Not used.
- Return type:
- Returns:
Tuple
(a, c)withaof shape(..., K)andcof shape(...).
- class spflow.zoo.mc.SumNodeContext(num_children, module=None, scope=None)[source]¶
Bases:
objectRead-only information about the sum nodes that a coefficient function serves.
- num_children¶
Number of children
Kof each sum node (the fan-in).
- module¶
Sum module that holds the nodes, if the rule is called from a circuit pass.
- scope¶
Joint scope of the module, if the rule is called from a circuit pass.
- class spflow.zoo.mc.MaxP[source]¶
Bases:
SumCombination,ProductCombinationMaximum of the child p-values, the only rule that is valid at every node type.
Formula:
p = max_i p_iover the observed children.Validity: at a sum node the maximum is at least the p-value of the mixture component that generated the row, and that p-value is valid. At a product node the maximum is at least the p-value of every single child, so the rule is valid under any dependence between the children (the intersection-union test). It rejects only if every child rejects, which makes it very conservative.
- combine(p, *, weights=None, observed=None, context=None)[source]¶
Return the maximum of the observed child p-values of each node.
- Parameters:
p (
Tensor) – Child p-values with the children on the last axis, shape(..., K).weights (
Tensor|None) – Mixture weights of shape(..., K)if the rule is used at sum nodes. Only their shape is used: the result is broadcast to their leading axes. At a sum node every child enters the maximum, whatever its weight, also a child with weight zero.observed (
Tensor|None) – Boolean mask, broadcastable top.Nonemeans that all entries are observed.context (
SumNodeContext|None) – Ignored.
- Return type:
- Returns:
Maximum over the observed children in
float64, with shapep.shape[:-1], or that shape broadcast againstweights.shape[:-1]ifweightsis given (as a view that must not be written to). A row without an observed child gives exactly 1; a row with a NaN at an observed child gives NaN.- Raises:
InvalidTypeError – If
observedis not a boolean tensor.ShapeError – If
phas no children axis, orobservedorweightsdoes not fit top.
Product Rules¶
All product rules are spflow.zoo.mc.ProductCombination rules and follow its conventions.
- class spflow.zoo.mc.Fisher[source]¶
Fisher’s method: the sum of the log p-values against a chi-squared distribution.
Formula:
T = -2 * sum_i log(max(p_i, 1e-300))andp = Q(k, T / 2), wherekis the number of observed children andQis the regularized upper incomplete gamma function, that is the survival function of the chi-squared distribution with2 * kdegrees of freedom.Validity: valid if the children are independent, which holds at a product node under the model null, and exact if their p-values are uniform in addition. It is not valid under arbitrary dependence between the children.
Accuracy: the upper tail is computed directly with
torch.special.gammaincc. That function has a relative error of about 2e-9 for more than 20 children whenT / 2is within 30 percent ofk; elsewhere the relative error is at most about 5e-13 for up to 250 children and about 2e-15 timeskfor more (2e-12 for 1000 children). The rule is therefore non-decreasing in its inputs only up to floating-point rounding. The inputs must not exceed 1: if their product exceeds 1, the result is NaN.
- class spflow.zoo.mc.Simes[source]¶
Simes’ method.
Formula:
p = min_i (k / i) * p_(i)overi = 1, ..., k, wherekis the number of observed children andp_(1) <= ... <= p_(k)are their sorted p-values. The termi = 1is Bonferroni’s method, so the result is never larger than that ofBonferroni.Validity: valid if the children are independent, which holds at a product node under the model null (exact for uniform p-values), and also under positive regression dependence. It is not valid under arbitrary dependence between the children.
- class spflow.zoo.mc.Bonferroni[source]¶
Bonferroni’s method: the smallest p-value times the number of children.
Formula:
p = k * p_(1), wherekis the number of observed children andp_(1)is the smallest of their p-values.Validity: valid under any dependence between the children. Under independence it is slightly conservative.
- class spflow.zoo.mc.HarmonicMean[source]¶
Harmonic mean of the child p-values with the multiplier of Vovk and Wang (2020).
Formula:
p = a_k * k / sum_i (1 / max(p_i, 1e-300)), wherekis the number of observed children,a_1 = 1,a_2 = 2anda_k = (y_k + k)^2 / ((y_k + 1) * k)fork >= 3withy_kthe positive root ofy^2 = k * ((y + 1) * log(y + 1) - y)(spflow.zoo.mc.constants.harmonic_mean_multiplier()).a_kis the full multiplier.Validity: valid under any dependence between the children; conservative under independence. The value
a_2 = 2is required for that: the smaller constante * log(2)is slightly anti-conservative under adversarial dependence.Reference: V. Vovk and R. Wang (2020), “Combining p-values via averaging”, Biometrika 107(4) (arXiv:1212.4966), for
a_kwithk >= 3; V. Vovk, B. Wang and R. Wang (2022), “Admissible ways of merging p-values under arbitrary dependence”, Annals of Statistics (arXiv:2007.14208), Proposition 8.1, fora_2 = 2.
- class spflow.zoo.mc.HarmonicMeanStar[source]¶
Harmonic* rule of Vovk, Wang and Wang (2022), an admissible improvement of the harmonic mean.
Formula for
k >= 3observed children with sorted p-valuesp_(1) <= ... <= p_(k):p = min(1, min over m = 1..k of (1/c + (m - 1)/d) / sum_{j <= m} 1 / p_(j))
with
1/c = y_k + kand1/d = (y_k + k) / (y_k + 1),y_kas inHarmonicMean. Fork = 2the rule ismin(2 * p_(1), 1). The result is exactly 0 if an observed input is exactly 0. The termm = kis the value ofHarmonicMean, so the result is never larger than that. Before the clip at 1 it is equal to that value for equal inputs and never smaller thandtimes that value.Validity: valid under any dependence between the children; conservative under independence.
Status: this rule is an option under evaluation.
Inputs below 1e-300 do not occur in a circuit pass: leaf p-values are at least 1e-300, and this rule and every valid sum rule return at least their smallest input (up to rounding). In a direct call with such inputs two properties are lost. First,
HarmonicMeanraises its inputs to 1e-300 and this rule does not, so the two rules are no longer equal for equal inputs and the boundddoes not hold. Second, a term whose sum of reciprocals overflows (formequal inputs: below aboutm * 5.6e-309) is left out of the minimum, so that the termm = 1decides. The result is then still a valid p-value, but it is only an upper bound of the formula and it is not monotone: raising an input can bring a term back into the minimum and lower the result.Reference: V. Vovk, B. Wang and R. Wang (2022), “Admissible ways of merging p-values under arbitrary dependence”, Annals of Statistics (arXiv:2007.14208), Theorem 8.2 and Proposition 8.4 with
r = -1.
- class spflow.zoo.mc.GridHarmonic[source]¶
Grid harmonic rule
H*of Vovk, Wang and Wang (2022).Formula for
kobserved children withl_k = 1 + 1/2 + ... + 1/k:inside(eps) <=> sum_i [l_k * p_i <= eps] / ceil(k * l_k * p_i / eps) >= 1 p = min(1, inf{eps > 0 : inside(eps)})
The result is exactly 0 if an observed input is exactly 0. Before the clip it lies between
l_ktimes the harmonic mean of the inputs and Hommel’s boundl_k * min_i (k / i) * p_(i); fork <= 3it equals Hommel’s bound, which is then returned directly. It is not ordered againstHarmonicMeanorHarmonicMeanStar.Validity: valid under any dependence between the children; conservative under independence.
Status: this rule is an option under evaluation.
Numerics: for
k >= 4the infimum is located by 56 bisection steps on the logarithm ofepsbetween the two bounds, and the upper end is returned. The test of the sum allows for rounding (>= 1 - 4 * k * 2.2e-16), because a floating-point sum of unit fractions can fall just below 1 when the exact sum is 1. The allowance also accepts anepswhose exact sum is below 1 by less than that amount; this is possible only for more than 30 children and was not seen on random inputs. The result is then below the formula by a relative amount of up to1 / n, withnthe largest denominator in the sum, and the level of the test grows by a relative amount of at most about5 * k * 2.2e-16. The relative resolution is near machine precision for moderate results and about 1.5e-13 near 1e-300, where the logarithm loses digits. The rule is a step function of its inputs: it has no useful gradient, and it is non-decreasing in its inputs only up to floating-point rounding. If the sum of the reciprocals of the inputs overflows (for equal inputs: below aboutk * 5.6e-309, which does not occur in a circuit pass with leaf p-values of at least 1e-300), Hommel’s bound is returned. It is a valid p-value, but only an upper bound of the formula, and the rule is not monotone across this limit.Cost: about 56 passes over the children per node, against one sort for the other harmonic rules. A full pass over a RAT-SPN with 64 to 784 variables took 5 to 10 times as long as with
HarmonicMean(measured on a CPU).Reference: V. Vovk, B. Wang and R. Wang (2022), “Admissible ways of merging p-values under arbitrary dependence”, Annals of Statistics (arXiv:2007.14208), Section 7 with Theorem 7.1.
Rule Interfaces¶
- class spflow.zoo.mc.PValueCombination[source]¶
Bases:
ABCAbstract base class of all p-value combination rules.
Subclasses are stateless and must be non-decreasing in every input (up to floating-point rounding).
- name¶
Stable short identifier of the rule, used in configuration names.
- abstractmethod combine(p, *, weights=None, observed=None, context=None)[source]¶
Merge the p-values of the children of each node.
- Parameters:
p (
Tensor) – Child p-values with the children on the last axis, shape(..., K). The tensor is not modified.weights (
Tensor|None) – Normalized mixture weights with the children on the last axis, shape(..., K), broadcastable againstpin the leading axes. Used by sum rules only.observed (
Tensor|None) – Boolean mask, broadcastable top.Falsemarks an entry that is not a child with a p-value for this row. Values ofpat such entries are arbitrary. Product rules andMaxPignore them. The children of a sum node are observed together or not at all, so the arithmetic-mean rules use the mask only to return 1 for a row without an observed child and merge allKentries of every other row.Nonemeans that all entries are observed.context (
SumNodeContext|None) – Information about the sum nodes for coefficient functions. Used by sum rules only.
- Return type:
- Returns:
Merged p-values with the children axis removed, in
float64. The result is not clipped to[0, 1]unless the formula of the rule contains the clip; the node clips.
- class spflow.zoo.mc.SumCombination[source]¶
Bases:
PValueCombination,ABCAbstract base class of the rules that are valid at sum nodes.
- class spflow.zoo.mc.ProductCombination[source]¶
Bases:
PValueCombination,ABCAbstract base class of the rules that are valid at product nodes.
Per row a product rule merges the observed children only, with their number
k_obsin place ofKin every constant of its formula. The product rules of this package share three conventions: a row with one observed child gives the p-value of that child unchanged, a row without an observed child gives exactly 1, and a row with a NaN at an observed child gives NaN. Their inputs must lie in[0, 1].
Leaf P-Values¶
- spflow.zoo.mc.leaf_pvalues(leaf, x, *, side='both', discrete_mode='exact', uniforms=None)[source]¶
Compute the p-values of observed values under the distributions of a leaf module.
With
L = P(X < x),A = P(X = x)andR = P(X > x)under one leaf distribution, the left p-value isL + wl * Aand the right p-value isR + wr * A. Continuous families have no atom (A = 0) and ignorediscrete_mode. For discrete families the mode sets the weights:"exact":wl = wr = 1. The p-value is valid and conservative by up to one atom. The right p-value isP(X >= x): it includes the observed atom."midp":wl = wr = 0.5. The mid-p value is not a valid p-value in general: for a Bernoulli leaf with success probability 0.5 andside="both"it equals 0.5 for both outcomes."randomized":wl = 1 - uandwr = uwith the givenuin[0, 1). Foruuniform and independent of the row, the p-value is exactly uniform under the leaf distribution. The price is a decision that depends on the random number. The left and the right p-value of one observation use the sameuand sum to 1.
side="left"returns the left p-value,side="right"the right one andside="both"returns2 * min(left, right). The result is clamped to[1e-300, 1]; the upper limit is necessary because a two-sided exact p-value of a discrete leaf can exceed 1.The values of a Categorical leaf have no order. Its p-value is the minimum-likelihood p-value, the same for every side:
lt + w * eqwithw = 1(exact),0.5(mid-p) oru(randomized), whereltis the probability of all categories that are less likely than the observed one andeqthe probability of all categories that are exactly as likely (the observed one included). The comparison uses the model’s ownfloat64probabilities. A value that is not one of the categories0, ..., K - 1gets the smallest p-value1e-300.No real value of
xraises. For the ordered discrete families (Bernoulli, Poisson, Geometric, Binomial, Hypergeometric), a value that is not an integer or lies outside the support has no atom and usesL = P(X < x)andR = P(X > x)as they are: 2.5 at a Poisson leaf gives the left p-valueP(X <= 2)and the right p-valueP(X >= 3). Continuous families treat a value outside their support in the same way (L = 0below the support,R = 0above it). Infinite values are accepted.Accuracy: all computations use
float64, whatever the dtype of the leaf. A leaf withfloat32parameters is evaluated at its rounded parameter values. Compared with the unrounded values, this limits the relative accuracy of its p-values to about 1e-6 near the centre of the distribution and to about 1e-4 in deep tails, where the rounding of the parameters is amplified. The incomplete gamma functions of torch (used by Gamma and Poisson) have a relative error of about 2e-9 where the shape argument is above 20 and the second argument lies within 30 percent of it (within 32 percent for shapes between 200 and 225). The shape argument is the concentration of a Gamma leaf, withrate * xas the second argument, and aboutxfor a Poisson leaf, with the rate as the second argument. Where the power series of torch for the lower incomplete gamma function stops before it has converged (a shape above about 3e5 and a second argument more than 4.5 standard deviations below it), a uniform asymptotic expansion is used instead. For shape arguments above 1e7 the error grows with the shape: for a Gamma leaf to about 4e-10 at 1e10, 5e-9 at 1e12 and 7e-8 at 4e14; for a Poisson leaf, whose atom loses digits in addition, to about 2e-9 at 1e9, 1e-7 at 1e12 and 7e-6 at 4e14. Binomial and Hypergeometric leaves build a table of the probability mass function over their support in every call, with a size proportional to the largest support. The relative error of these two families is about 1e-15 times the largest count (the number of trials or the population size): about 4e-12 for a count of 1e4 and 6e-10 for a count of 1e6. In all other cases the relative error is well below 1e-9. A Histogram leaf stores its bin edges infloat32, so its p-values refer to the rounded edges; its bin probabilities aresoftmax(logits).- Parameters:
leaf (
LeafModule) – Leaf module of a supported family: Normal, LogNormal, Exponential, Gamma, Laplace, Uniform, Histogram, Bernoulli, Categorical, Poisson, Geometric (number of failures before the first success), Binomial or Hypergeometric.x (
Tensor) – Observed values of shape(N, F): the columns of the leaf in the order ofleaf.scope.query, without NaN. The caller handles missing values and masks the result. The tensor is cast tofloat64and moved to the device of the leaf.side (
Literal['both','left','right']) – Test side."left"rejects small values,"right"rejects large values and"both"rejects values in either tail.discrete_mode (
Literal['exact','midp','randomized']) – P-value definition at discrete leaves, see above.uniforms (
Tensor|None) – Random numbers in[0, 1)of shape(N, F), one per row and feature, shared by all channels and repetitions. Required if and only ifdiscrete_modeis"randomized".
- Return type:
- Returns:
P-values of shape
(N, F, C, R)with(F, C, R) = leaf.out_shape, infloat64on the device of the leaf, clamped to[1e-300, 1]and without gradients.- Raises:
InvalidTypeError – If
leafis not a leaf module orxis not a real-valued tensor.InvalidParameterCombinationError – If
uniformsis missing in randomized mode or given in another mode.InvalidParameterError – If
sideordiscrete_modeis unknown, ifuniformsis not in[0, 1), ifxcontains NaN, if a parameter of the leaf lies outside the supported range (a Poisson rate above 5e14, a Gamma concentration above 1e15, a number of trials of a Binomial leaf that is negative, not finite or not an integer, a count of a Hypergeometric leaf that is not finite, a Uniform leaf whosehighis not larger thanlowor whose widthhigh - lowis infinite), or if a tail probability is NaN because the parameters of the leaf are degenerate (NaN, or a rate, scale or width that is zero or infinite infloat64, which afloat32leaf reaches when the exponential of its log-parameter underflows or overflows).ShapeError – If
xis not(N, F), ifuniformsdoes not have the shape ofx, or if the parameters of the leaf do not have the shape (features, channels, repetitions), so that the result would not have the shape(N, F, C, R).UnsupportedOperationError – If the leaf family is not supported, if the leaf is conditional or if its class overrides
log_likelihood.
Goodness of Fit¶
- spflow.zoo.mc.binomial_gof(pvalues, alpha=0.05)[source]¶
Test root p-values for an excess of values at or below one level (exact binomial test).
With
kthe number of p-values<= alphaamongn, the result is the upper tailP(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
alphathat 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
float64p-values: afloat320.05 is slightly above 0.05 and is not counted atalpha = 0.05.- Parameters:
pvalues (
Tensor|ndarray|Sequence[float]) – 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 (
float) – Level in the open interval (0, 1) at which the p-values are counted.
- Return type:
- Returns:
The p-value of the goodness-of-fit test, as a Python float.
- Raises:
InvalidParameterError – If
alphais not in (0, 1), ifpvalueshas no finite entry or if a finite entry lies outside [0, 1].InvalidTypeError – If
alphais not a real number, or ifpvaluesdoes not hold real numbers (for example strings,Noneor complex numbers) or cannot be converted to an array (for example a sequence of tensors that require grad).ShapeError – If
pvaluesis a nested sequence whose parts differ in length.
- spflow.zoo.mc.ks_gof(pvalues)[source]¶
Test root p-values against the uniform distribution (one-sided Kolmogorov-Smirnov test).
The statistic is
D+ = max_i (i / n - p_(i))withp_(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 ifD+ <= 0and otherwise the upper tail of the exact finite-sample distribution ofD+(scipy.stats.ksone). If no p-value is above1 / n, this tail equalsp_(n) ** nand 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 = 1after clipping or exact p-values of discrete leaves. Treat it as the secondary statistic andbinomial_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.
- Parameters:
pvalues (
Tensor|ndarray|Sequence[float]) – 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.- Return type:
- Returns:
The p-value of the goodness-of-fit test, as a Python float.
- Raises:
InvalidParameterError – If
pvalueshas no finite entry or if a finite entry lies outside [0, 1].InvalidTypeError – If
pvaluesdoes not hold real numbers (for example strings,Noneor complex numbers) or cannot be converted to an array (for example a sequence of tensors that require grad).ShapeError – If
pvaluesis a nested sequence whose parts differ in length.
- spflow.zoo.mc.gof_report(pvalues, alphas=(0.01, 0.05, 0.1))[source]¶
Summarize the goodness of fit of root p-values at several levels.
The report holds
ks_gof()and, for every level, the number and the rate of p-values at or below the level andbinomial_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 = 1after 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
float64p-values: afloat320.05 is slightly above 0.05 and is not counted at the level 0.05.- Parameters:
pvalues (
Tensor|ndarray|Sequence[float]) – 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 (
Sequence[float]) – Levels in the open interval (0, 1), as a sequence. One level is(alpha,).
- Return type:
- 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
pvalueshas no finite entry or if a finite entry lies outside [0, 1].InvalidTypeError – If
alphasis a string or not iterable (for example a single number), if a level is not a real number, or ifpvaluesdoes not hold real numbers (for example strings,Noneor complex numbers) or cannot be converted to an array (for example a sequence of tensors that require grad).ShapeError – If
pvaluesis a nested sequence whose parts differ in length.