Beyond correlation: ξ, Hoeffding's D, distance correlation and HSIC
Correlation can be zero for a perfect U shape. These tests look for any relationship at all, linear or not, including between groups of variables.
What runs in CodeSplash
- STAT084Hoeffding D test Runs in CodeSplash
- STAT085Distance covariance independence test Runs in CodeSplash
- STAT086Hilbert–Schmidt independence criterion test Runs in CodeSplash
- STAT087Cross HSIC test Runs in CodeSplash
- STAT088Cross distance covariance test Runs in CodeSplash
- STAT089Chatterjee xi independence test Runs in CodeSplash
- Test for any dependence (ξ, Hoeffding, distance correlation, HSIC) Verified in Python and R
You will be able to
- Explain why zero correlation does not mean independence
- Choose among ξ, Hoeffding's D, distance correlation and HSIC
- Use the asymmetry of ξ to see which variable predicts which
- Test dependence between sets of variables with distance covariance or cross HSIC
A perfect curve, zero correlation
ReadLet be a noisy quadratic in , with centered on zero. The relationship is obvious on a plot, yet Pearson's r = −0.028 and Spearman's ρ = −0.025.
Both are near zero because the rise on the right cancels the fall on the left. Zero correlation does not mean independence. You need a measure that is zero only when the variables are truly independent.
See it
ExploreCExplorable · Dependence the correlation misses
Can two variables be strongly related and still have a correlation near zero?
Pearson's r for this relationship will be about what?
Relationship
Commit your prediction above to see the result
Make your prediction to see the result.
Switch shapes: line, curve, circle, wave, noise. Note which coefficients react to which shapes, and which ones stay near zero while the picture shows a clear pattern.
Chatterjee's ξ asks whether y is a function of x
ReadSort the rows by . If is a smooth function of , neighboring rows have similar ranks of , so the ranks jump little:
For the quadratic, ξChatterjee's ξHow much y is a function of x — 0 under independence, 1 when y is exactly determined by x, any shape.(x → y) = 0.402 with p < .001. It's the default here: fast, no tuning, and with a known null distribution.
ξ has a direction
PredictPredict first
is a function of here. But given , there are two possible values of , one positive and one negative. How does ξ(y → x) compare with ξ(x → y)?
Reveal
ξ(x → y) = 0.402 and ξ(y → x) = 0.003. Knowing fixes , while knowing leaves ambiguous. ξ picks that up where symmetric measures can't.
Hoeffding's D
ReadHoeffding's DHoeffding's DA rank statistic for how far the joint distribution is from what independence would give. compares the joint distribution of ranks with what independence would produce, at every point of the plane. It detects many non-monotonic shapes without any tuning.
On a noisy wave, Pearson's r is 0.327, and Hoeffding's test gives p = .005. The card also reports , which runs from about to .
Distance correlation and HSIC
ReadDistance correlationDistance correlationA correlation built from distances between rows; it is zero only when the variables are independent. correlates the pairwise distances within and within . It's zero if and only if the variables are independent, given finite means, and and can each be several columns. CodeSplash reports a bias-corrected form with a test.
HSICHSICA kernel measure of dependence between two sets of variables; zero under independence for Gaussian kernels. does the same with similarity kernels. It needs a bandwidth; the default median heuristic uses the typical distance between points. On the quadratic, p = .005 by permutation.
On pure noise, the bias-corrected distance correlation sits at −0.001 with p = .545: no false alarm.
Sets of variables, and the cross tests
ReadBecause distances work in any number of dimensions, you can ask whether one set of variables depends on another. The distance correlation of two columns against one gives p = .005 by permutation.
Cross distance covariance and cross HSIC split the data in two and compare the halves. That gives a statistic with a normal null, so no permutations are needed: fast at large , at some cost in power. Cross HSIC on the quadratic gives = 6.25, p < .001, and cross dCov on two sets of columns gives p = .006.
Which one?
Reflect| You want | Use |
|---|---|
| A fast default, and the direction of prediction | Chatterjee's ξ |
| A single pair, many shapes, no tuning | Hoeffding's D |
| Sets of variables | Distance correlation or HSIC |
| Very large | Cross dCov or cross HSIC |
Beware of ξ on simple, noisy linear relationships: it has low power there. If you expect a monotonic trend, Spearman will detect it with far fewer rows. Which row matches a question you have right now?
Read the card
In the appChatterjee's ξ(x → y) = 0.402, p < .001, N = 118
- Chatterjee's ξ(x → y)
- 0.4019
- z
- 6.901
- p
- < .001
- n
- 118
Effect size
- Chatterjee's ξ(x → y) 0.4019
Plots
View data
| x | y quadratic |
|---|---|
| 0.5206 | 0.8319 |
| −1.080 | 0.1154 |
| 0.1392 | −1.026 |
| −0.0847 | −0.6384 |
| −0.6666 | 0.9804 |
| −2.516 | 6.778 |
| −1.020 | 1.064 |
| 0.1136 | 0.3246 |
| −0.4738 | 0.4670 |
| −0.4082 | 0.4326 |
| −0.7304 | 0.6322 |
| −0.2214 | 0.2123 |
| −0.2258 | −0.6691 |
| −2.547 | 7.544 |
| 1.347 | 1.722 |
| 0.6164 | 0.6260 |
| 0.2176 | −0.6333 |
| −0.8047 | 0.4650 |
| 0.6897 | 0.8538 |
| −0.3287 | 0.1813 |
| −0.1647 | 0.1581 |
| −1.392 | 1.285 |
| 1.466 | 2.395 |
| 0.0482 | −0.2532 |
| 1.908 | 2.810 |
| 1.731 | 3.307 |
| 0.0581 | 0.0112 |
| 0.6453 | 0.0495 |
| 1.726 | 3.115 |
| −0.5290 | −0.6496 |
| 0.1664 | 1.067 |
| 0.3328 | 0.2743 |
| 0.1824 | −0.0805 |
| 1.165 | 0.7660 |
| 0.5935 | 0.5174 |
| −0.8918 | 0.5918 |
| 0.5773 | 1.096 |
| −0.8249 | 0.1289 |
| −1.157 | 2.008 |
| 0.7780 | 0.8816 |
| −1.204 | 0.9219 |
| 0.3067 | −0.0010 |
| −0.8337 | 0.2404 |
| 1.418 | 1.011 |
| 0.7118 | 1.461 |
| −0.4025 | 0.9465 |
| 0.7994 | 0.7091 |
| 0.4265 | −0.5284 |
| −1.170 | 1.625 |
| −0.2062 | −0.4512 |
| −0.9306 | 1.165 |
| 0.4494 | 0.6359 |
| −0.6448 | 0.5104 |
| −0.2314 | 0.0189 |
| −1.236 | 2.067 |
| −0.9610 | 1.459 |
| 0.1340 | 0.2288 |
| −0.9991 | 0.9358 |
| −0.1415 | 0.4886 |
| 0.1673 | 0.1283 |
First 60 of 118 rows.
Assumptions
- Independent rows — Permutation and cross tests assume exchangeable rows; for time series or clustered data use block methods.
- Ties — Ties in x are broken at random (seeded) for ξ.
The same variables under other dependence measures
| Measure | Value | Sensitive to |
|---|---|---|
| Pearson r | −0.0277 | Linear association |
| Spearman ρ | −0.0254 | Monotonic association |
| ξ(x → y) | 0.4019 | y is a function of x (any shape) |
| ξ(y → x) | 0.0034 | x is a function of y (any shape) |
| Hoeffding 30·D | 0.0676 | Any departure from independence (ranks) |
| Distance correlation | 0.4592 | Any dependence (finite means) |
| Bias-corrected dCor | 0.1767 | Any dependence; ≈ 0 under independence |
| HSIC (median bandwidth) | 0.0194 | Any dependence (kernel) |
- 2 of 120 rows were left out because a value was missing.
- Chatterjee's ξ(x → y); one-sided test of independence (asymptotic normal p-value).
The exact R script · R R version 4.5.1 (2025-06-13)
# Test for any dependence (ξ, Hoeffding, distance correlation, HSIC)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method correlation.dependence 1.0.1 · spec 3c303f0c5fe8f8c7
# Dataset: f_dependence (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/f_dependence.parquet", col_select = c("x", "y quadratic")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("x", "y quadratic")]), , 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("x", "y quadratic")) # infinite values stop the run (registry/errors.yaml)
# %% Dependence
x_cols <- c("x")
y_cols <- c("y quadratic")
measure <- "xi"
calibration <- "auto"
n_perm <- as.integer(999)
bandwidth <- "median"
standardize <- TRUE
max_n <- as.integer(1000)
seed <- 42 # shared Wichmann-Hill streams: ties in x, permutations, subsample, split
univariate <- length(x_cols) == 1 && length(y_cols) == 1
if (measure %in% c("xi", "hoeffding") && !univariate) stop("ξ and Hoeffding's D compare one x variable with one y variable.")
if (length(intersect(x_cols, y_cols))) stop("A column cannot be both an x and a y variable.")
X <- as.matrix(df[x_cols]); storage.mode(X) <- "double"
Y <- as.matrix(df[y_cols]); storage.mode(Y) <- "double"
n <- nrow(df)
if (n < 10) cs_error("CS_E_TOO_FEW_ROWS", what = "A dependence test", min = 10, n = n)
for (col in c(x_cols, y_cols)) {
# a constant variable cannot depend on anything (most measures are 0 / 0)
if (length(unique(as.double(df[[col]]))) < 2) cs_error("CS_E_CONSTANT", column = col)
}
if (n > max_n) { # n x n matrices: analyze a seeded random subsample
idx <- sort(cs_rperm(cs_rng(seed + 2), n)[seq_len(max_n)])
warnings <- c(warnings, sprintf("Distance and kernel measures used a random subsample of %d of %d rows (seed %d).", max_n, n, as.integer(seed)))
} else {
idx <- seq_len(n)
}
Xs <- X[idx, , drop = FALSE]
Ys <- Y[idx, , drop = FALSE]
n_used <- if (measure != "xi") length(idx) else n
scaled <- function(M) {
if (!standardize) return(M)
sweep(sweep(M, 2, colMeans(M), "-"), 2, apply(M, 2, stats::sd), "/")
}
if (calibration == "auto") {
calibration <- c(xi = "asymptotic", hoeffding = "permutation", dcor = "permutation", hsic = "permutation")[measure]
if (is.na(calibration)) calibration <- "normal"
calibration <- unname(calibration)
}
if (measure %in% c("cross_hsic", "cross_dcov")) {
calibration <- "normal"
} else if (calibration == "asymptotic" && !(measure %in% c("xi", "dcor"))) {
stop("Only ξ and distance correlation have an asymptotic test; choose permutations.")
}
z <- NULL; test_statistic <- NULL; dof <- NULL; count <- NULL
bw_x <- NULL; bw_y <- NULL
used_perm <- calibration == "permutation"
if (measure == "xi") {
xv <- X[, 1]; yv <- Y[, 1]
res <- cs_xi(xv, yv, seed)
statistic <- res$statistic
label <- "Chatterjee's ξ(x → y)"
if (used_perm) {
pr <- cs_perm_pvalue(function(pm) cs_xi(xv, yv[pm], seed)$statistic, statistic, n, n_perm, seed + 1)
p <- pr$p; count <- pr$count
} else {
z <- res$z; p <- res$p
}
} else if (measure == "hoeffding") {
xv <- Xs[, 1]; yv <- Ys[, 1]
statistic <- cs_hoeffding_d(xv, yv)
label <- "Hoeffding's D"
pr <- cs_perm_pvalue(function(pm) cs_hoeffding_d(xv, yv[pm]), statistic, length(xv), n_perm, seed + 1)
p <- pr$p; count <- pr$count
} else if (measure == "dcor") {
dc <- cs_dcov(scaled(Xs), scaled(Ys))
if (used_perm) {
A <- dc$A; B <- dc$B
statistic <- dc$dcor; test_statistic <- dc$nv2
label <- "Distance correlation"
m <- nrow(A)
pr <- cs_perm_pvalue(function(pm) m * mean(A * B[pm, pm]), test_statistic, m, n_perm, seed + 1)
p <- pr$p; count <- pr$count
} else {
statistic <- dc$dcor_bc; test_statistic <- dc$t; dof <- dc$df; p <- dc$p_t
label <- "Bias-corrected distance correlation"
}
} else if (measure == "hsic") {
Xh <- scaled(Xs); Yh <- scaled(Ys)
if (bandwidth == "median") { bw_x <- cs_median_bandwidth(Xh); bw_y <- cs_median_bandwidth(Yh) } else { bw_x <- 1; bw_y <- 1 }
hs <- cs_hsic(Xh, Yh, bw_x, bw_y)
statistic <- hs$statistic
label <- "HSIC"
Kc <- hs$Kc; Lc <- hs$Lc
m <- nrow(Kc)
pr <- cs_perm_pvalue(function(pm) sum(Kc * Lc[pm, pm]) / (m - 1)^2, statistic, m, n_perm, seed + 1)
p <- pr$p; count <- pr$count
} else {
Xh <- scaled(Xs); Yh <- scaled(Ys)
kernel <- if (measure == "cross_hsic") "gaussian" else "distance"
if (kernel == "gaussian") {
if (bandwidth == "median") { bw_x <- cs_median_bandwidth(Xh); bw_y <- cs_median_bandwidth(Yh) } else { bw_x <- 1; bw_y <- 1 }
}
res <- cs_cross_stat(Xh, Yh, kernel, if (is.null(bw_x)) 1 else bw_x, if (is.null(bw_y)) 1 else bw_y, seed + 3)
statistic <- res$statistic; z <- res$z; p <- res$p
label <- if (kernel == "gaussian") "Cross HSIC" else "Cross distance covariance"
n_used <- 2 * res$half
}
# %% Profile: the same pair under other measures (estimates only)
xi_xy <- NULL; xi_yx <- NULL; hoeffding_30d <- NULL; pearson <- NULL; spearman <- NULL
Xp <- scaled(Xs); Yp <- scaled(Ys)
dcor_all <- cs_dcov(Xp, Yp)
dcor_v <- dcor_all$dcor; dcor_bc <- dcor_all$dcor_bc
rows <- list()
if (univariate) {
xa <- Xs[, 1]; ya <- Ys[, 1]
pearson <- stats::cor(xa, ya)
spearman <- stats::cor(rank(xa), rank(ya))
xi_xy <- cs_xi(xa, ya, seed)$statistic
xi_yx <- cs_xi(ya, xa, seed)$statistic
hoeffding_30d <- 30 * cs_hoeffding_d(xa, ya)
rows <- list(list(measure = "Pearson r", value = pearson, detects = "Linear association"),
list(measure = "Spearman ρ", value = spearman, detects = "Monotonic association"),
list(measure = "ξ(x → y)", value = xi_xy, detects = "y is a function of x (any shape)"),
list(measure = "ξ(y → x)", value = xi_yx, detects = "x is a function of y (any shape)"),
list(measure = "Hoeffding 30·D", value = hoeffding_30d, detects = "Any departure from independence (ranks)"))
}
hsic_med <- cs_hsic(Xp, Yp, cs_median_bandwidth(Xp), cs_median_bandwidth(Yp))$statistic
rows <- c(rows, list(list(measure = "Distance correlation", value = dcor_v, detects = "Any dependence (finite means)"),
list(measure = "Bias-corrected dCor", value = dcor_bc, detects = "Any dependence; ≈ 0 under independence"),
list(measure = "HSIC (median bandwidth)", value = hsic_med, detects = "Any dependence (kernel)")))
# %% Result
alpha <- 0.050000000000000044
verdict <- if (p < alpha) sprintf("The variables are not independent (%s).", cs_fmt_p(p)) else sprintf("The data are compatible with independence (%s).", cs_fmt_p(p))
summary <- sprintf("%s between %s and %s was %.3f (n = %d). %s", label, paste(x_cols, collapse = ", "), paste(y_cols, collapse = ", "), statistic, as.integer(n_used), verdict)
how <- switch(calibration,
asymptotic = if (measure == "xi") "asymptotic normal p-value" else "bias-corrected t-test",
permutation = sprintf("%d Monte Carlo permutations (seed %d)", n_perm, as.integer(seed)),
normal = "studentized cross statistic, standard normal p-value")
apa <- sprintf("%s = %.3f, %s, N = %d", label, statistic, cs_fmt_p(p), as.integer(n_used))
statistics_rows <- list(list(key = "statistic", label = label, value = statistic))
if (!is.null(test_statistic)) statistics_rows <- c(statistics_rows, list(list(key = "test_statistic", label = if (!is.null(dof)) "t" else "nV²", value = test_statistic)))
if (!is.null(z)) statistics_rows <- c(statistics_rows, list(list(key = "z", label = "z", value = z)))
statistics_rows <- c(statistics_rows, list(list(key = "p", label = "p", value = p, format = "p"), list(key = "n", label = "n", value = n_used)))
charts <- list()
if (univariate) {
sel <- unique(round(seq(1, n, length.out = min(n, 5000))))
charts <- list(cs_chart("scatter", "scatter", sprintf("%s against %s", y_cols[1], x_cols[1]), list(x = cs_col(x_cols[1], X[sel, 1]), y = cs_col(y_cols[1], Y[sel, 1]))))
}
cs_publish(list(
method = "correlation.dependence",
methodVersion = "1.0.1",
title = sprintf("Test of independence: %s", label),
engine = cs_engine_info("stats", "nanoparquet"),
n = n_used,
summary = summary,
apa = apa,
statistics = statistics_rows,
tables = list(list(key = "profile", title = "The same variables under other dependence measures", columns = list(
list(key = "measure", label = "Measure", type = "string"), list(key = "value", label = "Value", type = "number"),
list(key = "detects", label = "Sensitive to", type = "string")), rows = rows)),
effectSizes = list(list(key = "statistic", label = label, value = statistic, method = how)),
assumptions = list(
list(key = "independence", label = "Independent rows", status = "info",
detail = "Permutation and cross tests assume exchangeable rows; for time series or clustered data use block methods."),
list(key = "ties", label = "Ties", status = "info",
detail = if (measure == "xi") "Ties in x are broken at random (seeded) for ξ." else "Ties are handled by midranks or exact distances.")
),
charts = charts,
warnings = warnings,
notes = list(sprintf("%s; one-sided test of independence (%s).", label, how)),
values = list(measure = measure, measure_label = label, statistic = statistic, z = z, test_statistic = test_statistic, df = dof,
p = p, calibration = calibration, n = n, n_used = n_used, n_perm = if (used_perm) n_perm else NULL, count = count,
xi_xy = xi_xy, xi_yx = xi_yx, dcor = dcor_v, dcor_bc = dcor_bc, hoeffding_30d = hoeffding_30d, hsic = hsic_med,
pearson = pearson, spearman = spearman, bandwidth_x = bw_x, bandwidth_y = bw_y)
))
Chatterjee's ξ(x → y) = 0.402, p < .001, N = 118
- Chatterjee's ξ(x → y)
- 0.4019
- z
- 6.901
- p
- < .001
- n
- 118
Effect size
- Chatterjee's ξ(x → y) 0.4019
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Independent rows — Permutation and cross tests assume exchangeable rows; for time series or clustered data use block methods.
- Ties — Ties in x are broken at random (seeded) for ξ.
The same variables under other dependence measures
| Measure | Value | Sensitive to |
|---|---|---|
| Pearson r | −0.0277 | Linear association |
| Spearman ρ | −0.0254 | Monotonic association |
| ξ(x → y) | 0.4019 | y is a function of x (any shape) |
| ξ(y → x) | 0.0034 | x is a function of y (any shape) |
| Hoeffding 30·D | 0.0676 | Any departure from independence (ranks) |
| Distance correlation | 0.4592 | Any dependence (finite means) |
| Bias-corrected dCor | 0.1767 | Any dependence; ≈ 0 under independence |
| HSIC (median bandwidth) | 0.0194 | Any dependence (kernel) |
- 2 of 120 rows were left out because a value was missing.
- Chatterjee's ξ(x → y); one-sided test of independence (asymptotic normal p-value).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Test for any dependence (ξ, Hoeffding, distance correlation, HSIC)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method correlation.dependence 1.0.1 · spec 3c303f0c5fe8f8c7
# Dataset: f_dependence (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 dependence
from codesplash.stats.rng import Rng
# %% Data
df = pd.read_parquet("tests/parity/fixtures/f_dependence.parquet", columns=["x", "y quadratic"])
n_input = len(df)
df = df.dropna(subset=["x", "y quadratic"]) # 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, ["x", "y quadratic"]) # infinite values stop the run (registry/errors.yaml)
# %% Dependence
x_cols = ["x"]
y_cols = ["y quadratic"]
measure = "xi"
calibration = "auto"
n_perm = int(999)
bandwidth = "median"
standardize = True
max_n = int(1000)
seed = 42 # shared Wichmann–Hill streams: ties in x, permutations, subsample, split
univariate = len(x_cols) == 1 and len(y_cols) == 1
if measure in ("xi", "hoeffding") and not univariate:
raise ValueError("ξ and Hoeffding's D compare one x variable with one y variable.")
if set(x_cols) & set(y_cols):
raise ValueError("A column cannot be both an x and a y variable.")
X = df[x_cols].to_numpy(dtype=float)
Y = df[y_cols].to_numpy(dtype=float)
n = len(df)
if n < 10:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="A dependence test", min=10, n=n)
for col, v in zip(x_cols + y_cols, np.column_stack([X, Y]).T):
if len(np.unique(v)) < 2: # a constant variable cannot depend on anything (most measures are 0 / 0)
cs.cs_error("CS_E_CONSTANT", column=col)
if n > max_n: # n × n matrices: analyze a seeded random subsample
idx = np.sort(Rng(seed + 2).permutation(n)[:max_n])
warnings.append(f"Distance and kernel measures used a random subsample of {max_n} of {n} rows (seed {seed}).")
else:
idx = np.arange(n)
Xs, Ys = X[idx], Y[idx]
n_used = len(idx) if measure != "xi" else n
def scaled(M):
return (M - M.mean(axis=0)) / M.std(axis=0, ddof=1) if standardize else M
if calibration == "auto":
calibration = {"xi": "asymptotic", "hoeffding": "permutation", "dcor": "permutation", "hsic": "permutation"}.get(measure, "normal")
if measure in ("cross_hsic", "cross_dcov"):
calibration = "normal"
elif calibration == "asymptotic" and measure not in ("xi", "dcor"):
raise ValueError("Only ξ and distance correlation have an asymptotic test; choose permutations.")
z = test_statistic = dof = count = None
bw_x = bw_y = None
used_perm = calibration == "permutation"
if measure == "xi":
xv, yv = X[:, 0], Y[:, 0]
res = dependence.xi(xv, yv, seed)
statistic = res["statistic"]
label = "Chatterjee's ξ(x → y)"
if used_perm:
pr = dependence.perm_pvalue(lambda pm: dependence.xi(xv, yv[pm], seed)["statistic"], statistic, n, n_perm, seed + 1)
p, count = pr["p"], pr["count"]
else:
z, p = res["z"], res["p"]
elif measure == "hoeffding":
xv, yv = Xs[:, 0], Ys[:, 0]
statistic = dependence.hoeffding_d(xv, yv)
label = "Hoeffding's D"
pr = dependence.perm_pvalue(lambda pm: dependence.hoeffding_d(xv, yv[pm]), statistic, len(xv), n_perm, seed + 1)
p, count = pr["p"], pr["count"]
elif measure == "dcor":
dc = dependence.dcov(scaled(Xs), scaled(Ys))
if used_perm:
A, B = dc["A"], dc["B"]
statistic, test_statistic = dc["dcor"], dc["nv2"]
label = "Distance correlation"
m = A.shape[0]
pr = dependence.perm_pvalue(lambda pm: m * float(np.mean(A * B[np.ix_(pm, pm)])), test_statistic, m, n_perm, seed + 1)
p, count = pr["p"], pr["count"]
else:
statistic, test_statistic, dof, p = dc["dcor_bc"], dc["t"], dc["df"], dc["p_t"]
label = "Bias-corrected distance correlation"
elif measure == "hsic":
Xh, Yh = scaled(Xs), scaled(Ys)
bw_x, bw_y = (dependence.median_bandwidth(Xh), dependence.median_bandwidth(Yh)) if bandwidth == "median" else (1.0, 1.0)
hs = dependence.hsic(Xh, Yh, bw_x, bw_y)
statistic = hs["statistic"]
label = "HSIC"
Kc, Lc = hs["Kc"], hs["Lc"]
m = Kc.shape[0]
pr = dependence.perm_pvalue(lambda pm: float(np.sum(Kc * Lc[np.ix_(pm, pm)]) / (m - 1) ** 2), statistic, m, n_perm, seed + 1)
p, count = pr["p"], pr["count"]
else:
Xh, Yh = scaled(Xs), scaled(Ys)
kernel = "gaussian" if measure == "cross_hsic" else "distance"
if kernel == "gaussian":
bw_x, bw_y = (dependence.median_bandwidth(Xh), dependence.median_bandwidth(Yh)) if bandwidth == "median" else (1.0, 1.0)
res = dependence.cross_stat(Xh, Yh, kernel, bw_x or 1.0, bw_y or 1.0, seed + 3)
statistic, z, p = res["statistic"], res["z"], res["p"]
label = "Cross HSIC" if kernel == "gaussian" else "Cross distance covariance"
n_used = 2 * res["half"]
# %% Profile: the same pair under other measures (estimates only)
xi_xy = xi_yx = hoeffding_30d = pearson = spearman = hsic_med = None
Xp, Yp = scaled(Xs), scaled(Ys)
dcor_all = dependence.dcov(Xp, Yp)
dcor_v, dcor_bc = dcor_all["dcor"], dcor_all["dcor_bc"]
rows = []
if univariate:
xa, ya = Xs[:, 0], Ys[:, 0]
pearson = float(np.corrcoef(xa, ya)[0, 1])
spearman = float(np.corrcoef(stats.rankdata(xa), stats.rankdata(ya))[0, 1])
xi_xy = dependence.xi(xa, ya, seed)["statistic"]
xi_yx = dependence.xi(ya, xa, seed)["statistic"]
hoeffding_30d = 30 * dependence.hoeffding_d(xa, ya)
rows += [{"measure": "Pearson r", "value": pearson, "detects": "Linear association"},
{"measure": "Spearman ρ", "value": spearman, "detects": "Monotonic association"},
{"measure": "ξ(x → y)", "value": xi_xy, "detects": "y is a function of x (any shape)"},
{"measure": "ξ(y → x)", "value": xi_yx, "detects": "x is a function of y (any shape)"},
{"measure": "Hoeffding 30·D", "value": hoeffding_30d, "detects": "Any departure from independence (ranks)"}]
hsic_med = dependence.hsic(Xp, Yp, dependence.median_bandwidth(Xp), dependence.median_bandwidth(Yp))["statistic"]
rows += [{"measure": "Distance correlation", "value": dcor_v, "detects": "Any dependence (finite means)"},
{"measure": "Bias-corrected dCor", "value": dcor_bc, "detects": "Any dependence; ≈ 0 under independence"},
{"measure": "HSIC (median bandwidth)", "value": hsic_med, "detects": "Any dependence (kernel)"}]
# %% Result
alpha = 0.050000000000000044
names = lambda cols: ", ".join(cols)
verdict = (f"The variables are not independent ({cs.fmt_p(p)})." if p < alpha
else f"The data are compatible with independence ({cs.fmt_p(p)}).")
summary = f"{label} between {names(x_cols)} and {names(y_cols)} was {statistic:.3f} (n = {n_used}). {verdict}"
how = {"asymptotic": "asymptotic normal p-value" if measure == "xi" else "bias-corrected t-test",
"permutation": f"{n_perm} Monte Carlo permutations (seed {seed})", "normal": "studentized cross statistic, standard normal p-value"}[calibration]
apa = f"{label} = {statistic:.3f}, {cs.fmt_p(p)}, N = {n_used}"
statistics_rows = [{"key": "statistic", "label": label, "value": statistic}]
if test_statistic is not None:
statistics_rows.append({"key": "test_statistic", "label": "t" if dof is not None else "nV²", "value": test_statistic})
if z is not None:
statistics_rows.append({"key": "z", "label": "z", "value": z})
statistics_rows += [{"key": "p", "label": "p", "value": p, "format": "p"}, {"key": "n", "label": "n", "value": n_used}]
charts = []
if univariate:
sel = np.unique(np.round(np.linspace(0, n - 1, min(n, 5000))).astype(int))
charts.append(cs.chart("scatter", "scatter", f"{y_cols[0]} against {x_cols[0]}", {"x": cs.col(x_cols[0], X[sel, 0]), "y": cs.col(y_cols[0], Y[sel, 0])}))
cs.publish({
"method": "correlation.dependence",
"methodVersion": "1.0.1",
"title": f"Test of independence: {label}",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n_used,
"summary": summary,
"apa": apa,
"statistics": statistics_rows,
"tables": [{"key": "profile", "title": "The same variables under other dependence measures", "columns": [
{"key": "measure", "label": "Measure", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
{"key": "detects", "label": "Sensitive to", "type": "string"}], "rows": rows}],
"effectSizes": [{"key": "statistic", "label": label, "value": statistic, "method": how}],
"assumptions": [
{"key": "independence", "label": "Independent rows", "status": "info",
"detail": "Permutation and cross tests assume exchangeable rows; for time series or clustered data use block methods."},
{"key": "ties", "label": "Ties", "status": "info",
"detail": "Ties in x are broken at random (seeded) for ξ." if measure == "xi" else "Ties are handled by midranks or exact distances."},
],
"charts": charts,
"warnings": warnings,
"notes": [f"{label}; one-sided test of independence ({how})."],
"values": {"measure": measure, "measure_label": label, "statistic": statistic, "z": z, "test_statistic": test_statistic, "df": dof,
"p": p, "calibration": calibration, "n": n, "n_used": n_used, "n_perm": n_perm if used_perm else None, "count": count,
"xi_xy": xi_xy, "xi_yx": xi_yx, "dcor": dcor_v, "dcor_bc": dcor_bc, "hoeffding_30d": hoeffding_30d, "hsic": hsic_med,
"pearson": pearson, "spearman": spearman, "bandwidth_x": bw_x, "bandwidth_y": bw_y},
})
The card reports the measure you chose plus the others for comparison, including Pearson and Spearman. A large gap between ξ or dCor and Pearson is your cue to look at the plot, because the relationship isn't a straight line.
Check your understanding
CheckpointCheck yourself
Pearson's r = 0.01 and bias-corrected distance correlation = 0.45 with p < .001. What's the most likely situation?
Show the answer
Answer: b
Distance correlation detects dependence of any form. A big gap from Pearson usually means curved or non-monotonic structure.
Check yourself
What does ξ(x → y) much larger than ξ(y → x) suggest?
Show the answer
Answer: b
ξ measures how well one variable determines the other. It says nothing about causation.
Check yourself
You want to test whether a set of 5 sensor readings is related to a set of 3 outcomes. What fits?
Show the answer
Answer: c
Pearson and ξ compare two single columns. Distance correlation and HSIC work with sets of variables.
Check yourself
You expect a simple increasing trend with a lot of noise. Why might Spearman be better than ξ?
Show the answer
Answer: a
General tests pay for their generality. If you know the shape you expect, a test aimed at that shape usually needs fewer rows.
Do it on your own data
In the appPick the columns and a Measure. Permutation calibration is available for all but the cross tests, and it runs on the shared random stream, so Python and R give the same p-value.
import numpy as np
from scipy import stats
rng = np.random.default_rng(1)
x = rng.normal(size=300)
y = x**2 + rng.normal(scale=0.3, size=300)
print(stats.pearsonr(x, y).statistic)
print(stats.chatterjeexi(x, y).statistic) # SciPy 1.15+xi <- function(x, y) { # no ties assumed
r <- rank(y[order(x)])
1 - 3 * sum(abs(diff(r))) / (length(y)^2 - 1)
}
set.seed(1)
x <- rnorm(300)
y <- x^2 + rnorm(300, sd = 0.3)
c(pearson = cor(x, y), xi = xi(x, y))These two scripts draw different random data, so their numbers differ a little.
Recap
Recap- Zero correlation doesn't rule out a strong relationship.
- ξ is fast and directional; Hoeffding's D is a tuning-free omnibus for a pair.
- Distance correlation and HSIC handle sets of variables; the cross versions scale to large .
- General tests have less power against simple trends, so use the most specific test you can justify.
Concepts in this lesson