The Bayesian correlation
Test a correlation with a stretched-beta prior, estimate ρ with a credible interval, and keep evidence and strength apart.
What runs in CodeSplash
- STAT312Jeffreys Bayesian correlation test Runs in CodeSplash
- Bayesian correlation (Jeffreys Bayes factor) Verified in Python and R
You will be able to
- Describe the stretched-beta prior on ρ and its width
- Read a Bayes factor and a posterior for ρ together
- Distinguish strong evidence from a strong correlation
A prior on ρ
ReadThe test compares with an that spreads its belief across correlations from −1 to 1:
The stretched-beta priorStretched beta priorThe prior on a correlation ρ in the Bayesian correlation test — a Beta(1/κ, 1/κ) stretched to (−1, 1); κ = 1 is uniform. has one setting, its width . At the prior is uniform, so every correlation is equally likely. A smaller pulls belief toward 0.
This is the test Jeffreys proposed, with the width as a choice you state.
Predict with few points
PredictPredict first
Ten points give = 0.54. That looks sizeable. With a uniform prior, how strong is the evidence?
Reveal
Roughly neutral: = 1.21. Ten points can't pin down . The posterior median is 0.44, and its interval runs from −0.17 to 0.80, which includes zero and values near 1.
Prior and direction
ReflectSame ten points, a medium prior ( = 0.33), and a positive direction: = 2.55, against a two-sided 1.43.
The evidence grows because makes sharper predictions. It would be fair only if you'd expected a positive correlation in advance.
The uniform-prior run's robustness range is 1.16 to 1.43. Before you see your own data, what do you expect: any sign, or one?
Evidence isn't strength
PredictPredict first
On 153 days of air-quality data, wind and temperature have a directional of about 9,827,187.
Does a number that large mean the correlation is strong?
Reveal
No. The sample is −0.46, with a posterior median of −0.45. That's moderate. The Bayes factor says that a non-zero predicted the data far better. The posterior says how large it is.
Read the card
In the appBF₁₀ = 9827186.99 (κ = 0.577), r = −.46, ρ = -0.45, 90% CrI [-0.55, -0.34]
- BF₁₀ (ρ < 0 vs ρ = 0)
- 9.827e+6
- BF₀₁
- 1.018e-7
- Sample r
- −0.4580
- ρ (posterior median)
- −0.4487
- 90% credible interval
- [−0.5481, −0.3367]
Effect size
- ρ (posterior median) −0.4487 90% CI [−0.5481, −0.3367]
Plots
View data
| curve | density | ρ |
|---|---|---|
| Prior | 9.308e-5 | −1.0000 |
| Prior | 0.0474 | −0.9950 |
| Prior | 0.0786 | −0.9900 |
| Prior | 0.1056 | −0.9850 |
| Prior | 0.1301 | −0.9800 |
| Prior | 0.1529 | −0.9750 |
| Prior | 0.1744 | −0.9700 |
| Prior | 0.1949 | −0.9650 |
| Prior | 0.2145 | −0.9600 |
| Prior | 0.2334 | −0.9550 |
| Prior | 0.2516 | −0.9500 |
| Prior | 0.2693 | −0.9450 |
| Prior | 0.2864 | −0.9400 |
| Prior | 0.3031 | −0.9350 |
| Prior | 0.3194 | −0.9300 |
| Prior | 0.3354 | −0.9250 |
| Prior | 0.3509 | −0.9200 |
| Prior | 0.3661 | −0.9150 |
| Prior | 0.3810 | −0.9100 |
| Prior | 0.3957 | −0.9050 |
| Prior | 0.4100 | −0.9000 |
| Prior | 0.4241 | −0.8950 |
| Prior | 0.4380 | −0.8900 |
| Prior | 0.4516 | −0.8850 |
| Prior | 0.4649 | −0.8800 |
| Prior | 0.4781 | −0.8750 |
| Prior | 0.4911 | −0.8700 |
| Prior | 0.5039 | −0.8650 |
| Prior | 0.5164 | −0.8600 |
| Prior | 0.5288 | −0.8550 |
| Prior | 0.5410 | −0.8500 |
| Prior | 0.5531 | −0.8450 |
| Prior | 0.5650 | −0.8400 |
| Prior | 0.5767 | −0.8350 |
| Prior | 0.5883 | −0.8300 |
| Prior | 0.5997 | −0.8250 |
| Prior | 0.6109 | −0.8200 |
| Prior | 0.6221 | −0.8150 |
| Prior | 0.6331 | −0.8100 |
| Prior | 0.6439 | −0.8050 |
| Prior | 0.6546 | −0.8000 |
| Prior | 0.6652 | −0.7950 |
| Prior | 0.6757 | −0.7900 |
| Prior | 0.6860 | −0.7850 |
| Prior | 0.6962 | −0.7800 |
| Prior | 0.7063 | −0.7750 |
| Prior | 0.7163 | −0.7700 |
| Prior | 0.7261 | −0.7650 |
| Prior | 0.7359 | −0.7600 |
| Prior | 0.7455 | −0.7550 |
| Prior | 0.7550 | −0.7500 |
| Prior | 0.7645 | −0.7450 |
| Prior | 0.7738 | −0.7400 |
| Prior | 0.7830 | −0.7350 |
| Prior | 0.7921 | −0.7300 |
| Prior | 0.8011 | −0.7250 |
| Prior | 0.8100 | −0.7200 |
| Prior | 0.8189 | −0.7150 |
| Prior | 0.8276 | −0.7100 |
| Prior | 0.8362 | −0.7050 |
First 60 of 402 rows.
View data
| BF₁₀ | prior width κ |
|---|---|
| 1.113e+6 | 0.0500 |
| 1.410e+6 | 0.0549 |
| 1.757e+6 | 0.0603 |
| 2.154e+6 | 0.0662 |
| 2.600e+6 | 0.0727 |
| 3.091e+6 | 0.0798 |
| 3.620e+6 | 0.0877 |
| 4.179e+6 | 0.0963 |
| 4.760e+6 | 0.1057 |
| 5.352e+6 | 0.1161 |
| 5.945e+6 | 0.1275 |
| 6.527e+6 | 0.1400 |
| 7.088e+6 | 0.1538 |
| 7.619e+6 | 0.1689 |
| 8.111e+6 | 0.1854 |
| 8.557e+6 | 0.2036 |
| 8.952e+6 | 0.2236 |
| 9.291e+6 | 0.2456 |
| 9.574e+6 | 0.2696 |
| 9.797e+6 | 0.2961 |
| 9.962e+6 | 0.3252 |
| 9.996e+6 | 0.3333 |
| 1.007e+7 | 0.3571 |
| 1.012e+7 | 0.3921 |
| 1.012e+7 | 0.4306 |
| 1.007e+7 | 0.4729 |
| 9.982e+6 | 0.5193 |
| 9.848e+6 | 0.5702 |
| 9.827e+6 | 0.5774 |
| 9.677e+6 | 0.6262 |
| 9.475e+6 | 0.6877 |
| 9.244e+6 | 0.7551 |
| 8.989e+6 | 0.8293 |
| 8.713e+6 | 0.9106 |
| 8.421e+6 | 1 |
View data
| BF₁₀ | rows |
|---|---|
| 0.5610 | 3 |
| 1.192 | 6 |
| 1.472 | 8 |
| 3.951 | 11 |
| 5.540 | 13 |
| 9.802 | 16 |
| 34.467 | 18 |
| 17.453 | 21 |
| 2.930 | 23 |
| 7.779 | 26 |
| 3.462 | 28 |
| 4.166 | 31 |
| 6.367 | 34 |
| 11.826 | 36 |
| 15.772 | 39 |
| 4.437 | 41 |
| 6.704 | 44 |
| 5.196 | 46 |
| 2.563 | 49 |
| 2.820 | 51 |
| 4.152 | 54 |
| 5.169 | 56 |
| 6.084 | 59 |
| 6.299 | 61 |
| 13.936 | 64 |
| 20.172 | 67 |
| 66.583 | 69 |
| 226.82 | 72 |
| 151.72 | 74 |
| 52.350 | 77 |
| 75.585 | 79 |
| 105.62 | 82 |
| 109.28 | 84 |
| 189.40 | 87 |
| 208.40 | 89 |
| 385.35 | 92 |
| 444.18 | 95 |
| 795.06 | 97 |
| 2257.16 | 100 |
| 3302.92 | 102 |
| 2235.86 | 105 |
| 2531.60 | 107 |
| 2845.76 | 110 |
| 3299.41 | 112 |
| 4167.05 | 115 |
| 4890.34 | 117 |
| 7802.21 | 120 |
| 42044.54 | 122 |
| 210107.60 | 125 |
| 1.569e+6 | 128 |
| 795728.90 | 130 |
| 1.107e+6 | 133 |
| 805579.79 | 135 |
| 1.033e+6 | 138 |
| 1.720e+6 | 140 |
| 2.377e+6 | 143 |
| 3.372e+6 | 145 |
| 1.075e+7 | 148 |
| 7.031e+6 | 150 |
| 9.827e+6 | 153 |
View data
| Wind | Temp |
|---|---|
| 7.400 | 67 |
| 8 | 72 |
| 12.600 | 74 |
| 11.500 | 62 |
| 14.300 | 56 |
| 14.900 | 66 |
| 8.600 | 65 |
| 13.800 | 59 |
| 20.100 | 61 |
| 8.600 | 69 |
| 6.900 | 74 |
| 9.700 | 69 |
| 9.200 | 66 |
| 10.900 | 68 |
| 13.200 | 58 |
| 11.500 | 64 |
| 12 | 66 |
| 18.400 | 57 |
| 11.500 | 68 |
| 9.700 | 62 |
| 9.700 | 59 |
| 16.600 | 73 |
| 9.700 | 61 |
| 12 | 61 |
| 16.600 | 57 |
| 14.900 | 58 |
| 8 | 57 |
| 12 | 67 |
| 14.900 | 81 |
| 5.700 | 79 |
| 7.400 | 76 |
| 8.600 | 78 |
| 9.700 | 74 |
| 16.100 | 67 |
| 9.200 | 84 |
| 8.600 | 85 |
| 14.300 | 79 |
| 9.700 | 82 |
| 6.900 | 87 |
| 13.800 | 90 |
| 11.500 | 87 |
| 10.900 | 93 |
| 9.200 | 92 |
| 8 | 82 |
| 13.800 | 80 |
| 11.500 | 79 |
| 14.900 | 77 |
| 20.700 | 72 |
| 9.200 | 65 |
| 11.500 | 73 |
| 10.300 | 76 |
| 6.300 | 77 |
| 1.700 | 76 |
| 4.600 | 76 |
| 6.300 | 76 |
| 8 | 75 |
| 8 | 78 |
| 10.300 | 73 |
| 11.500 | 80 |
| 14.900 | 77 |
First 60 of 153 rows.
Assumptions
- Bivariate normality — No extreme rows; marginal distributions are compatible with normality or n ≥ 30.
- Linear relationship — Check the scatter plot: ρ measures linear association.
- Independent observations — Each row should be a separate unit.
Evidence
| Quantity | Value |
|---|---|
| BF₁₀ (chosen alternative) | 9.827e+6 |
| BF₁₀ (two-sided) | 4.914e+6 |
| P(H₁ | data), equal prior odds | 1.0000 |
| Posterior mean of ρ | −0.4463 |
- Prior: ρ ~ stretched Beta(1/κ, 1/κ) on (−1, 1), κ = 0.577, restricted to ρ < 0.
- Evidence: extreme evidence for H₁. With equal prior odds, P(H₁ | data) = 1.000.
- A Bayes factor is relative evidence, not a p-value; it is not entered in the multiple-testing ledger.
The exact R script · R R version 4.5.1 (2025-06-13)
# Bayesian correlation (Jeffreys Bayes factor)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bayes.correlation 1.0.1 · spec cbd627e00c0ffd94
# Dataset: airquality (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_bayes_corr, cs_bayes_prior_scale, cs_bayes_evidence_label (twins of codesplash.stats.bayes)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/airquality.parquet", col_select = c("Wind", "Temp")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("Wind", "Temp")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("Wind", "Temp")) # infinite values stop the run (registry/errors.yaml)
# %% Test
a <- "Wind"
b <- "Temp"
x <- as.numeric(df[[a]])
y <- as.numeric(df[[b]])
if (length(x) < 3) cs_error("CS_E_TOO_FEW_ROWS", what = "A Bayesian correlation", min = 3, n = length(x))
if (length(unique(x)) < 2) cs_error("CS_E_CONSTANT", column = a)
if (length(unique(y)) < 2) cs_error("CS_E_CONSTANT", column = b)
kappa <- cs_bayes_prior_scale("correlation", "wide", 0.333)
alternative <- "less"
cred <- 0.9
res <- cs_bayes_corr(x, y, kappa = kappa, alternative = alternative, cred = cred,
robustness = TRUE, sequential = TRUE)
bf10 <- res$bf10
post <- res$post
n <- length(x)
# %% Assumptions
assumptions <- list()
sw <- vapply(list(x, y), function(v) if (length(v) >= 3 && length(v) <= 5000) stats::shapiro.test(v)$p.value else NA_real_, numeric(1))
zs <- function(v) abs((v - mean(v)) / stats::sd(v) * sqrt(length(v) / (length(v) - 1)))
extreme <- sum(zs(x) > 3.5 | zs(y) > 3.5)
if (extreme > 0) {
status <- "warn"
detail <- sprintf("%d row(s) lie more than 3.5 SD from a mean; Pearson's r and its Bayes factor can hinge on them.", extreme)
} else if (any(!is.na(sw) & sw < 0.05) && n < 30) {
status <- "warn"
detail <- "Shapiro–Wilk p < .05 for a variable with fewer than 30 rows; the bivariate-normal likelihood is doubtful."
} else {
status <- "pass"
detail <- "No extreme rows; marginal distributions are compatible with normality or n ≥ 30."
}
assumptions[[length(assumptions) + 1]] <- list(key = "normality", label = "Bivariate normality", status = status, detail = detail)
assumptions[[length(assumptions) + 1]] <- list(key = "linearity", label = "Linear relationship", status = "info", detail = "Check the scatter plot: ρ measures linear association.")
assumptions[[length(assumptions) + 1]] <- list(key = "independence", label = "Independent observations", status = "info", detail = "Each row should be a separate unit.")
# %% Result
label <- cs_bayes_evidence_label(bf10)
direction <- switch(alternative, "two-sided" = "ρ ≠ 0", greater = "ρ > 0", less = "ρ < 0")
summary <- sprintf(
"BF₁₀ = %s for a correlation between %s and %s (sample r = %.2f, n = %d): the data are %s times more likely under %s — %s (prior width κ = %s). Under the alternative, ρ is most likely near %.2f (%s credible interval [%.2f, %.2f]).",
cs_fmt_num(bf10), a, b, res$r, n, cs_fmt_num(if (bf10 >= 1) bf10 else 1 / bf10),
if (bf10 >= 1) sprintf("the alternative (%s)", direction) else "no correlation", label, format(signif(kappa, 3)),
post$median, sprintf("%.0f%%", 100 * cred), post$low, post$high)
grid <- res$grid
charts <- list(cs_chart("prior_posterior", "prior-posterior", "Prior and posterior of ρ",
list(x = cs_col("ρ", c(grid, grid)), density = cs_col("density", c(res$prior_density, res$posterior_density)),
curve = cs_col("curve", c(rep("Prior", length(grid)), rep("Posterior", length(grid))), levels = c("Prior", "Posterior"))),
controls = list(point = 0, ci_low = post$low, ci_high = post$high, cred = cred, bf10 = bf10)))
if (!is.null(res$robust_r)) {
charts[[length(charts) + 1]] <- cs_chart("robustness", "bf-robustness", "Bayes factor across prior widths",
list(x = cs_col("prior width κ", res$robust_r), bf = cs_col("BF₁₀", res$robust_bf)), controls = list(chosen = kappa))
}
if (!is.null(res$seq_n) && length(res$seq_n) >= 2) {
charts[[length(charts) + 1]] <- cs_chart("sequential", "bf-sequential", "Bayes factor as rows accumulate",
list(n = cs_col("rows", as.numeric(res$seq_n)), bf = cs_col("BF₁₀", res$seq_bf)))
}
rows <- unique(as.integer(round(seq(0, n - 1, length.out = min(n, 5000))))) + 1L
charts[[length(charts) + 1]] <- cs_chart("scatter", "scatter", sprintf("%s against %s", b, a), list(x = cs_col(a, x[rows]), y = cs_col(b, y[rows])))
cs_publish(list(
method = "bayes.correlation",
methodVersion = "1.0.1",
title = "Bayesian correlation",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("BF₁₀ = %s (κ = %s), r = %s, ρ = %.2f, %s CrI [%.2f, %.2f]", cs_fmt_num(bf10), format(signif(kappa, 3)),
cs_fmt_num(res$r, leading_zero = FALSE), post$median, sprintf("%.0f%%", 100 * cred), post$low, post$high),
statistics = list(
list(key = "bf10", label = sprintf("BF₁₀ (%s vs ρ = 0)", direction), value = bf10),
list(key = "bf01", label = "BF₀₁", value = 1 / bf10),
list(key = "r", label = "Sample r", value = res$r),
list(key = "rho", label = "ρ (posterior median)", value = post$median),
list(key = "cri", label = sprintf("%.0f%% credible interval", 100 * cred), value = c(post$low, post$high))
),
tables = list(list(key = "evidence", title = "Evidence",
columns = list(list(key = "quantity", label = "Quantity", type = "string"), list(key = "value", label = "Value", type = "number")),
rows = list(list(quantity = "BF₁₀ (chosen alternative)", value = bf10),
list(quantity = "BF₁₀ (two-sided)", value = res$bf10_two_sided),
list(quantity = "P(H₁ | data), equal prior odds", value = bf10 / (1 + bf10)),
list(quantity = "Posterior mean of ρ", value = post$mean)))),
effectSizes = list(list(key = "rho", label = "ρ (posterior median)", value = post$median, ciLow = post$low, ciHigh = post$high, ciLevel = cred,
method = "posterior under H₁ (Jeffreys exact likelihood), equal-tailed credible interval")),
assumptions = assumptions,
warnings = warnings,
notes = list(
sprintf("Prior: ρ ~ stretched Beta(1/κ, 1/κ) on (−1, 1), κ = %s%s.", format(signif(kappa, 3)), if (alternative == "two-sided") "" else paste0(", restricted to ", direction)),
sprintf("Evidence: %s. With equal prior odds, P(H₁ | data) = %.3f.", label, bf10 / (1 + bf10)),
"A Bayes factor is relative evidence, not a p-value; it is not entered in the multiple-testing ledger."
),
values = list(
bf10 = bf10, bf01 = 1 / bf10, log_bf10 = res$log_bf10, bf10_two_sided = res$bf10_two_sided, p_h1 = bf10 / (1 + bf10),
r = res$r, n = n, kappa = kappa, rho_mean = post$mean, rho_median = post$median,
rho_low = post$low, rho_high = post$high, error_pct = 100 * res$error,
bf_robust_min = if (!is.null(res$robust_bf)) min(res$robust_bf) else NULL,
bf_robust_max = if (!is.null(res$robust_bf)) max(res$robust_bf) else NULL
),
charts = charts
))
BF₁₀ = 9827186.99 (κ = 0.577), r = −.46, ρ = -0.45, 90% CrI [-0.55, -0.34]
- BF₁₀ (ρ < 0 vs ρ = 0)
- 9.827e+6
- BF₀₁
- 1.018e-7
- Sample r
- −0.4580
- ρ (posterior median)
- −0.4487
- 90% credible interval
- [−0.5481, −0.3367]
Effect size
- ρ (posterior median) −0.4487 90% CI [−0.5481, −0.3367]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Bivariate normality — No extreme rows; marginal distributions are compatible with normality or n ≥ 30.
- Linear relationship — Check the scatter plot: ρ measures linear association.
- Independent observations — Each row should be a separate unit.
Evidence
| Quantity | Value |
|---|---|
| BF₁₀ (chosen alternative) | 9.827e+6 |
| BF₁₀ (two-sided) | 4.914e+6 |
| P(H₁ | data), equal prior odds | 1.0000 |
| Posterior mean of ρ | −0.4463 |
- Prior: ρ ~ stretched Beta(1/κ, 1/κ) on (−1, 1), κ = 0.577, restricted to ρ < 0.
- Evidence: extreme evidence for H₁. With equal prior odds, P(H₁ | data) = 1.000.
- A Bayes factor is relative evidence, not a p-value; it is not entered in the multiple-testing ledger.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Bayesian correlation (Jeffreys Bayes factor)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bayes.correlation 1.0.1 · spec cbd627e00c0ffd94
# Dataset: airquality (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.stats import bayes as bf # Jeffreys correlation Bayes factor (twin of R cs_bayes_*)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/airquality.parquet", columns=["Wind", "Temp"])
n_input = len(df)
df = df.dropna(subset=["Wind", "Temp"]) # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["Wind", "Temp"]) # infinite values stop the run (registry/errors.yaml)
# %% Test
a, b = "Wind", "Temp"
x = df[a].to_numpy(dtype=float)
y = df[b].to_numpy(dtype=float)
if len(x) < 3:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="A Bayesian correlation", min=3, n=len(x))
for column, v in ((a, x), (b, y)): # exact check: a float SD of identical values need not be 0
if len(np.unique(v)) < 2:
cs.cs_error("CS_E_CONSTANT", column=column)
kappa = bf.prior_scale("correlation", "wide", 0.333)
alternative = "less"
cred = 0.9
res = bf.corr_bf(x, y, kappa=kappa, alternative=alternative, cred=cred,
robustness=True, sequential=True)
bf10 = res["bf10"]
post = res["post"]
n = len(x)
# %% Assumptions
assumptions = []
sw = [stats.shapiro(v).pvalue if 3 <= len(v) <= 5000 else None for v in (x, y)]
z = np.abs(stats.zscore(x)), np.abs(stats.zscore(y))
extreme = int(((z[0] > 3.5) | (z[1] > 3.5)).sum())
if extreme:
status, detail = "warn", f"{extreme} row(s) lie more than 3.5 SD from a mean; Pearson's r and its Bayes factor can hinge on them."
elif any(p is not None and p < 0.05 for p in sw) and n < 30:
status, detail = "warn", "Shapiro–Wilk p < .05 for a variable with fewer than 30 rows; the bivariate-normal likelihood is doubtful."
else:
status, detail = "pass", "No extreme rows; marginal distributions are compatible with normality or n ≥ 30."
assumptions.append({"key": "normality", "label": "Bivariate normality", "status": status, "detail": detail})
assumptions.append({"key": "linearity", "label": "Linear relationship", "status": "info", "detail": "Check the scatter plot: ρ measures linear association."})
assumptions.append({"key": "independence", "label": "Independent observations", "status": "info", "detail": "Each row should be a separate unit."})
# %% Result
label = bf.evidence_label(bf10)
direction = {"two-sided": "ρ ≠ 0", "greater": "ρ > 0", "less": "ρ < 0"}[alternative]
summary = (
f"BF₁₀ = {cs.fmt_num(bf10)} for a correlation between {a} and {b} (sample r = {res['r']:.2f}, n = {n}): "
f"the data are {cs.fmt_num(bf10 if bf10 >= 1 else 1 / bf10)} times more likely under "
f"{'the alternative (' + direction + ')' if bf10 >= 1 else 'no correlation'} — {label} (prior width κ = {kappa:.3g}). "
f"Under the alternative, ρ is most likely near {post['median']:.2f} ({cred:.0%} credible interval [{post['low']:.2f}, {post['high']:.2f}])."
)
grid = res["grid"]
charts = [cs.chart(
"prior_posterior", "prior-posterior", "Prior and posterior of ρ",
{"x": cs.col("ρ", np.concatenate([grid, grid])),
"density": cs.col("density", np.concatenate([res["prior_density"], res["posterior_density"]])),
"curve": cs.col("curve", ["Prior"] * len(grid) + ["Posterior"] * len(grid), levels=["Prior", "Posterior"])},
controls={"point": 0, "ci_low": post["low"], "ci_high": post["high"], "cred": cred, "bf10": bf10},
)]
if "robust_r" in res:
charts.append(cs.chart("robustness", "bf-robustness", "Bayes factor across prior widths",
{"x": cs.col("prior width κ", res["robust_r"]), "bf": cs.col("BF₁₀", res["robust_bf"])}, controls={"chosen": kappa}))
if "seq_n" in res and len(res["seq_n"]) >= 2:
charts.append(cs.chart("sequential", "bf-sequential", "Bayes factor as rows accumulate",
{"n": cs.col("rows", res["seq_n"]), "bf": cs.col("BF₁₀", res["seq_bf"])}))
rows = np.unique(np.round(np.linspace(0, n - 1, min(n, 5000))).astype(int))
charts.append(cs.chart("scatter", "scatter", f"{b} against {a}", {"x": cs.col(a, x[rows]), "y": cs.col(b, y[rows])}))
cs.publish({
"method": "bayes.correlation",
"methodVersion": "1.0.1",
"title": "Bayesian correlation",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"BF₁₀ = {cs.fmt_num(bf10)} (κ = {kappa:.3g}), r = {cs.fmt_num(res['r'], leading_zero=False)}, ρ = {post['median']:.2f}, {cred:.0%} CrI [{post['low']:.2f}, {post['high']:.2f}]",
"statistics": [
{"key": "bf10", "label": f"BF₁₀ ({direction} vs ρ = 0)", "value": bf10},
{"key": "bf01", "label": "BF₀₁", "value": 1 / bf10},
{"key": "r", "label": "Sample r", "value": res["r"]},
{"key": "rho", "label": "ρ (posterior median)", "value": post["median"]},
{"key": "cri", "label": f"{cred:.0%} credible interval", "value": [post["low"], post["high"]]},
],
"tables": [{"key": "evidence", "title": "Evidence",
"columns": [{"key": "quantity", "label": "Quantity", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
"rows": [{"quantity": "BF₁₀ (chosen alternative)", "value": bf10},
{"quantity": "BF₁₀ (two-sided)", "value": res["bf10_two_sided"]},
{"quantity": "P(H₁ | data), equal prior odds", "value": bf10 / (1 + bf10)},
{"quantity": "Posterior mean of ρ", "value": post["mean"]}]}],
"effectSizes": [{"key": "rho", "label": "ρ (posterior median)", "value": post["median"], "ciLow": post["low"], "ciHigh": post["high"], "ciLevel": cred,
"method": "posterior under H₁ (Jeffreys exact likelihood), equal-tailed credible interval"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Prior: ρ ~ stretched Beta(1/κ, 1/κ) on (−1, 1), κ = {kappa:.3g}{'' if alternative == 'two-sided' else ', restricted to ' + direction}.",
f"Evidence: {label}. With equal prior odds, P(H₁ | data) = {bf10 / (1 + bf10):.3f}.",
"A Bayes factor is relative evidence, not a p-value; it is not entered in the multiple-testing ledger."],
"values": {
"bf10": bf10, "bf01": 1 / bf10, "log_bf10": res["log_bf10"], "bf10_two_sided": res["bf10_two_sided"], "p_h1": bf10 / (1 + bf10),
"r": res["r"], "n": n, "kappa": kappa, "rho_mean": post["mean"], "rho_median": post["median"],
"rho_low": post["low"], "rho_high": post["high"], "error_pct": 100 * res["error"],
"bf_robust_min": float(np.min(res["robust_bf"])) if "robust_bf" in res else None,
"bf_robust_max": float(np.max(res["robust_bf"])) if "robust_bf" in res else None,
},
"charts": charts,
})
The 90% credible interval runs from −0.55 to −0.34.
Now check the scatter plot and the assumption rows. Is the relationship linear? Do a few days pull it? A Bayes factor, however large, can't repair an outlier-driven correlation.
Check your understanding
CheckpointCheck yourself
What happens to the prior on as shrinks?
Show the answer
Answer: b
is uniform. Smaller values say that small correlations are more plausible.
Check yourself
= 2,000 with = 0.15 and = 800. Which statement can you defend?
Show the answer
Answer: b
The Bayes factor is about . The posterior for gives the size, and the design decides anything about cause.
Check yourself
With = 10, = 1.2 and a posterior median of 0.44. What should you report?
Show the answer
Answer: c
The data are compatible with no correlation and with a large one, and you should say so.
Do it in CodeSplash
In the appChoose First variable and Second variable, set the prior width and the direction, then read the robustness and sequential charts.
import pandas as pd
import pingouin as pg
df = pd.read_csv("airquality.csv").dropna(subset=["Wind", "Temp"])
r = df["Wind"].corr(df["Temp"])
print(r, pg.bayesfactor_pearson(r, len(df), kappa=1.0))# install.packages("BayesFactor")
library(BayesFactor)
correlationBF(airquality$Wind, airquality$Temp, rscale = "medium")These scripts use their own priors and options, so the values may differ from the card's unless you match them.
Recap
Recap- The Bayesian correlation puts a stretched-beta prior on , with a width you state.
- Few points give weak evidence, even for a large sample .
- A huge Bayes factor doesn't mean a large correlation: read the posterior for size.
- Check the plot, since a Bayes factor can't fix an outlier-driven relationship.
Concepts in this lesson