Skip to content

CDiscover · discover.tendency

Is there cluster structure? (Hopkins + VAT)

Do these rows clump into groups at all, or are they spread out like random noise?

Checks for cluster structure before you cluster. The Hopkins statistic compares nearest-neighbor distances from real rows with those from uniformly scattered points in the same box: near 0.5 = no structure, near 1 = clumped (Wright's dimension-power form, H ~ Beta(m, m) under randomness, so a p-value is exact). The VAT image reorders the distance matrix so clusters show as dark blocks on the diagonal. Sampling uses the shared stream, so both engines agree.

Verified in Python and R Python and R agree to 10 decimals Seeded Also called Hopkins statistic, clustering tendency, VAT…

A real result

Example “Iris clumped”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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

Shortened for the Academy: 1 chart(s) dropped to stay under 100 KB; 1 chart(s) dropped to stay under 100 KB.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Iris clumpedml_iris · features: sepal_length, sepal_width, petal_length, petal_width
  • Usarrests unpoweredml_usarrests · features: Murder, Assault, UrbanPop, Rape

In the guides

Where it sits in the decision guides

  • Clustering (k-means, hierarchical) · 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–500 columns
Numbers that define closeness (standardized; rows with a missing value are left out).

Choices you make

model

Rows sampleddefault 0.1

Share of rows (and of uniform points) used per Hopkins draw; Hopkins recommends 5–10%.

Repeated drawsdefault 10

Draws averaged for a stable estimate; the p-value uses the first draw.

Advanced

Distance powerdefault dimension

How nearest-neighbor distances are combined.

  • Raised to the dimension (Wright 2022)(default) — Correct reference distribution Beta(m, m): use this.
  • Unpowered (original 1954 form) — Classic formula; its null distribution is not Beta.

What it reports

n
How many independent units the analysis used; it sets precision and power.
m
How many independent groups the result rests on, such as the studies in a multilevel meta-analysis.
hopkins
Compares nearest-neighbor distances from real rows with those from random points; near 0.5 = no structure, near 1 = clumped.
hopkins_first
Compares nearest-neighbor distances from real rows with those from random points; near 0.5 = no structure, near 1 = clumped.
hopkins_sd
Standard deviation of the Hopkins statistic over repeated random samples. Smaller means the reported mean is more stable.
p_value
How surprising your data would be if the null hypothesis were true, as a probability.
n_vat
How many independent units the analysis used; it sets precision and power.
vat_check
The distance matrix reordered so that clusters appear as dark blocks along the diagonal.

Python and R

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

Default traps between the two languages

  • Sampled rows and uniform points come from the shared random stream in both engines. hopkins::hopkins and clustertend use R's own random numbers (and clustertend the unpowered form), so their values differ draw to draw.
Python

The exact script CodeSplash ran for example “Iris clumped” · 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,
})
R

The exact script CodeSplash ran for example “Iris clumped” · 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
))

Sources

  • Lawson RG, Jurs PC (1990). New index for clustering tendency and its application to chemical problems. J Chem Inf Comput Sci 30:36–41.
  • Wright K (2022). Will the real Hopkins statistic please stand up? The R Journal 14(3):282–292.
  • Bezdek JC, Hathaway RJ (2002). VAT: a tool for visual assessment of (cluster) tendency. IJCNN 2002, 2225–2230.

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