Skip to content

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.

Applied ~10 min8 steps

What runs in CodeSplash

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

Read first

01

Ask before you cluster

Read

k-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 HH approaches 1. If the rows are as spread out as random points, the distances match and HH sits near 0.5.

02

Make a guess

Predict

Predict 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?

IrisUS arrestsAbout the same
Reveal

Iris: HH = 0.994 with p < .001.

US arrests: HH = 0.594 with p = .274. States differ, but these data are compatible with no clumping at all.

03

The formula

Read

With mm sampled rows, let uiu_i be the distance from a uniform point to its nearest real row, and wiw_i the distance from a real row to its nearest other real row:

H=∑iui d∑iui d+∑iwi dH = \frac{\sum_i u_i^{\,d}}{\sum_i u_i^{\,d} + \sum_i w_i^{\,d}}

Raising distances to the power of the dimension dd gives HH an exact Beta(m,m)(m, m) 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.

04

See the blocks

Explore

A 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.

VAT image (cluster tendency)Is there cluster structure before any clustering is run?
View data
row blockcolumn blockmean distance
110
120.6970
130.7660
140.5490
150.8100
160.5440
170.8140
180.7370
190.6830
1100.8130
1110.4630
1120.7890
1132.999
1142.543
1152.255
1162.978
1172.194
1182.073
1192.201
1202.387
1212.592
1222.771
1232.112
1242.604
1252.341
1262.017
1272.150
1282.440
1292.012
1302.174
210.4880
220
230.5670
240.6350
250.8120
260.5770
270.5170
280.4250
290.5250
2100.7950
2111.073
2120.7260
2133.154
2142.072
2152.006
2162.153
2172.116
2182.332
2192.495
2202.215
2212.028
2222.293
2232.923
2242.277
2253.227
2262.090
2272.632
2282.129
2292.143
2303.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.

05

Read the card

Read
Is there cluster structure? (Hopkins + VAT)Recorded · Python and R agreeRecorded 2026-11-09 · 8 values compared
R

Hopkins statistic 0.99 (p = 5.62e-25): the rows look clearly clumped.

Hopkins H
0.9937
p (vs. random scatter)
< .001

Hopkins draws

DrawH
10.9928
20.9968
30.9988
40.9982
50.9942
60.9978
70.9986
80.9630
90.9984
100.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
))
Python

Hopkins statistic 0.99 (p = 5.62e-25): the rows look clearly clumped.

Hopkins H
0.9937
p (vs. random scatter)
< .001

Hopkins draws

DrawH
10.9928
20.9968
30.9988
40.9982
50.9942
60.9978
70.9986
80.9630
90.9984
100.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 HH with its spread across repeated draws. Here its standard deviation is 0.011 across 15 sampled rows per draw.

06

Check your understanding

Checkpoint

Check yourself

You get HH = 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.

  1. 1Choose k with several criteria
  2. 2Test stability under resampling
  3. 3Check tendency with Hopkins and VAT
  4. 4Fit the clusters

Show the answer

The order:

  1. Check tendency with Hopkins and VAT
  2. Choose k with several criteria
  3. Fit the clusters
  4. 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.

07

Do it on your own data

In the app

In Discover, choose Find segments, pick your data and features, and open Is there cluster structure? under Checks.

Python
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()))
R
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.

08

Recap

Recap
  • Clustering always returns clusters, so check first whether there is anything to find.
  • HH 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