Skip to content

CDiscover · discover.cluster_inference

Are these clusters really different? (selective inference)

After hierarchical clustering, do two of the clusters truly differ in their means, or did the clustering just split one group?

Clustering then testing the clusters with an ordinary test double-dips: the clusters were chosen to look different, so a t-test or chi-squared test on them almost always rejects, even on pure noise. This method gives the selective p-value of Gao, Bien & Witten (2022) for every pair of clusters from Euclidean hierarchical clustering: it asks how far apart the two cluster means would be when the data still produced these same two clusters, and estimates that conditional p-value by importance sampling (each draw re-runs the clustering). The naive p-value is shown beside it for contrast. Experimental.

Experimental Python and R agree to 6 decimals Seeded Also called selective inference, clusterpval, post-clustering inference…

A real result

Example “One cloud average”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Are these clusters really different? (selective inference)Recorded · Python and R agreeRecorded 2026-11-21 · 17 values compared
R

3 pair(s) of 3 clusters (average linkage) tested; clusters 1 and 2: selective p = 0.612 (naive p = 9.48e-12).

Selective p (1 vs 2)
.612
Naive p (1 vs 2)
< .001

Plots

Naive and selective p-values by pairHow do categories compare on one value — and across up to three groups?

The naive p ignores that the clusters were found in the same data; the selective p accounts for it.

View data
ClustersTestp-value
1 vs 2Naive9.480e-12
1 vs 2Selective0.6123
1 vs 3Naive0.0062
1 vs 3Selective0.2694
2 vs 3Naive1.301e-7
2 vs 3Selective0.0817

Difference in means for each pair of clusters

ClustersRows (first)Rows (second)Distance between meansNaive pSelective pDraws keptEffective draws
1 vs 27183.6479.480e-120.612315633.510
1 vs 37115.1000.00620.269420078.212
2 vs 3818.4621.301e-70.081721445.340
Python

3 pair(s) of 3 clusters (average linkage) tested; clusters 1 and 2: selective p = 0.612 (naive p = 9.48e-12).

Selective p (1 vs 2)
.612
Naive p (1 vs 2)
< .001

To keep this page light, the plots are shown once, under the R tab.

Difference in means for each pair of clusters

ClustersRows (first)Rows (second)Distance between meansNaive pSelective pDraws keptEffective draws
1 vs 27183.6479.480e-120.612315633.510
1 vs 37115.1000.00620.269420078.212
2 vs 3818.4621.301e-70.081721445.340

Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.

Worked examples in the app

  • One cloud averageclu4_sigclust · features: g1, g2, g3, g4, g5
  • Two clouds average k2clu4_sigclust · features: c1, c2, c3, c4, c5
  • Two clouds ward k3clu4_sigclust · features: c1, c2, c3, c4, c5
  • Iris complete standardizedml_iris · features: sepal_length, sepal_width, petal_length, petal_width
  • Degenerate constantclu4_sigclust · features: g1, g2, g3, g4, g5
  • Degenerate tiesclu4_sigclust · features: g1, g2, g3, g4, g5
  • Degenerate all naclu4_sigclust · features: g1, g2, g3, g4, g5
  • Degenerate infclu4_sigclust · features: g1, g2, g3, g4, g5

In the guides

Where it sits in the decision guides

  • Testing and comparing clusterings (SigClust, selective inference, ARI, CKA) · DS & ML Decision Guide · Discover — find structure without labels
  • Discover: cluster quality (silhouette, ARI); coherence (topics); stability and interpretability · DS & ML Decision Guide · How to evaluate — common metrics by question type

What you need

Variablesnumeric · 1–200 columns
Numbers that define closeness (rows with a missing value are left out). The test assumes they share one noise SD.

Choices you make

model

Linkagedefault average

How hierarchical clustering measures the distance between clusters (Euclidean distances between rows).

  • Average(default) — Mean distance between the two clusters' rows.
  • Complete — Largest distance between the two clusters' rows.
  • Single — Smallest distance; tends to chain.
  • Ward — Merge that adds the least within-cluster variance (R's ward.D2).
Clustersdefault 3

Where the tree is cut; every pair of the k clusters is tested.

Monte Carlo drawsdefault 1000

Importance-sampling draws per pair; each re-runs the clustering, so time grows with draws × pairs.

Scale variablesdefault none

The test assumes one common noise SD across variables.

  • Keep as they are(default) — For variables in the same units.
  • Standardize — Gives every variable unit SD first (the noise SD is then estimated after standardizing).

What it reports

n
Rows and variables used, clusters at the cut, and the number of cluster pairs tested.
q
Rows and variables used, clusters at the cut, and the number of cluster pairs tested.
k
Rows and variables used, clusters at the cut, and the number of cluster pairs tested.
sigma
One noise SD from all variables around their means; it overstates the noise when clusters are real, which is conservative.
n_pairs
Rows and variables used, clusters at the cut, and the number of cluster pairs tested.
p_selective
A p-value that conditions on how the clusters were chosen, so it stays valid when the same data formed them.
p_naive
The χ² test of a difference in cluster means that ignores that the clusters were found in the same data; far too small.
distance
Euclidean length of the difference between two clusters' mean rows; the test statistic of the selective test.
kept
Monte Carlo draws whose re-clustered data reproduced the two clusters; only these count toward the selective p.
ess
Monte Carlo draws whose re-clustered data reproduced the two clusters; only these count toward the selective p.
min_p_selective
A p-value that conditions on how the clusters were chosen, so it stays valid when the same data formed them.

Per group, level or term: p_selective[<a>-<b>], p_naive[<a>-<b>]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-8). Python uses scipy; R uses codesplashr.

Default traps between the two languages

  • Both engines draw the same normal deviates from the shared stream and re-run the same Euclidean hierarchical clustering (scipy's linkage and fcluster in Python, hclust and cutree in R), so the same draws are kept. The clusterpval R package (GitHub only) computes the exact selective p-value for average, centroid and single linkage; this method uses its Monte Carlo approach for every linkage, so values differ by Monte Carlo error.
Python

The exact script CodeSplash ran for example “One cloud average” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Are these clusters really different? (selective inference)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.cluster_inference 1.0.0 · spec 12586d9a59e1c47d
# Dataset: clu4_sigclust (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

import codesplash as cs
from codesplash.ml import cluster as csc
from codesplash.ml import cluster_checks as ck
from codesplash.ml import embed as csembed
from codesplash.stats.rng import Rng

# %% Data
FEATURES = ["g1", "g2", "g3", "g4", "g5"]
SEED = 42
LINKAGE = "average"
K = 3
DRAWS = 300
SCALE = "none"
df = pd.read_parquet("tests/parity/fixtures/clu4_sigclust.parquet", columns=FEATURES)
n_input = len(df)
cs.check_finite_columns(df, FEATURES)  # ±Inf stops with CS_E_NOT_FINITE in both engines
rows = csembed.complete_rows(df, FEATURES)
warnings = []
if len(rows) < n_input:
    warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a value was missing.")
cs.check_rows(len(rows), K + 2, "Selective inference after clustering")
X = csembed.numeric_matrix(df, FEATURES, rows)
if np.all(np.ptp(X, axis=0) == 0):
    cs.cs_error("CS_E_CONSTANT", column=", ".join(FEATURES))
if SCALE == "standardize":
    flat = np.ptp(X, axis=0) == 0
    X = csembed.standardize(X, ddof=1)
    X[:, flat] = 0.0  # constant columns exactly 0 in both engines

# %% Clusters and the noise SD
labels = csc.canonical(ck.hclust_cut(X, LINKAGE, K))
k_found = int(labels.max())
if k_found < 2:
    cs.cs_error("CS_E_UNDEFINED", what="Selective inference", reason="the tree has fewer than two clusters at this cut")
sigma = ck.pooled_sigma(X)

# %% Selective p-value for every pair (shared stream, pair by pair)
rng = Rng(SEED)
pairs = []
values = {"n": len(rows), "q": X.shape[1], "k": k_found, "sigma": sigma}
for a in range(1, k_found + 1):
    for b in range(a + 1, k_found + 1):
        res = ck.selective_pair(X, labels == a, labels == b, LINKAGE, K, sigma, DRAWS, rng)
        pairs.append((a, b, res))
        values[f"p_selective[{a}-{b}]"] = res["p_selective"]
        values[f"p_naive[{a}-{b}]"] = res["p_naive"]
first = pairs[0][2]
values.update({
    "n_pairs": len(pairs), "p_selective": first["p_selective"], "p_naive": first["p_naive"], "distance": first["stat"],
    "kept": first["kept"], "ess": first["ess"],
    "min_p_selective": min((r["p_selective"] for _, _, r in pairs if r["p_selective"] == r["p_selective"]), default=None),
})
low_ess = [f"{a}–{b}" for a, b, r in pairs if r["kept"] > 0 and r["ess"] < 20]
if low_ess:
    warnings.append("Few effective draws for pair(s) " + ", ".join(low_ess) + "; raise the number of draws for a steadier p-value.")
none_kept = [f"{a}–{b}" for a, b, r in pairs if r["kept"] == 0]
if none_kept:
    warnings.append("No draw reproduced pair(s) " + ", ".join(none_kept) + "; their selective p-value is undefined at this number of draws.")
tables = [{
    "key": "pairs",
    "title": "Difference in means for each pair of clusters",
    "columns": [
        {"key": "pair", "label": "Clusters", "type": "string"},
        {"key": "n_a", "label": "Rows (first)", "type": "integer"},
        {"key": "n_b", "label": "Rows (second)", "type": "integer"},
        {"key": "distance", "label": "Distance between means", "type": "number"},
        {"key": "p_naive", "label": "Naive p", "type": "p"},
        {"key": "p_selective", "label": "Selective p", "type": "p"},
        {"key": "kept", "label": "Draws kept", "type": "integer"},
        {"key": "ess", "label": "Effective draws", "type": "number"},
    ],
    "rows": [
        {"pair": f"{a} vs {b}", "n_a": r["n1"], "n_b": r["n2"], "distance": r["stat"], "p_naive": r["p_naive"],
         "p_selective": r["p_selective"], "kept": r["kept"], "ess": r["ess"]}
        for a, b, r in pairs
    ],
}]

# %% Chart: naive vs selective p-values
cats, vals, grp = [], [], []
for a, b, r in pairs:
    for label, key in (("Naive", "p_naive"), ("Selective", "p_selective")):
        if r[key] == r[key]:
            cats.append(f"{a} vs {b}")
            vals.append(r[key])
            grp.append(label)
charts = [cs.chart(
    "pvalues", "cleveland-dot", "Naive and selective p-values by pair",
    {
        "category": cs.col("Clusters", cats, "categorical", levels=[f"{a} vs {b}" for a, b, _ in pairs]),
        "value": cs.col("p-value", vals, "numeric"),
        "group": cs.col("Test", grp, "categorical", levels=["Naive", "Selective"]),
    },
    note="The naive p ignores that the clusters were found in the same data; the selective p accounts for it.",
)]

# %% Result
ps = first["p_selective"]
cs.publish({
    "title": "Are these clusters really different? (selective inference)",
    "engine": cs.engine_info("scipy", "numpy", "pandas"),
    "n": len(rows),
    "summary": (
        f"{len(pairs)} pair(s) of {k_found} clusters ({LINKAGE} linkage) tested; clusters 1 and 2: selective p = "
        + (f"{ps:.3g}" if ps == ps else "undefined") + f" (naive p = {first['p_naive']:.3g})."
    ),
    "statistics": [
        {"key": "p_selective", "label": "Selective p (1 vs 2)", "value": ps, "format": "p"},
        {"key": "p_naive", "label": "Naive p (1 vs 2)", "value": first["p_naive"], "format": "p"},
    ],
    "tables": tables,
    "values": values,
    "charts": charts,
    "warnings": warnings,
})
R

The exact script CodeSplash ran for example “One cloud average” · R version 4.5.1 (2025-06-13)

# Are these clusters really different? (selective inference)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.cluster_inference 1.0.0 · spec 12586d9a59e1c47d
# Dataset: clu4_sigclust (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
FEATURES <- c("g1", "g2", "g3", "g4", "g5")
SEED <- 42
LINKAGE <- "average"
K <- 3
DRAWS <- 300
SCALE <- "none"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/clu4_sigclust.parquet", col_select = FEATURES))
n_input <- nrow(df)
cs_check_finite_columns(df, FEATURES)  # ±Inf stops with CS_E_NOT_FINITE in both engines
rows <- cs_ml_complete_rows(df, FEATURES)
warnings <- list()
if (length(rows) < n_input) warnings <- c(warnings, sprintf("%d of %d rows were left out because a value was missing.", n_input - length(rows), n_input))
cs_check_rows(length(rows), K + 2, "Selective inference after clustering")
X <- cs_ml_numeric_matrix(df, FEATURES, rows)
if (all(apply(X, 2, function(v) max(v) - min(v)) == 0)) cs_error("CS_E_CONSTANT", column = paste(FEATURES, collapse = ", "))
if (SCALE == "standardize") {
  flat <- apply(X, 2, function(v) max(v) - min(v)) == 0
  s <- apply(X, 2, stats::sd)
  s[flat] <- 1
  X <- sweep(sweep(X, 2, colMeans(X)), 2, s, "/")
  X[, flat] <- 0  # constant columns exactly 0 in both engines
}

# %% Clusters and the noise SD
labels <- cs_ml_canonical(cs_ml_hclust_cut(X, LINKAGE, K))
k_found <- max(labels)
if (k_found < 2) cs_error("CS_E_UNDEFINED", what = "Selective inference", reason = "the tree has fewer than two clusters at this cut")
sigma <- cs_ml_pooled_sigma(X)

# %% Selective p-value for every pair (shared stream, pair by pair)
rng <- cs_rng(SEED)
pairs <- list()
values <- list(n = length(rows), q = ncol(X), k = k_found, sigma = sigma)
for (a in seq_len(k_found)) {
  for (b in seq_len(k_found)) {
    if (b <= a) next
    res <- cs_ml_selective_pair(X, labels == a, labels == b, LINKAGE, K, sigma, DRAWS, rng)
    pairs[[length(pairs) + 1L]] <- list(a = a, b = b, r = res)
    values[[sprintf("p_selective[%d-%d]", a, b)]] <- res$p_selective
    values[[sprintf("p_naive[%d-%d]", a, b)]] <- res$p_naive
  }
}
first <- pairs[[1]]$r
psel <- vapply(pairs, function(x) x$r$p_selective, numeric(1))
values$n_pairs <- length(pairs)
values$p_selective <- first$p_selective
values$p_naive <- first$p_naive
values$distance <- first$stat
values$kept <- first$kept
values$ess <- first$ess
values["min_p_selective"] <- list(if (any(!is.nan(psel))) min(psel[!is.nan(psel)]) else NULL)
pair_name <- function(x, sep = "–") sprintf("%d%s%d", x$a, sep, x$b)
low_ess <- vapply(Filter(function(x) x$r$kept > 0 && x$r$ess < 20, pairs), pair_name, character(1))
if (length(low_ess)) warnings <- c(warnings, paste0("Few effective draws for pair(s) ", paste(low_ess, collapse = ", "), "; raise the number of draws for a steadier p-value."))
none_kept <- vapply(Filter(function(x) x$r$kept == 0, pairs), pair_name, character(1))
if (length(none_kept)) warnings <- c(warnings, paste0("No draw reproduced pair(s) ", paste(none_kept, collapse = ", "), "; their selective p-value is undefined at this number of draws."))
tables <- list(list(
  key = "pairs", title = "Difference in means for each pair of clusters",
  columns = list(
    list(key = "pair", label = "Clusters", type = "string"),
    list(key = "n_a", label = "Rows (first)", type = "integer"),
    list(key = "n_b", label = "Rows (second)", type = "integer"),
    list(key = "distance", label = "Distance between means", type = "number"),
    list(key = "p_naive", label = "Naive p", type = "p"),
    list(key = "p_selective", label = "Selective p", type = "p"),
    list(key = "kept", label = "Draws kept", type = "integer"),
    list(key = "ess", label = "Effective draws", type = "number")
  ),
  rows = lapply(pairs, function(x) list(pair = sprintf("%d vs %d", x$a, x$b), n_a = x$r$n1, n_b = x$r$n2, distance = x$r$stat,
                                        p_naive = x$r$p_naive, p_selective = x$r$p_selective, kept = x$r$kept, ess = x$r$ess))
))

# %% Chart: naive vs selective p-values
cats <- character(0)
vals <- numeric(0)
grp <- character(0)
for (x in pairs) {
  for (g in list(c("Naive", "p_naive"), c("Selective", "p_selective"))) {
    v <- x$r[[g[2]]]
    if (!is.nan(v)) {
      cats <- c(cats, sprintf("%d vs %d", x$a, x$b))
      vals <- c(vals, v)
      grp <- c(grp, g[1])
    }
  }
}
charts <- list(cs_chart("pvalues", "cleveland-dot", "Naive and selective p-values by pair", list(
  category = cs_col("Clusters", cats, "categorical", levels = vapply(pairs, function(x) sprintf("%d vs %d", x$a, x$b), character(1))),
  value = cs_col("p-value", vals, "numeric"),
  group = cs_col("Test", grp, "categorical", levels = c("Naive", "Selective"))
), note = "The naive p ignores that the clusters were found in the same data; the selective p accounts for it."))

# %% Result
ps <- first$p_selective
cs_publish(list(
  title = "Are these clusters really different? (selective inference)",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = sprintf("%d pair(s) of %d clusters (%s linkage) tested; clusters 1 and 2: selective p = %s (naive p = %s).",
                    length(pairs), k_found, LINKAGE, if (is.nan(ps)) "undefined" else format(signif(ps, 3)), format(signif(first$p_naive, 3))),
  statistics = list(list(key = "p_selective", label = "Selective p (1 vs 2)", value = ps, format = "p"),
                    list(key = "p_naive", label = "Naive p (1 vs 2)", value = first$p_naive, format = "p")),
  tables = tables,
  values = values,
  charts = charts,
  warnings = warnings
))

Sources

  • Gao LL, Bien J, Witten D (2022). Selective inference for hierarchical clustering. Journal of the American Statistical Association 119:332–342.
  • Chen YT, Witten D (2023). Selective inference for k-means clustering. JMLR 24(152):1–41.

From the CodeSplash method registry · discover.cluster_inference v1.0.0.