Do these rows clump at all?
Clustering always finds clusters. The Hopkins statistic and a VAT image check whether there is anything to find before you go looking.
What runs in CodeSplash
- Is there cluster structure? (Hopkins + VAT) Verified in Python and R
You will be able to
- Interpret a Hopkins statistic and its p-value
- Read a VAT image as blocks on a diagonal
- Say what a large p-value on a Hopkins test does and does not mean
Ask before you cluster
Readk-means will split a uniform cloud of points into as many groups as you request, and the groups will look tidy.
So check first. The Hopkins statisticHopkins statisticCompares nearest-neighbor distances from real rows with those from random points; near 0.5 = no structure, near 1 = clumped. compares two sets of nearest-neighbor distances: from a sample of real rows to their neighbors, and from uniformly scattered points in the same box to the real rows.
If the rows clump, scattered points sit far from the data while real rows sit close to each other, and approaches 1. If the rows are as spread out as random points, the distances match and sits near 0.5.
Make a guess
PredictPredict first
Two datasets, both scaled. Iris measures flowers from three species. US arrests records crime rates for 50 states, which vary fairly smoothly. Which do you expect to clump more strongly?
Reveal
Iris: = 0.994 with p < .001.
US arrests: = 0.594 with p = .274. States differ, but these data are compatible with no clumping at all.
The formula
ReadWith sampled rows, let be the distance from a uniform point to its nearest real row, and the distance from a real row to its nearest other real row:
Raising distances to the power of the dimension gives an exact Beta distribution when the rows have no structure, so the p-value is exact. Drawing several samples steadies the estimate; the card averages them and bases the p-value on the first draw.
See the blocks
ExploreA VAT image reorders rows so that neighbors sit together, then paints the distance matrix. Dark blocks on the diagonal mean groups of mutually close rows. The size of a block shows the size of the group.
View data
| row block | column block | mean distance |
|---|---|---|
| 1 | 1 | 0 |
| 1 | 2 | 0.6970 |
| 1 | 3 | 0.7660 |
| 1 | 4 | 0.5490 |
| 1 | 5 | 0.8100 |
| 1 | 6 | 0.5440 |
| 1 | 7 | 0.8140 |
| 1 | 8 | 0.7370 |
| 1 | 9 | 0.6830 |
| 1 | 10 | 0.8130 |
| 1 | 11 | 0.4630 |
| 1 | 12 | 0.7890 |
| 1 | 13 | 2.999 |
| 1 | 14 | 2.543 |
| 1 | 15 | 2.255 |
| 1 | 16 | 2.978 |
| 1 | 17 | 2.194 |
| 1 | 18 | 2.073 |
| 1 | 19 | 2.201 |
| 1 | 20 | 2.387 |
| 1 | 21 | 2.592 |
| 1 | 22 | 2.771 |
| 1 | 23 | 2.112 |
| 1 | 24 | 2.604 |
| 1 | 25 | 2.341 |
| 1 | 26 | 2.017 |
| 1 | 27 | 2.150 |
| 1 | 28 | 2.440 |
| 1 | 29 | 2.012 |
| 1 | 30 | 2.174 |
| 2 | 1 | 0.4880 |
| 2 | 2 | 0 |
| 2 | 3 | 0.5670 |
| 2 | 4 | 0.6350 |
| 2 | 5 | 0.8120 |
| 2 | 6 | 0.5770 |
| 2 | 7 | 0.5170 |
| 2 | 8 | 0.4250 |
| 2 | 9 | 0.5250 |
| 2 | 10 | 0.7950 |
| 2 | 11 | 1.073 |
| 2 | 12 | 0.7260 |
| 2 | 13 | 3.154 |
| 2 | 14 | 2.072 |
| 2 | 15 | 2.006 |
| 2 | 16 | 2.153 |
| 2 | 17 | 2.116 |
| 2 | 18 | 2.332 |
| 2 | 19 | 2.495 |
| 2 | 20 | 2.215 |
| 2 | 21 | 2.028 |
| 2 | 22 | 2.293 |
| 2 | 23 | 2.923 |
| 2 | 24 | 2.277 |
| 2 | 25 | 3.227 |
| 2 | 26 | 2.090 |
| 2 | 27 | 2.632 |
| 2 | 28 | 2.129 |
| 2 | 29 | 2.143 |
| 2 | 30 | 3.351 |
First 60 of 900 rows.
Count the blocks, and note how sharp their edges are. Blurred edges suggest groups that shade into each other. A single smear suggests one blob.
Read the card
ReadHopkins statistic 0.99 (p = 5.62e-25): the rows look clearly clumped.
- Hopkins H
- 0.9937
- p (vs. random scatter)
- < .001
Hopkins draws
| Draw | H |
|---|---|
| 1 | 0.9928 |
| 2 | 0.9968 |
| 3 | 0.9988 |
| 4 | 0.9982 |
| 5 | 0.9942 |
| 6 | 0.9978 |
| 7 | 0.9986 |
| 8 | 0.9630 |
| 9 | 0.9984 |
| 10 | 0.9982 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Is there cluster structure? (Hopkins + VAT)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.tendency 1.0.0 · spec 626f768f90a4bac3
# Dataset: ml_iris (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("sepal_length", "sepal_width", "petal_length", "petal_width")
SEED <- 42
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = FEATURES))
n_input <- nrow(df)
warnings <- list()
rows <- cs_ml_complete_rows(df, FEATURES)
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))
}
if (length(rows) < 10) stop("The tendency check needs at least 10 complete rows.")
X <- cs_ml_numeric_matrix(df, FEATURES, rows)
s <- apply(X, 2, stats::sd)
s[s == 0] <- 1
X <- sweep(sweep(X, 2, colMeans(X)), 2, s, "/")
# %% Hopkins statistic (shared-stream sampling)
m <- max(2, min(length(rows) - 1, ceiling(0.1 * length(rows))))
hop <- cs_ml_hopkins(X, m, SEED, reps = 10, power = "dimension")
# %% VAT (<= 500 evenly spaced rows)
vat_rows <- cs_ml_even_sample(length(rows), 500)
D <- cs_ml_euclidean_matrix(X[vat_rows + 1L, , drop = FALSE])
ord <- cs_ml_vat(D)
img <- cs_ml_block_image(D, ord, cap = 80)
b <- img$blocks
values <- list(n = length(rows), m = m, hopkins = hop$hopkins, hopkins_first = hop$first, hopkins_sd = hop$sd,
p_value = hop$p_value, n_vat = length(vat_rows), vat_check = cs_ml_checksum(as.numeric(ord), seq_along(ord) - 1L))
grid <- expand.grid(col = seq_len(b), row = seq_len(b))
vs <- img$image[cbind(grid$row, grid$col)]
H <- hop$hopkins
verdict <- if (H >= 0.75) "clearly clumped" else if (H >= 0.6) "somewhat clumped" else "close to random scatter"
cs_publish(list(
title = "Is there cluster structure? (Hopkins + VAT)",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = length(rows),
summary = sprintf("Hopkins statistic %.2f (p = %s): the rows look %s.", H, format(signif(hop$p_value, 3)), verdict),
statistics = list(list(key = "hopkins", label = "Hopkins H", value = H),
list(key = "p_value", label = "p (vs. random scatter)", value = hop$p_value, format = "p")),
tables = list(list(key = "draws", title = "Hopkins draws",
columns = list(list(key = "draw", label = "Draw", type = "integer"), list(key = "h", label = "H", type = "number")),
rows = lapply(seq_along(hop$draws), function(i) list(draw = i, h = hop$draws[i])))),
charts = list(cs_chart("vat", "vat-heatmap", "Reordered distances (VAT)", list(
col = cs_col("Column block", grid$col, "numeric"),
row = cs_col("Row block", grid$row, "numeric"),
distance = cs_col("Mean distance", vs, "numeric")
), note = sprintf("Dark blocks on the diagonal are candidate clusters; %s rows in %d × %d blocks.", format(length(vat_rows), big.mark = ","), b, b))),
values = values,
warnings = warnings
))
Hopkins statistic 0.99 (p = 5.62e-25): the rows look clearly clumped.
- Hopkins H
- 0.9937
- p (vs. random scatter)
- < .001
Hopkins draws
| Draw | H |
|---|---|
| 1 | 0.9928 |
| 2 | 0.9968 |
| 3 | 0.9988 |
| 4 | 0.9982 |
| 5 | 0.9942 |
| 6 | 0.9978 |
| 7 | 0.9986 |
| 8 | 0.9630 |
| 9 | 0.9984 |
| 10 | 0.9982 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Is there cluster structure? (Hopkins + VAT)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.tendency 1.0.0 · spec 626f768f90a4bac3
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.ml import cluster as csc
from codesplash.ml import discover_ext as dx
from codesplash.ml import embed as csembed
# %% Data
FEATURES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
SEED = 42
df = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=FEATURES)
n_input = len(df)
warnings = []
rows = csembed.complete_rows(df, FEATURES)
if len(rows) < n_input:
warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a value was missing.")
if len(rows) < 10:
raise ValueError("The tendency check needs at least 10 complete rows.")
X = csembed.standardize(csembed.numeric_matrix(df, FEATURES, rows), ddof=1)
# %% Hopkins statistic (shared-stream sampling)
m = max(2, min(len(rows) - 1, math.ceil(0.1 * len(rows))))
hop = dx.hopkins(X, m, SEED, reps=10, power="dimension")
# %% VAT (≤ 500 evenly spaced rows)
vat_rows = csc.even_sample(len(rows), 500)
D = dx.euclidean_matrix(X[vat_rows])
order = dx.vat(D)
image, b = dx.block_image(D, order, cap=80)
values = {
"n": len(rows), "m": m, "hopkins": hop["hopkins"], "hopkins_first": hop["first"], "hopkins_sd": hop["sd"],
"p_value": hop["p_value"], "n_vat": len(vat_rows),
"vat_check": csembed.checksum(order.astype(np.float64), np.arange(len(order))),
}
xs, ys, vs = [], [], []
for i in range(b):
for j in range(b):
xs.append(j + 1)
ys.append(i + 1)
vs.append(float(image[i, j]))
H = hop["hopkins"]
verdict = "clearly clumped" if H >= 0.75 else ("somewhat clumped" if H >= 0.6 else "close to random scatter")
cs.publish({
"title": "Is there cluster structure? (Hopkins + VAT)",
"engine": cs.engine_info("numpy", "scipy", "pandas"),
"n": len(rows),
"summary": f"Hopkins statistic {H:.2f} (p = {hop['p_value']:.3g}): the rows look {verdict}.",
"statistics": [
{"key": "hopkins", "label": "Hopkins H", "value": H},
{"key": "p_value", "label": "p (vs. random scatter)", "value": hop["p_value"], "format": "p"},
],
"tables": [{
"key": "draws",
"title": "Hopkins draws",
"columns": [{"key": "draw", "label": "Draw", "type": "integer"}, {"key": "h", "label": "H", "type": "number"}],
"rows": [{"draw": i + 1, "h": float(h)} for i, h in enumerate(hop["draws"])],
}],
"charts": [cs.chart("vat", "vat-heatmap", "Reordered distances (VAT)", {
"col": cs.col("Column block", xs, "numeric"),
"row": cs.col("Row block", ys, "numeric"),
"distance": cs.col("Mean distance", vs, "numeric"),
}, note=f"Dark blocks on the diagonal are candidate clusters; {len(vat_rows):,} rows in {b} × {b} blocks.")],
"values": values,
"warnings": warnings,
})
Shortened for the Academy: 1 chart(s) dropped to stay under 100 KB; 1 chart(s) dropped to stay under 100 KB.
The card reports with its spread across repeated draws. Here its standard deviation is 0.011 across 15 sampled rows per draw.
Check your understanding
CheckpointCheck yourself
You get = 0.52 with p = 0.40. What should you say?
Show the answer
Answer: b
A large p-value doesn't prove there is no structure. Weak or small groups can go undetected, but you have no evidence of clumping and should treat any clusters with suspicion.
Check yourself
A VAT image shows two sharp dark squares on the diagonal and a faint third one that bleeds into the second. A reasonable reading is:
Show the answer
Answer: b
Block sharpness carries the information. Overlap is itself a finding: it suggests mixture models may suit the data better than hard clusters.
Check yourself
Put a sound first look at segments in order.
Show the answer
The order:
- Check tendency with Hopkins and VAT
- Choose k with several criteria
- Fit the clusters
- Test stability under resampling
Check that there is something to find, decide how many groups to look for, fit, then confirm that the groups hold up.
Do it on your own data
In the appIn Discover, choose Find segments, pick your data and features, and open Is there cluster structure? under Checks.
import numpy as np
from sklearn.datasets import load_iris
from sklearn.neighbors import NearestNeighbors
from sklearn.preprocessing import StandardScaler
X = StandardScaler().fit_transform(load_iris().data)
n, d = X.shape
m = max(1, n // 10)
rng = np.random.default_rng(1)
idx = rng.choice(n, m, replace=False)
uniform = rng.uniform(X.min(axis=0), X.max(axis=0), size=(m, d))
nn = NearestNeighbors(n_neighbors=2).fit(X)
u = nn.kneighbors(uniform, n_neighbors=1)[0][:, 0]
w = nn.kneighbors(X[idx])[0][:, 1] # column 0 is the row itself
print((u**d).sum() / ((u**d).sum() + (w**d).sum()))X <- scale(iris[, 1:4])
n <- nrow(X); d <- ncol(X); m <- max(1, n %/% 10)
set.seed(1)
idx <- sample(n, m)
uniform <- apply(X, 2, function(col) runif(m, min(col), max(col)))
nearest <- function(p, data) min(sqrt(colSums((t(data) - p)^2)))
u <- apply(uniform, 1, nearest, data = X)
w <- sapply(idx, function(i) nearest(X[i, ], X[-i, ]))
sum(u^d) / (sum(u^d) + sum(w^d))These scripts use each language's own random numbers, so their values differ a little from each other and from the app's. CodeSplash draws from one shared stream, so its Python and R runs agree exactly.
Recap
Recap- Clustering always returns clusters, so check first whether there is anything to find.
- near 0.5 is compatible with no structure; near 1 means the rows clump.
- VAT shows the blocks behind that number. Read both.
Concepts in this lesson