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 ai_eval.resources.bayes_nonpaired import NonPairedBayesPropTest, descriptive_summary
bb = NonPairedBayesPropTest(threshold=0.7)
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.7, n_quad=100, seed=0, n_samples=20000, verbose=False, decision_rule='all', rope_epsilon=0.02)
¶
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.7
|
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
_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.
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
.. math::
p = 2\,\min\!\bigl(P(T^{\text{rep}} > T^{\text{obs}})
+ \tfrac{1}{2} P(T^{\text{rep}} = T^{\text{obs}}),\;
P(T^{\text{rep}} < T^{\text{obs}})
+ \tfrac{1}{2} P(T^{\text{rep}} = T^{\text{obs}})\bigr).
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
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 | |
plot_posteriors(**kwargs)
¶
Two-panel plot: overlaid θ_A / θ_B posteriors and Δ = θ_A − θ_B.
The left panel shows the analytic Beta posterior densities for θ_A and θ_B overlaid in a single axes. The right panel shows the Monte Carlo difference posterior Δ = θ_A − θ_B.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
dict
|
Accepts |
{}
|
Source code in bayesprop/resources/bayes_nonpaired.py
571 572 573 574 575 576 577 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 | |
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
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 | |
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
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 904 905 906 907 908 909 | |
plot_forest(results, label_A='Model A', label_B='Model 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. |
'Model A'
|
label_B
|
str
|
Display label for group B. |
'Model B'
|
**kwargs
|
Any
|
Accepts |
{}
|
Source code in bayesprop/resources/bayes_nonpaired.py
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 986 987 988 989 990 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 | |
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
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
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
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 | |