Non-Paired Model¶
Independent Beta-Bernoulli A/B test with exact Savage-Dickey Bayes factor.
The sequential variant SequentialNonPairedBayesPropTest is documented on
the Sequential designs page.
bayes_nonpaired
¶
Non-paired Bayesian A/B test using conjugate Beta-Bernoulli model.
This module provides :class:NonPairedBayesPropTest for comparing two
independent groups via binarized pass/fail counts with a Beta-Bernoulli
conjugate model, Savage-Dickey Bayes factor on the difference of
proportions, posterior predictive checks, and publication-ready plots.
Also provides :func:descriptive_summary for building a combined
descriptive statistics + threshold-sweep summary table.
Typical workflow::
from bayesprop.resources.bayes_nonpaired import NonPairedBayesPropTest, descriptive_summary
bb = NonPairedBayesPropTest(threshold=0.5)
result = bb.test(scores_A, scores_B)
df = descriptive_summary(scores_dict, thresholds=[0.5, 0.7, 0.8, 0.9, 0.95])
NonPairedBayesPropTest(alpha0=1.0, beta0=1.0, threshold=0.5, n_quad=100, seed=0, n_samples=20000, verbose=False, decision_rule='all', rope_epsilon=0.02)
¶
Bases: BaseBayesPropTest
Non-paired Bayesian A/B test using conjugate Beta-Bernoulli model.
Workflow
- Binarize continuous scores at a threshold.
- Update Beta(alpha0, beta0) prior with observed pass/fail counts.
- Compute posterior probability of superiority P(theta_B > theta_A) via Gauss-Legendre quadrature.
Initialise the Beta-Bernoulli proportion test.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alpha0
|
float
|
Prior alpha parameter for the Beta distribution. |
1.0
|
beta0
|
float
|
Prior beta parameter for the Beta distribution. |
1.0
|
threshold
|
float
|
Binarization threshold for continuous scores. |
0.5
|
n_quad
|
int
|
Number of Gauss-Legendre quadrature nodes. |
100
|
seed
|
int
|
Random seed for Monte Carlo sampling. |
0
|
n_samples
|
int
|
Number of Monte Carlo draws for difference posterior. |
20000
|
verbose
|
bool
|
If True, print diagnostic messages. |
False
|
decision_rule
|
DecisionRuleType
|
Default decision framework — one of
|
'all'
|
rope_epsilon
|
float
|
Half-width of the ROPE interval (default 0.02 = 2 pp). |
0.02
|
Source code in bayesprop/resources/bayes_nonpaired.py
__repr__()
¶
Return an informative string representation.
Source code in bayesprop/resources/bayes_nonpaired.py
_binarize(y)
¶
Return y unchanged if already binary, else binarize at self.threshold.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
ndarray
|
Array of scores. If all values are 0.0 or 1.0 the array
is returned as-is; otherwise values ≥ |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Binary array of the same length as y. |
Source code in bayesprop/resources/bayes_nonpaired.py
prob_greater(a1, b1, a2, b2)
¶
Posterior probability of superiority P(theta1 > theta2) via Gauss-Legendre quadrature.
Computes:
where \(f_{\theta_1}\) is the Beta(a1, b1) PDF and \(F_{\theta_2}\) is the Beta(a2, b2) CDF (regularized incomplete Beta function).
Uses np.log1p(-x) instead of np.log(1 - x) for improved
numerical stability near x = 1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a1
|
float
|
Alpha parameter of the first Beta distribution. |
required |
b1
|
float
|
Beta parameter of the first Beta distribution. |
required |
a2
|
float
|
Alpha parameter of the second Beta distribution. |
required |
b2
|
float
|
Beta parameter of the second Beta distribution. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Posterior probability of superiority, i.e. the probability |
float
|
that a draw from Beta(a1, b1) exceeds a draw from Beta(a2, b2). |
Source code in bayesprop/resources/bayes_nonpaired.py
test(y_a, y_b)
¶
Run the Beta-Bernoulli test. Auto-binarizes if scores are not 0/1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_a
|
ArrayLike
|
Scores for group A (continuous or binary). |
required |
y_b
|
ArrayLike
|
Scores for group B (continuous or binary). |
required |
Returns:
| Type | Description |
|---|---|
NonPairedTestResult
|
class: |
NonPairedTestResult
|
and posterior probability of superiority P(theta_B > theta_A). |
Source code in bayesprop/resources/bayes_nonpaired.py
fit(y_a, y_b)
¶
Fit Beta posteriors and sample difference posterior via Monte Carlo.
This extends :meth:test by also drawing from the individual
Beta posteriors to build the posterior of Δ = p_A − p_B, which
enables Savage-Dickey Bayes factors, posterior predictive checks,
and richer summaries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_a
|
ArrayLike
|
Scores for group A (continuous or binary). |
required |
y_b
|
ArrayLike
|
Scores for group B (continuous or binary). |
required |
Returns:
| Type | Description |
|---|---|
NonPairedBayesPropTest
|
self (for method chaining). |
Source code in bayesprop/resources/bayes_nonpaired.py
_check_fitted()
¶
Raise RuntimeError if .fit() has not been called.
savage_dickey_test(null_value=0.0)
¶
Savage-Dickey density-ratio Bayes factor for H0: Δ = null_value.
The prior on Δ = p_A − p_B is induced by the independent
Beta(α₀, β₀) priors. Densities are computed via exact
log-space convolution (:func:beta_diff_pdf).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
null_value
|
float
|
The point null hypothesis value for Δ. |
0.0
|
Returns:
| Type | Description |
|---|---|
SavageDickeyResult
|
class: |
SavageDickeyResult
|
interpretation, and decision. |
Source code in bayesprop/resources/bayes_nonpaired.py
posterior_probability_H0(BF_01, prior_H0=0.5)
staticmethod
¶
Convert BF_01 to posterior probability of H0 (spike-and-slab).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
BF_01
|
float
|
Bayes factor in favour of H0. |
required |
prior_H0
|
float
|
Prior probability of H0 (default 0.5). |
0.5
|
Returns:
| Type | Description |
|---|---|
PosteriorProbH0Result
|
class: |
PosteriorProbH0Result
|
and model probabilities. |
Source code in bayesprop/resources/bayes_nonpaired.py
rope_test(rope=None, ci_mass=0.95)
¶
ROPE analysis on the posterior of Δ = θ_A − θ_B.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rope
|
tuple[float, float] | None
|
(lower, upper) ROPE bounds. Defaults to
|
None
|
ci_mass
|
float
|
Credible interval mass (default 95%). |
0.95
|
Returns:
| Type | Description |
|---|---|
ROPEResult
|
class: |
ROPEResult
|
decision. |
Source code in bayesprop/resources/bayes_nonpaired.py
decide(rule=None)
¶
Run the chosen decision framework(s) and return a composite result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rule
|
DecisionRuleType | None
|
Override the default |
None
|
Returns:
| Type | Description |
|---|---|
HypothesisDecision
|
class: |
HypothesisDecision
|
populated. |
Source code in bayesprop/resources/bayes_nonpaired.py
ppc_pvalues(seed=None)
¶
Posterior predictive p-values for summary statistics.
For each summary statistic (group means and mean difference),
replicated datasets are drawn from the posterior predictive
distribution and a two-sided mid-p value is computed as
The mid-p correction splits the probability mass at exact ties
evenly between the two tails, which prevents the p-value from
clipping at 1.0 when T^rep and T^obs coincide often
(a common occurrence for binary data, where the sample mean
lives on the coarse grid k/n).
Note
For the conjugate Beta-Bernoulli model the sample mean is the sufficient statistic for each group, so PPC p-values for the means are expected to be close to 1.0 by construction. They are reported here only as a sanity check against gross misspecification (e.g. wrong likelihood family) and should not be interpreted as a strong test of fit for this saturated model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int | None
|
Random seed for reproducibility. Falls back to
|
None
|
Returns:
| Type | Description |
|---|---|
dict[str, PPCStatistic]
|
Dict mapping statistic name to :class: |
dict[str, PPCStatistic]
|
with observed value, p-value, and status ("OK" / "WARN"). |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If :meth: |
Source code in bayesprop/resources/bayes_nonpaired.py
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 | |
plot_posteriors(**kwargs)
¶
Overlaid analytic Beta posteriors of θ_A and θ_B.
Single-panel plot showing the posterior densities for θ_A and θ_B overlaid on the same axes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
dict
|
Accepts |
{}
|
Source code in bayesprop/resources/bayes_nonpaired.py
plot_posterior_delta(color='#9C27B0', **kwargs)
¶
KDE posterior density of Δ = θ_A − θ_B with 95% CI.
Plots a smooth kernel density estimate of the Monte Carlo difference posterior with the 95% credible interval shaded and the posterior mean marked.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
color
|
str
|
Colour for the density curve and fill. |
'#9C27B0'
|
**kwargs
|
dict
|
Accepts |
{}
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If :meth: |
Source code in bayesprop/resources/bayes_nonpaired.py
plot_savage_dickey(color='#9C27B0', **kwargs)
¶
Posterior vs prior density of Δ with Savage-Dickey BF annotation.
Overlays the exact convolution densities of Δ under the posterior and prior, marks the density values at Δ = 0, and annotates the plot with BF₁₀, log₁₀ BF₁₀, and the decision.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
color
|
str
|
Colour for the posterior density curve and fill. |
'#9C27B0'
|
**kwargs
|
dict
|
Accepts |
{}
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If :meth: |
Source code in bayesprop/resources/bayes_nonpaired.py
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 | |
print_summary()
¶
Print posterior summary, Savage-Dickey test, and PPC p-values.
Outputs a formatted report to stdout containing:
- Beta posterior parameters and moments for θ_A, θ_B
- Posterior mean Δ, 95% CI, and P(A > B)
- Savage-Dickey Bayes factor with interpretation
- Posterior model probabilities P(H₀ | D) and P(H₁ | D)
- Posterior predictive p-values for key summary statistics
- Trace summary table (mean, sd, HDI)
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If :meth: |
Source code in bayesprop/resources/bayes_nonpaired.py
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 | |
plot_forest(results, label_A='Group A', label_B='Group B', **kwargs)
staticmethod
¶
Forest plot with P(A > B) bar chart for multiple metrics.
The left panel shows posterior mean differences with 95% credible intervals; the right panel shows horizontal bars for the posterior probability of superiority.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
dict[str, 'NonPairedBayesPropTest']
|
Mapping from metric name to a fitted
:class: |
required |
label_A
|
str
|
Display label for group A. |
'Group A'
|
label_B
|
str
|
Display label for group B. |
'Group B'
|
**kwargs
|
Any
|
Accepts |
{}
|
Source code in bayesprop/resources/bayes_nonpaired.py
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 | |
print_comparison_table(results)
staticmethod
¶
Print a formatted comparison table across metrics.
Displays the posterior mean difference, 95% credible interval, posterior probability of superiority P(A > B), and a verdict for each metric in a fixed-width table.
The verdict is determined as:
- A wins if P(A > B) > 0.95
- B wins if P(A > B) ≤ 0.5
- Tied otherwise
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
dict[str, 'NonPairedBayesPropTest']
|
Mapping from metric name to a fitted
:class: |
required |
Source code in bayesprop/resources/bayes_nonpaired.py
_format_bf(value)
¶
Format a Bayes Factor for human-readable display.
Source code in bayesprop/resources/bayes_nonpaired.py
classify_bf(bf10, bf_upper=3.0, bf_lower=1.0 / 3.0)
¶
Three-way decision from a Bayes factor against a point null.
This is the single source of truth for the "reject / accept /
inconclusive" mapping used by both the sequential stopping rule
in :class:SequentialNonPairedBayesPropTest and any external
operating-characteristic / BFDA tooling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bf10
|
float
|
Bayes factor in favour of H₁. |
required |
bf_upper
|
float
|
Threshold above which we declare evidence for H₁. Conventional choices: 3 ("moderate"), 10 ("strong"), 30 ("very strong"), 100 ("decisive") — Jeffreys (1961). |
3.0
|
bf_lower
|
float
|
Threshold below which we declare evidence for H₀.
Should equal |
1.0 / 3.0
|
Returns:
| Type | Description |
|---|---|
BFDecision
|
One of |
BFDecision
|
( |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in bayesprop/resources/bayes_nonpaired.py
_gauss_legendre_unit(n_quad)
cached
¶
Return cached Gauss-Legendre nodes/weights mapped to [0, 1].
leggauss(n_quad) triggers a symmetric eigenvalue solve via the
Golub-Welsch algorithm — measured at ~44 % of the cost of a single
:meth:NonPairedBayesPropTest.fit call in tight loops. Because the
result depends only on n_quad we memoise it module-wide.
The returned arrays are treated as read-only by callers.
Source code in bayesprop/resources/bayes_nonpaired.py
beta_diff_pdf(z, a1, b1, a2, b2, n_grid=2000)
¶
Evaluate the PDF of Δ = θ_A − θ_B at z via log-space convolution.
Where θ_A ~ Beta(a1, b1) and θ_B ~ Beta(a2, b2) are independent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
float
|
Point at which to evaluate the density (−1 < z < 1). |
required |
a1
|
float
|
Alpha parameter for the Beta distribution of θ_A. |
required |
b1
|
float
|
Beta parameter for the Beta distribution of θ_A. |
required |
a2
|
float
|
Alpha parameter for the Beta distribution of θ_B. |
required |
b2
|
float
|
Beta parameter for the Beta distribution of θ_B. |
required |
n_grid
|
int
|
Number of quadrature nodes for trapezoidal integration. |
2000
|
Returns:
| Type | Description |
|---|---|
float
|
f_Δ(z), the density of the difference at z. |
Source code in bayesprop/resources/bayes_nonpaired.py
_prior_diff_pdf_at(alpha0, beta0, null_value, n_grid=2000)
cached
¶
Cached prior density of Δ = θ_A − θ_B at null_value under symmetric Beta(α₀, β₀).
Used by the Savage-Dickey ratio. The prior parameters and null
point do not change across a simulation, so memoising removes one
full 2000-point convolution per call to :meth:savage_dickey_test.
Source code in bayesprop/resources/bayes_nonpaired.py
descriptive_summary(scores_data, thresholds=None)
¶
Build a combined descriptive-stats + Beta-Bernoulli threshold-sweep table.
Parameters¶
scores_data : dict
Must contain keys "model_A", "model_B", and "metrics"
where metrics[name] has "s_A_raw" and "s_B_raw" arrays.
thresholds : list of float, optional
Binarization thresholds for the Beta-Bernoulli sweep.
Default: [0.5, 0.7, 0.8, 0.9, 0.95].
Returns:¶
pd.DataFrame Multi-indexed by (Metric, Model) with descriptive stats and BB results.
Source code in bayesprop/resources/bayes_nonpaired.py
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 | |