Module contents
Lesson 1 of 24Core 80 min

Learning without labels: tasks, dissimilarities and data geometry

Unsupervised learning questions and their geometry, mixed-data dissimilarities, hubness and intrinsic dimension.

After this lesson you can

  • Classify unlabeled problems and choose a suitable success criterion.
  • Construct dissimilarities for mixed and structured data and justify weights and variable types.
  • Measure and explain hubness and apply a correction.
  • Derive and implement TwoNN alongside Levina–Bickel.
  • Explain the role of intrinsic dimension in distance concentration.

Before you start

Motivation: unlabeled data and no question

An authentication service writes two million log lines a day. A fund stores daily returns for five hundred assets over twenty years. A robot records thousands of joint trajectories. In none of the three cases has anyone labeled what is normal, what is a market regime or what is a correct movement. You have x1,…,xn\vb{x}_1, \dots, \vb{x}_n and nothing else. In supervised learning the label yy told you what was expected: predict it. Here nobody tells you, leading to two difficulties that run through the entire module.

First, you must decide the question. “Find structure” is not a mathematical problem until you choose which structure to seek (modes, groups, a low-dimensional surface, a useful encoding) and how to know you have found it. Second, you must decide the geometry. Almost every method in this module starts with a notion of “near”: neighbors in k-means and DBSCAN, the t-SNE graph. If your data are records with numbers, categories and flags, sets of open ports, or sequences of system calls, Euclidean distance across columns does not exist or makes no sense. And if your data are high-dimensional vectors, geometry behaves in ways that contradict intuition from R2\R^2: all points seem equidistant, a few become “everyone’s neighbors” and others are nobody’s neighbors.

This lesson organizes both decisions. First it sets out four questions to ask of a distribution p(x)p(\vb{x}) and their success criteria. It then constructs dissimilarities for mixed and structured data. Finally, it considers two high-dimensional phenomena that affect any neighbor-based method: hubness and the role of intrinsic dimension, which governs difficulty rather than the dimension of the space containing the numbers.

Four questions about p(x)p(\vb{x})

Suppose x1,…,xn∼iidp\vb{x}_1, \dots, \vb{x}_n \iid p in Rd\R^d, with unknown pp. Everything done without labels asks a question about pp or a representation of it.

Without labels there is no single test error to minimize, so each question brings its own success criterion, and confusing them is the source of most misleading unsupervised results.

QuestionWhat is soughtSuccess criterionCovered in
Densityp^\hat plog likelihood on held-out datalesson 4, lesson 8
Clusteringpartition or hierarchystability, internal indices, usefulness for the motivating tasklessons 2 to 7
Dimensionality reductionf:Rd→Rmf : \R^d \to \R^mreconstruction error, preserved neighborhoodslessons 10 to 18
Representationsfθf_\thetaperformance of a linear probe or k-NN on fθ(x)f_\theta(\vb{x})lessons 20 to 24

The density criterion is the only one with a closed form. For any p^\hat p with p^>0\hat p > 0 where p>0p > 0,

Ep[log⁡p^(X)]=−H⁡(p)−KL⁡(p ∥ p^),\E_{p}\big[\log \hat p(X)\big] = -\Ent(p) - \KL(p \,\Vert\, \hat p),

where H⁡(p)\Ent(p) is the differential entropy of pp (it does not depend on the model). Maximizing expected log likelihood of p^\hat p is equivalent to minimizing KL⁡(p ∥ p^)\KL(p \,\Vert\, \hat p), and is estimated by averaging log⁡p^(xi)\log \hat p(\vb{x}_i) over data not used to fit p^\hat p. In clustering, by contrast, there is no analogous quantity: two reasonable partitions of the same data can be incompatible, and Kleinberg proved that no clustering method satisfies three desirable properties at once (see lesson 7). It is therefore evaluated by stability, internal indices or, better, what the clustering enables afterward.

The four questions are not independent. A Gaussian mixture fitted to data is simultaneously a density estimator, a clustering (each component is a group), a manifold model (if covariances have low rank) and a representation (component responsibilities are features). What matters is knowing what you require for each use.

Review: scaling, metrics and concentration

Three results from previous modules are used constantly here. We only review them.

  • Scaling. Standardizing each variable (mean 0, standard deviation 1) is a decision, not a formality. It is appropriate when units are arbitrary and destroys structure when variance is informative, such as comparable physical quantities. You saw this in feature standardization and k-NN metrics and scaling.
  • Metrics. Minkowski ∥x−y∥p\norm{\vb{x} - \vb{y}}_p, Mahalanobis (x−y)⊤Σ−1(x−y)\sqrt{(\vb{x}-\vb{y})\T\mat{\Sigma}\inv(\vb{x}-\vb{y})} and cosine distance are three general-purpose choices for real vectors.
  • Concentration. If X,Y∼iidN(0,Im)\vb{X}, \vb{Y} \iid \Normal(\vb{0}, \mat{I}_m), then ∥X−Y∥2=2χm2\norm{\vb{X} - \vb{Y}}^2 = 2\chi^2_m and the distance is 2 U\sqrt{2}\,U with U∼χmU \sim \chi_m. Its coefficient of variation σD/μD\sigma_D/\mu_D is exactly m−E[U]2/E[U]\sqrt{m - \E[U]^2}/\E[U], which for large mm is 1/2m1/\sqrt{2m} (this is norm concentration, and in k-NN the curse of dimensionality):
mm12550500
σD/μD\sigma_D/\mu_D exact0.7560.5230.3230.1000.032
1/2m1/\sqrt{2m}0.7070.5000.3160.1000.032

With m=500m = 500 the distance between any two points is the mean plus or minus about 3%. Beyer, Goldstein, Ramakrishnan and Shaft (1999) drew a consequence for search: if relative distance dispersion tends to zero, the ratio between farthest and nearest point distances tends to 1, and “nearest neighbor” loses meaning. This lesson adds that the mm in the formula is not the dimension dd of the space but something else, as you will see in the manifold hypothesis section.

Dissimilarities for mixed and structured data

Many methods need only know how similar two data points are, not where they are. A dissimilarity is a symmetric function d(x,y)≥0d(\vb{x}, \vb{y}) \ge 0 with d(x,x)=0d(\vb{x}, \vb{x}) = 0; a distance additionally requires the triangle inequality and d=0d = 0 only when the data coincide. Algorithms using only the matrix D=(dij)\mat{D} = (d_{ij}) (k-medoids, hierarchical clustering, DBSCAN, spectral clustering, t-SNE) work with any dissimilarity you can write, allowing non-vector data to be used. The exception is k-means, which needs coordinates to calculate centroids.

The choice depends on the nature of the data:

  • TF-IDF vectors or directions (orientation matters, not magnitude): cosine distance 1−cos⁡θ1 - \cos\theta. If vectors are normalized, ∥x−y∥2=2(1−cos⁡θ)\norm{\vb{x} - \vb{y}}^2 = 2(1 - \cos\theta), so cosine and Euclidean distance give the same ordering.
  • Sets (open ports per host, installed packages): Jaccard distance, dJ(A,B)=1−∣A∩B∣/∣A∪B∣d_J(A, B) = 1 - \abs{A \cap B}/\abs{A \cup B}, which is a metric. Two hosts with {22,80,443}\{22, 80, 443\} and {80,443,3306,5432}\{80, 443, 3306, 5432\} have 2 ports in common out of 5 distinct ones: dJ=0.6d_J = 0.6. A port neither opens does not count: shared absence is uninformative.
  • Sequences (system calls, strings): Levenshtein edit distance, the smallest number of insertions, deletions and substitutions converting one into the other. Dynamic programming computes it with Di,0=iD_{i,0} = i, D0,j=jD_{0,j} = j and
Di,j=min⁡(Di−1,j+1,  Di,j−1+1,  Di−1,j−1+1[ai≠bj]),D_{i,j} = \min\big(D_{i-1,j} + 1,\; D_{i,j-1} + 1,\; D_{i-1,j-1} + \ind[a_i \neq b_j]\big),

in O(∣a∣∣b∣)\bigO(\abs{a}\abs{b}). With unit costs it is a metric. The distance between “kitten” and “sitting” is 3, and between traces open, read, mmap, write, close and open, mmap, read, write, write, close is 2: insert mmap before read and replace the original mmap with write. The “natural” reading of the change (swap read and mmap and add a write) would cost 3, because Levenshtein does not know transpositions; if reordering neighboring calls is one operation in your domain, the Damerau–Levenshtein variant counts it as 1. For very long sequences it is replaced by Jaccard on nn-grams, which is linear.

  • Records with different variable types (numbers, categories, flags): the Gower coefficient, constructed next.

The Gower coefficient

A host inventory record has, for example, CPU load (real), operating system (categorical), site (categorical with many levels) and a list of open ports (many rare binaries). There is no natural distance, but there is one for each variable separately. Gower’s (1971) idea is to average them.

Gower worked with similarity sij=1−dijs_{ij} = 1 - d_{ij}; it is the same thing. Four properties worth remembering:

  1. It is a weighted mean, so dij∈[0,1]d_{ij} \in [0, 1], and missing values and shared absences simply leave the average (changing the denominator).
  2. It reduces to known distances. If all variables are numeric with equal weights, dij=1K∥xi/R−xj/R∥1d_{ij} = \frac{1}{K}\norm{\vb{x}_i/\vb{R} - \vb{x}_j/\vb{R}}_1: Manhattan distance on range-scaled variables, divided by KK. The first cell checks this against scipy. If all variables are asymmetric binary with equal weights, dij=∣A △ B∣/∣A∪B∣d_{ij} = \abs{A \,\triangle\, B}/\abs{A \cup B} is exactly the Jaccard distance between sets of active variables.
  3. It is Euclidean after a square root. Gower proved that, without missing values or asymmetric binaries, the matrix S=(1−dij)\mat{S} = (1 - d_{ij}) is positive semidefinite. It is then a Gram matrix, sij=⟨ϕi,ϕj⟩s_{ij} = \inner{\vb{\phi}_i}{\vb{\phi}_j} with ∥ϕi∥=1\norm{\vb{\phi}_i} = 1, and ∥ϕi−ϕj∥2=2(1−sij)=2dij\norm{\vb{\phi}_i - \vb{\phi}_j}^2 = 2(1 - s_{ij}) = 2 d_{ij}. Thus 2dij\sqrt{2 d_{ij}} is a Euclidean distance between certain vectors and can be supplied to methods requiring it (MDS, k-means on those coordinates). With missing or asymmetric values that guarantee is lost.
  4. Weights are a modeling choice. Each variable contributes wkw_k times a jump dijk∈[0,1]d_{ijk} \in [0, 1], and not all jumps are comparable.

The fourth property causes the most harm in practice. A categorical variable with LL equiprobable levels is 0 with probability 1/L1/L and 1 otherwise: its variance, 1L(1−1L)\frac{1}{L}(1 - \frac{1}{L}), is 0.25 with L=2L = 2 and 0.076 with L=12L = 12. A Gaussian numeric variable scaled by its range (the expected range of 60 Gaussian values is 4.64σ4.64\sigma) contributes Var⁡∣Δ∣/R2≈2(1−2/π)σ2/(4.64σ)2=0.727/21.5≈0.034\Var\abs{\Delta}/R^2 \approx 2(1 - 2/\pi)\sigma^2/(4.64\sigma)^2 = 0.727/21.5 \approx 0.034, because Δ=X−Y∼N(0,2σ2)\Delta = X - Y \sim \Normal(0, 2\sigma^2) and ∣Δ∣\abs{\Delta} is half-normal. Thus, without weights, a 0/1 jump can move dissimilarity several times more than the difference between two CPUs. A family of ten rare binaries, with ten 0/1 jumps, contributes ten times. How much variability in dijd_{ij} comes from each family can be measured exactly, because dij=∑fcijfd_{ij} = \sum_f c_{ijf} (with cijfc_{ijf} the part contributed by family ff) and therefore

Var⁡(dij)=∑fCov⁡(cijf,dij),\Var(d_{ij}) = \sum_f \Cov(c_{ijf}, d_{ij}),

and each term divided by total variance is the share of variance contributed by that family.

InteractiveWeights and types in Gower dissimilarity
MDS projection of the Gower matrix. Color shows the k-medoids cluster (k=3k = 3) and shape shows the true role.
  • cluster 1
  • cluster 2
  • cluster 3
  • large circle: medoid
Marker shapes: circle = web, square = workstation, triangle = database.
Share of variance in dijd_{ij} contributed by each variable family (sums to 1)
0 %25 %50 %75 %100 %numeric (2)10 %operating system13 %site2 %ports (10)75 %
Ports (rare binary features)
1.00
1.00
1.00
1.00
12
Agreement with true roles (ARI)0.38
Dominant familyports (10): 75 %
Hosts per cluster34, 12, 14
The ports (10) family dominates dissimilarity (75 % of variance), and the clustering departs from the true roles.
Sixty hosts in three roles (web, workstation, database; twenty each) with numeric CPU and traffic, operating system, a site with LL levels independent of role and ten open ports. Each control is the weight of each variable in its family. The projection is MDS of the Gower matrix, colored by the three-medoid partition; marker shape is the true role. Below is the exact allocation of variance in dijd_{ij} by family. Start with all weights at 1 and symmetric ports: which family dominates? Switch ports to asymmetric and inspect the allocation and agreement with roles (ARI). Then lower site weight to 0, raise numeric weights and lower port weights. Move LL and observe how the site's contribution changes.

With all weights at 1, the ten ports make up 71% of variables and contribute about three quarters of the variance of dijd_{ij}, although only three inform role. Treating them as symmetric has another effect: shared absences, which are almost all of them, count as similarity, and hosts with few open ports all lie close together regardless of which ports. Switching to asymmetric makes pairs without ports in common ignore the variable and those sharing them move closer; agreement with roles rises considerably (in the interactive, ARI from 0.38 to 0.85 with a fixed seed). Site, with L=12L = 12, contributes little (2%) despite providing no information: with so many levels almost all pairs differ, and an almost constant term shifts every dissimilarity equally without changing who is near whom. The danger is the opposite of what is often said: an uninformative categorical variable with few levels. With L=2L = 2 its per-jump variance is the maximum possible (0.25), and if its weight is raised to 3 it contributes 42% of variance and ARI falls to 0.10: the partition separates sites, not roles. With asymmetric ports, numeric weights at 3 and site at 0, the interactive reaches ARI 0.95. A share can be slightly negative (site, −1-1% with asymmetric ports): it is a covariance, and a family varying against the rest subtracts. No general rule substitutes for inspecting the allocation, as the interactive does.

Implementation from scratch

The following cell implements the full coefficient (numeric, categorical and symmetric or asymmetric binary variables, with weights) in vectorized form and checks it in three places: the numeric case against scipy, the two-record example just described, and the property of being Euclidean after the square root.

[ ]Gower from scratch and checksBrowser
import numpy as np
from scipy.spatial.distance import cdist

def gower(num=None, cat=None, bina=None, w=None, asym=False):
    """Disimilitud de Gower d_ij = sum_k w_k delta_ijk d_ijk / sum_k w_k delta_ijk.
    num: (n, p) reales, d = |dif| / rango.  cat: (n, q) etiquetas, d = 1[distintas].
    bina: (n, r) en {0, 1}, d = 1[distintas]; si asym, delta = 1[x_i o x_j] (el 0-0 no cuenta)."""
    n = next(len(a) for a in (num, cat, bina) if a is not None)
    cols = []  # (d, delta) por variable
    if num is not None:
        R = np.ptp(num, axis=0); R[R == 0] = 1
        cols += [(np.abs(num[:, [k]] - num[:, k]) / R[k], np.ones((n, n))) for k in range(num.shape[1])]
    if cat is not None:
        cols += [((cat[:, [k]] != cat[:, k]).astype(float), np.ones((n, n))) for k in range(cat.shape[1])]
    if bina is not None:
        for k in range(bina.shape[1]):
            x = bina[:, k]
            d = (x[:, None] != x[None, :]).astype(float)
            delta = ((x[:, None] | x[None, :]) > 0).astype(float) if asym else np.ones((n, n))
            cols.append((d, delta))
    w = np.ones(len(cols)) if w is None else np.asarray(w, float)
    assert len(w) == len(cols), "un peso por variable"
    suma, peso = np.zeros((n, n)), np.zeros((n, n))
    for wk, (d, delta) in zip(w, cols):
        suma += wk * delta * d
        peso += wk * delta
    D = np.divide(suma, peso, out=np.zeros((n, n)), where=peso > 0)
    np.fill_diagonal(D, 0.0)
    return D

# 1) Caso puramente numérico: Gower = cityblock sobre variables reescaladas por rango, dividido por p
rng = np.random.default_rng(0)
X = rng.normal(size=(200, 5)) * np.array([1, 10, 100, 0.1, 5])
R = np.ptp(X, axis=0)
D_g = gower(num=X)
D_c = cdist(X / R, X / R, "cityblock") / X.shape[1]
print("numérico: max |Gower - cityblock/p| =", np.abs(D_g - D_c).max())

# 2) Edades 30 y 50 (rango 50), mismo país, binaria simétrica distinta
num = np.array([[30.0], [50.0], [0.0], [50.0]])      # las dos últimas fijan el rango 0..50
cat = np.array([["ES"], ["ES"], ["ES"], ["ES"]])
bina = np.array([[1], [0], [0], [0]])
d12 = gower(num=num, cat=cat, bina=bina)[0, 1]
print(f"edades 30 y 50, mismo país, binaria distinta: d = {d12:.4f}  (= 1 - (0.6 + 1 + 0)/3)")

# 3) Sin ausentes ni asimétricas, S = 1 - d es semidefinida positiva: sqrt(2 d) es una distancia euclídea
n = 150
num = rng.normal(size=(n, 3)); cat = rng.integers(0, 4, size=(n, 2)); bina = rng.integers(0, 2, size=(n, 3))
D = gower(num=num, cat=cat, bina=bina)
print("autovalor mínimo de S = 1 - d:", np.linalg.eigvalsh(1 - D).min().round(6))

The implementation matches cdist to rounding error (10−1610^{-16}), reproduces 0.4667 and matrix S\mat{S} has a positive minimum eigenvalue (0.000635), so the Euclidean square root exists in this case. The second cell reproduces the interactive model (with the numpy generator, so figures differ from the interactive) and compares three configurations over twenty seeds. It includes k-medoids from scratch: assign each datum to the nearest medoid and reposition each group’s medoid at the datum with the smallest sum of dissimilarities to the rest, until nothing changes. The adjusted Rand index (ARI) is 1 if the partition matches roles and 0 if it is as good as random.

[ ]Which weights recover the roles?Browser
import numpy as np
from sklearn.metrics import adjusted_rand_score

def hosts(seed, n=60, L=12):
    """60 hosts: 3 papeles (web, puesto, base de datos); 2 numéricas, SO, sede (L niveles) y 10 puertos."""
    r = np.random.default_rng(seed)
    papel = np.repeat([0, 1, 2], n // 3)
    cpu = np.array([55, 25, 70])[papel] + r.normal(0, 11, n)
    trafico = np.array([3.0, 1.6, 2.3])[papel] + r.normal(0, 0.38, n)
    p_so = np.array([[.15, .80, .05], [.60, .10, .30], [.10, .85, .05]])[papel]
    so = (r.uniform(size=(n, 1)) > p_so.cumsum(1)).sum(1)
    sede = r.integers(0, L, n)
    p_pto = np.full((3, 10), 0.03)
    for k in range(3):
        p_pto[k, 3 * k:3 * k + 3] = 0.55
    puertos = (r.uniform(size=(n, 10)) < p_pto[papel]).astype(int)
    return papel, np.c_[cpu, trafico], np.c_[so, sede], puertos

def kmedoides(D, k):
    med = [int(D.sum(1).argmin())]
    while len(med) < k:                                   # inicialización voraz
        ganancia = np.maximum(D[:, med].min(1)[:, None] - D, 0).sum(0)
        ganancia[med] = -1
        med.append(int(ganancia.argmax()))
    for _ in range(50):                                   # asignar y recolocar
        lab = D[:, med].argmin(1)
        nuevo = [int(np.flatnonzero(lab == c)[D[np.ix_(lab == c, lab == c)].sum(1).argmin()]) for c in range(k)]
        if nuevo == med:
            break
        med = nuevo
    return D[:, med].argmin(1)

configs = {
    "pesos 1, puertos simétricos": dict(w=[1] * 14, asym=False),
    "pesos 1, puertos asimétricos": dict(w=[1] * 14, asym=True),
    "asimétricos, numéricas x3, sede 0": dict(w=[3, 3, 1, 0] + [1] * 10, asym=True),
}
ari = {c: [] for c in configs}
for seed in range(20):
    papel, num, cat, bina = hosts(seed)
    for c, cfg in configs.items():
        D = gower(num, cat, bina, cfg["w"], cfg["asym"])
        ari[c].append(adjusted_rand_score(papel, kmedoides(D, 3)))
for c, v in ari.items():
    print(f"{c:36s} ARI medio = {np.mean(v):.2f}  (desv. {np.std(v):.2f}, mínimo {np.min(v):.2f})")

With all weights at 1, mean ARI is 0.51 with symmetric ports and 0.82 with asymmetric ports; with asymmetric ports, numeric weights at 3 and site at 0, it is 0.88. None reaches 1: roles overlap in CPU and traffic and operating system is only partly informative. The comparison shows the order of magnitude of the cost of ignoring types: moving from 0.51 to 0.82 by changing only how shared absences are handled.

For types that do not fit in a vector there are two routes with scikit-learn and scipy: pass the precomputed matrix with metric="precomputed" (for example in DBSCAN, AgglomerativeClustering, TSNE and KNeighborsClassifier) or compress it with scipy.spatial.distance.squareform when an algorithm asks for the upper triangle. The memory cost is O(n2)\bigO(n^2), so the precomputed matrix is practical up to tens of thousands of data points; beyond that, use approximate neighbors.

Hubness: a few points are everyone’s neighbors

Construct the directed kk-neighbor graph: an arrow from y\vb{y} to x\vb{x} if x\vb{x} is among the kk nearest neighbors of y\vb{y}. The number of arrows entering each point is its k-occurrence.

Radovanović, Nanopoulos and Ivanović (2010) define it this way and study it in real and synthetic data. Two exact facts before looking further:

Proof

(a) Each of the nn lists has kk entries and each entry increments exactly one k-occurrence. (b) Let xx be a point and let y1,y2,…y_1, y_2, \dots be points to its left ordered by closeness to xx. If x∈kNN(ya)x \in \mathrm{kNN}(y_a), points y1,…,ya−1y_1, \dots, y_{a-1} lie between yay_a and xx, so they are closer to yay_a than xx; because xx is one of the kk nearest to yay_a, there are at most k−1k - 1 of them, meaning a≤ka \le k. The same holds on the right. Therefore at most kk points on each side have xx in their list.

∎

The bound in (b) is the m=1m = 1 case of a general fact. Cover Rm\R^m around x\vb{x} with CmC_m cones of aperture 60°60°. If y\vb{y} and y′\vb{y}' fall in the same cone and ∥y−x∥≤∥y′−x∥\norm{\vb{y} - \vb{x}} \le \norm{\vb{y}' - \vb{x}}, the triangle’s angle at x\vb{x} is at most 60°60°, so the other two sum to at least 120°120°; the one at y\vb{y} is the larger of those two (opposite the longer side, ∥y′−x∥\norm{\vb{y}' - \vb{x}}), so it is at least 60°60° and at least as large as the angle at x\vb{x}. Opposite sides and angles have the same ordering, so ∥y−y′∥≤∥y′−x∥\norm{\vb{y} - \vb{y}'} \le \norm{\vb{y}' - \vb{x}}: y\vb{y} is at least as close to y′\vb{y}' as x\vb{x}. Thus if y′\vb{y}' has x\vb{x} in its list, its cone contains at most k−1k - 1 points closer to x\vb{x} than it is (without ties): from each cone only the kk closest to x\vb{x} can point to it, and Nk≤k CmN_k \le k\,C_m. Radovanović et al. (section 5.2) note that for k=1k = 1 the maximum is 2 in R\R, 5 in the plane and 11 in R3\R^3, one less than the kissing number when ties are forbidden, and that this bound grows exponentially with dimension. In low dimensions a point cannot monopolize occurrences. In high dimensions the bound becomes so large it ceases to constrain them, and the distribution of NkN_k is freed.

Why central points become hubs

Take centered data, X,Y∼iidN(0,Im)\vb{X}, \vb{Y} \iid \Normal(\vb{0}, \mat{I}_m). Then

∥x−y∥2=∥x∥2+∥y∥2−2⟨x,y⟩.\norm{\vb{x} - \vb{y}}^2 = \norm{\vb{x}}^2 + \norm{\vb{y}}^2 - 2\inner{\vb{x}}{\vb{y}}.

Standardize ∥x∥2=m+2m ax\norm{\vb{x}}^2 = m + \sqrt{2m}\,a_x, with axa_x approximately N(0,1)\Normal(0, 1) (the variance of χm2\chi^2_m is 2m2m), and ⟨x,y⟩≈m zxy\inner{\vb{x}}{\vb{y}} \approx \sqrt{m}\,z_{xy} with zxyz_{xy} approximately N(0,1)\Normal(0, 1). This gives

∥x−y∥2−2m  ≈  m [2 (ax+ay)−2zxy].\norm{\vb{x} - \vb{y}}^2 - 2m \;\approx\; \sqrt{m}\,\big[\sqrt{2}\,(a_x + a_y) - 2 z_{xy}\big].

Fix query y\vb{y}. Ranking candidates x\vb{x} depends only on 2 ax−2zxy\sqrt{2}\,a_x - 2 z_{xy}, which has variance 2+4=62 + 4 = 6. And axa_x is a point-specific handicap for x\vb{x} that is the same for every query: a point whose squared norm is below normal (near the mean) starts with an advantage over all others, while zxyz_{xy} changes from query to query and averages out. One third of ranking variance (2/62/6) is this shared handicap, and the effect accumulates over many queries. Quantify it: x\vb{x} enters y\vb{y}‘s list if 2 ax−2zxy\sqrt{2}\,a_x - 2z_{xy} falls in the lowest k/nk/n fraction, a Gaussian tail, yielding

E[Nk(x)∣ax=a]≈n Φ ⁣(t2−a2),t=6 Φ−1(k/n),\E[N_k(\vb{x}) \given a_x = a] \approx n\,\Phi\!\Big(\frac{t}{2} - \frac{a}{\sqrt{2}}\Big), \qquad t = \sqrt{6}\,\Phi^{-1}(k/n),

where Φ\Phi is the standard normal cumulative distribution function. With n=500n = 500 and k=10k = 10, t/2=−2.52t/2 = -2.52, and a point with a=−2a = -2 (squared norm two standard deviations below) appears in about 68 lists, one with a=0a = 0 in about 3, and one with a=+2a = +2 in 0.02: almost never. Expectation over a∼N(0,1)a \sim \Normal(0, 1) gives exactly kk again, as required by the theorem. This is a heuristic model (it applies the central limit theorem to ∥x∥2\norm{\vb{x}}^2 and ⟨x,y⟩\inner{\vb{x}}{\vb{y}}, which is not exact in low dimensions), but predicts three things the simulation below confirms: hubness saturates as mm rises, hubs are small-norm points, and a substantial fraction of points are antihubs. Across 50 real datasets, Radovanović et al. find that the correlation of NkN_k with distance to the nearest cluster center (found with k-means) is usually much stronger than with distance to the global mean: in clustered data hubs are near their cluster centers. And skewness of NkN_k correlates more with intrinsic dimension, measured by the Levina–Bickel estimator introduced below, than ambient dimension.

InteractiveHubs emerge
Histogram of k-occurrences NkN_k for 400 points
mean = k = 10
Each point’s NkN_k versus its distance from the data mean, divided by the median distance
  • hub: Nk≥2kN_k \ge 2k
  • other points
  • antihub: Nk=0N_k = 0
  • mean =k= k
50
10
Distance correction
Skewness of NkN_k (hubness)4.31
Maximum and mean NkN_k152 and 10
Hubs (Nk≥2kN_k \ge 2k) and antihubs (Nk=0N_k = 0)12.0 % and 12.5 %
Correlation of NkN_k with distance from the mean−0.75
The skewness is 4.31. A few points near the mean appear in up to 152 lists, while 13 % appear in none.
Four hundred Gaussian points of intrinsic dimension mm and their kk-neighbor graph. Above, histogram of NkN_k: the mean is always kk (dashed line). Below, each point's NkN_k against distance to the data mean. Raise mm from 1 to 100 and see the right tail of hubs (red) and pile of antihubs (aquamarine rings) emerge together, and correlation with distance to the mean become strongly negative. With m=1m = 1, no point exceeds 2k2k. Then enable local scaling or mutual proximity.

Hubness is not merely a curiosity of the distribution of NkN_k: it changes what algorithms do.

  • Neighbor classification. A hub appears in many points’ lists, so its label votes in many predictions; if that label is bad (a class outlier), it propagates errors. Antihubs, conversely, never vote.
  • Vector search and recommendation. This is the most visible symptom: a few documents or songs appear in results for almost every query and others appear in none. In an embedding index this degrades list usefulness even if recall relative to exact neighbors is perfect, because the exact neighbors themselves are biased (evaluation of approximate search and its indices, such as HNSW, starts from that exact neighbor).
  • Clustering and anomaly detection. Methods using neighbor lists (DBSCAN, local outlier factor, scores by distance to the kkth neighbor) inherit the bias: an antihub looks like an outlier (far from everyone in the relative sense) even if it is an ordinary point.

Mitigating hubness

The remedies act on the distance matrix, not the data. Schnitzer, Flexer, Schedl and Widmer (2012) propose two and analyze why they work: both make the “is a neighbor of” relation more symmetric.

  • Local scaling. Divide each distance by the local scale of both points: dxyLS=dxy/μxμyd^{\mathrm{LS}}_{xy} = d_{xy}/\sqrt{\mu_x \mu_y}, with μx\mu_x the mean distance from xx to its kk neighbors (this is Jegou et al.’s NICDM variant, used in their experiments; the original Zelnik-Manor and Perona form is exp⁡(−dxy2/σxσy)\exp(-d_{xy}^2/\sigma_x\sigma_y) with σx\sigma_x distance to the kkth neighbor). A hub has nearby neighbors, so μx\mu_x is small, inflating distances from it.
  • Mutual proximity. Reinterpret dxyd_{xy} as a probability. With XX the distribution of distances from all points to x\vb{x} and YY the distribution from all points to y\vb{y},
MP(dxy)=P(X>dxy ∩ Y>dyx),\mathrm{MP}(d_{xy}) = \Pr\big(X > d_{xy} \,\cap\, Y > d_{yx}\big),

the probability that an arbitrary point is farther from x\vb{x} than y\vb{y} and farther from y\vb{y} than x\vb{x}. Estimate it from empirical distributions of matrix rows; the independent variant, P(X>dxy)P(Y>dyx)\Pr(X > d_{xy})\Pr(Y > d_{yx}), is used here. Dissimilarity is 1−MP1 - \mathrm{MP}. The effect is that each distance is read on the scale of both endpoints: if h\vb{h} is a hub, distance dxhd_{\vb{x}\vb{h}} is small from x\vb{x}‘s perspective, but not from h\vb{h}‘s, which has many nearby points, so P(H>dhx)\Pr(H > d_{\vb{h}\vb{x}}) falls. A pair is close only if each is among the other’s neighbors, the symmetry hubness breaks.

  • Centering. If using dot products or cosines, subtracting the data mean before computing them removes the common component making points near the mean have high cosine with everyone. It is the cheapest option, and the cell below measures it.

The authors show in a toy example (a compact cluster inside a diffuse cloud) that with original distance 96.4% of nearest neighbors are of the same class and with mutual proximity 100%; with k=5k = 5 it rises from 95.2% to 98.8%. Across 30 real collections, mean skewness SN5S_{N_5} falls from 2.5 to 0.29 with mutual proximity and to 0.94 with NICDM, and k-NN accuracy improvements are clear only in high-hubness datasets (SN5>1.4S_{N_5} > 1.4): in low-hubness datasets almost no change is significant, and none worsens significantly. The next cell checks the mechanism and measures, without embellishment, what is gained on handwritten digits, where hubness is moderate.

[ ]Hubness: simulation, Gaussian model and correctionsBrowser
import numpy as np
from scipy.spatial.distance import cdist
from scipy.stats import skew, norm

def k_occurrences(D, k):
    """N_k[i] = en cuántas listas de k vecinos aparece el punto i (la diagonal no cuenta)."""
    D = D + np.diag(np.full(len(D), np.inf))
    vecinos = np.argpartition(D, k - 1, axis=1)[:, :k]
    return np.bincount(vecinos.ravel(), minlength=len(D))

rng = np.random.default_rng(0)
n, k = 500, 10
print(f"Gaussianas N(0, I_m), n = {n}, k = {k}: la suma de N_k es n*k = {n * k}")
for m in [2, 10, 100, 1000]:
    X = rng.normal(size=(n, m))
    N = k_occurrences(cdist(X, X), k)
    assert N.sum() == n * k
    r = np.corrcoef(N, (X ** 2).sum(1))[0, 1]
    print(f"  m = {m:4d}: asimetría {skew(N):5.2f}   N_k máximo {N.max():3d}   antihubs {np.mean(N == 0):.1%}   corr(N_k, |x|^2) = {r:5.2f}")

# modelo gaussiano de alta dimensión: N_k(x) ~ Poisson( n Phi(t/2 - a/sqrt(2)) ), a ~ N(0, 1), t = sqrt(6) Phi^{-1}(k/n)
t = np.sqrt(6) * norm.ppf(k / n)
lam = n * norm.cdf(t / 2 - rng.normal(size=200_000) / np.sqrt(2))
modelo = rng.poisson(lam)
print(f"  modelo (m -> infinito): asimetría {skew(modelo):5.2f}   antihubs {np.mean(modelo == 0):.1%}   media {modelo.mean():.2f}")

The simulation confirms the model. The sum of NkN_k is always nk=5000nk = 5000, skewness goes from −0.54-0.54 with m=2m = 2 to 0.94 with m=10m = 10, 3.29 with m=100m = 100 and 4.14 with m=1000m = 1000, and the limiting model gives 4.48: it rises and saturates. With m=2m = 2 no point appears in more than 16 lists, while with m=100m = 100 one reaches 133. Antihubs make up 15.4% with m=100m = 100 and 17.8% with m=1000m = 1000 (the model, the limit, gives 26%: convergence is slow). And NkN_k is strongly negatively correlated with squared norm (−0.74-0.74 and −0.73-0.73), as the handicap predicted.

[ ]Local scaling, mutual proximity and centering on digitsBrowser
import numpy as np
from scipy.spatial.distance import cdist
from scipy.stats import skew
from sklearn.datasets import load_digits

def k_occurrences(D, k):
    D = D + np.diag(np.full(len(D), np.inf))
    return np.bincount(np.argpartition(D, k - 1, axis=1)[:, :k].ravel(), minlength=len(D))

def mutual_proximity(D):
    """Disimilitud 1 - P(X > d_xy) P(Y > d_yx) con las distribuciones empíricas de las filas (MP con independencia)."""
    n = len(D)
    orden = np.sort(D, axis=1)[:, 1:]                     # distancias de cada fila, sin la diagonal
    P = np.empty_like(D)
    for i in range(n):
        P[i] = 1 - np.searchsorted(orden[i], D[i], side="right") / (n - 1)
    MP = 1 - P * P.T
    np.fill_diagonal(MP, 0)
    return MP

def local_scaling(D, k):
    """d_xy / sqrt(mu_x mu_y), con mu_x la distancia media de x a sus k vecinos."""
    mu = np.sort(D + np.diag(np.full(len(D), np.inf)), axis=1)[:, :k].mean(1)
    out = D / np.sqrt(np.outer(mu, mu))
    np.fill_diagonal(out, 0)
    return out

def knn_accuracy(D, y, k):
    """Exactitud de k-NN con dejar uno fuera, a partir de la matriz de disimilitudes."""
    D = D + np.diag(np.full(len(D), np.inf))
    vecinos = np.argpartition(D, k - 1, axis=1)[:, :k]
    votos = np.stack([np.bincount(f, minlength=10) for f in y[vecinos]])
    return np.mean(votos.argmax(1) == y)

k = 10
X, y = load_digits(return_X_y=True)
D = cdist(X, X)
print("Dígitos (1797 imágenes de 64 píxeles), k = 10")
for nombre, DD in [("euclídea", D), ("escalado local", local_scaling(D, k)), ("mutual proximity", mutual_proximity(D))]:
    N = k_occurrences(DD, k)
    print(f"  {nombre:17s} asimetría {skew(N):5.2f}  N_k máx {N.max():3d}  antihubs {np.mean(N == 0):.1%}  1-NN {knn_accuracy(DD, y, 1):.4f}  5-NN {knn_accuracy(DD, y, 5):.4f}")

def coseno(X):
    Z = X / np.linalg.norm(X, axis=1, keepdims=True)
    C = 1 - Z @ Z.T
    np.fill_diagonal(C, 0)
    return C
print("Centrado antes del coseno")
for nombre, XX in [("coseno", X), ("coseno centrado", X - X.mean(0))]:
    DD = coseno(XX)
    N = k_occurrences(DD, k)
    print(f"  {nombre:17s} asimetría {skew(N):5.2f}  N_k máx {N.max():3d}  5-NN {knn_accuracy(DD, y, 5):.4f}")

On digits, hubness is moderate (skewness 0.79 with Euclidean distance), and corrections reduce it: to 0.36 with local scaling and −0.11-0.11 with mutual proximity, which also removes almost all antihubs (from 0.9% to 0.1%). The accuracy gain is small, as expected with such low hubness and a classifier already 98.8% accurate: 5-NN goes from 0.9878 to 0.9911 and 0.9917, and 1-NN from 0.9883 to 0.9894 and 0.9889. 5-NN gains 6 to 7 images out of 1797 and 1-NN gains 1 or 2, differences that do not support strong claims with this sample. This is what Schnitzer et al.’s study predicts: with skewness 0.79, below the 1.4 threshold, there is not much to correct. With centering before cosine, skewness falls from 0.93 to 0.65, but 5-NN worsens from 0.9878 to 0.9816: reducing hubness is not the same as improving classification, so measure the effect on your task.

The manifold hypothesis and intrinsic dimension

Real data with enormous ambient dimension do not fill their space. A 64×6464 \times 64 image is a point in R4096\R^{4096}, but the set of photos of a face under different lighting and poses is parameterized by a handful of degrees of freedom. That is the idea:

This is an empirical hypothesis, not a theorem: it can fail (data that do fill the space, such as white noise) and should be checked. Making it operational requires a definition of dimension estimable from a sample. The most useful is local scaling: if data are “mm-dimensional” at a point, the number of data points in a ball of radius rr grows like rmr^m, because an mm-dimensional ball has volume proportional to rmr^m.

Now the connection to earlier sections. If data are x=Qz\vb{x} = \mat{Q}\vb{z} with Q∈Rd×m\mat{Q} \in \R^{d \times m} having orthonormal columns (an mm-dimensional subspace inside Rd\R^d, rotated arbitrarily), then ∥x−x′∥=∥z−z′∥\norm{\vb{x} - \vb{x}'} = \norm{\vb{z} - \vb{z}'} because an isometry preserves distances. All distance-concentration properties are those of z\vb{z}: they depend on mm, not dd. This one-line proposition has a practical lesson: “distances are concentrated” does not prove there is no structure, but that intrinsic dimension is high. With isotropic N(0,σ2)\Normal(0, \sigma^2) noise in the dd coordinates, a term with mean 2σ2d2\sigma^2 d is added to ∥z−z′∥2\norm{\vb{z} - \vb{z}'}^2, and ambient dimension matters again: noise dominates when 2σ2d2\sigma^2 d is comparable to 2m2m, that is, for d≳m/σ2d \gtrsim m/\sigma^2.

InteractiveIntrinsic dimension is the one that matters
Histogram of 19,900 pairwise distances divided by their mean
  • measured distances
  • exact density of 2χm2\sqrt{2\chi^2_m}
  • the mean
Relative contrast (dmax⁡−dmin⁡)/dmin⁡(d_{\max} - d_{\min})/d_{\min} (median over query points) versus dd, with 100 points
0.15
  • space-filling point cloud (m=dm = d)
  • manifold with m=3m = 3
Where the data lie
500
3
0.00
Effective dd and mm500 and 3
Coefficient of variation σD/μD\sigma_D/\mu_D0.419
Theory from exact 2χm2\sqrt{2\chi^2_m}0.422
Median relative contrast10.221
The data lie in R3\R^{3}. Distances at d=500d = 500 are the same as at d=3d = 3, so only mm matters.
Two hundred points. Choose whether they occupy a subspace of dimension mm, the sphere Sm\mathbb{S}^m (a curved manifold) or the entire space (m=dm = d), and move dd and mm. The histogram of pairwise distances divided by their mean and the coefficient of variation change only with mm: raise dd from 2 to 1000 with m=3m = 3 and nothing moves. With 'Fill space' it does concentrate, and the histogram follows the exact density of 2χm2\sqrt{2\chi^2_m} (dashed line). Below, relative contrast (dmax⁡−dmin⁡)/dmin⁡(d_{\max} - d_{\min})/d_{\min} against dd: it falls for the cloud filling space and is horizontal for the manifold. Raise noise σ\sigma and observe at what dd the manifold curve leaves the horizontal.

The next cell measures the same outside the interactive, with m=3m = 3, σ=0.1\sigma = 0.1 and 100 points: median relative contrast for a noiseless manifold does not change with dd, that of the same noisy manifold falls as dd grows (the threshold m/σ2=300m/\sigma^2 = 300 marks the order of magnitude where noise weighs as much as the manifold), and that of a space-filling cloud plunges much sooner.

[ ]Contrast depends on m, and on noise if presentBrowser
import numpy as np
from scipy.spatial.distance import cdist

def contraste(X):
    """Mediana, sobre los puntos de consulta, de (d_max - d_min) / d_min."""
    D = cdist(X, X)
    mx = D.max(1)
    np.fill_diagonal(D, np.inf)
    return np.median((mx - D.min(1)) / D.min(1))

rng = np.random.default_rng(0)
n, m, sigma = 100, 3, 0.1
Z = rng.normal(size=(n, m))
print(f"n = {n}; variedad: subespacio de dimensión m = {m} dentro de R^d; ruido sigma = {sigma} en las d coordenadas; d* = m/sigma^2 = {m / sigma**2:.0f}")
print("      d | sin ruido | con ruido | llena R^d")
for d in [3, 10, 50, 100, 300, 1000]:
    V = np.zeros((n, d)); V[:, :m] = Z                         # la rotación no cambia distancias: se omite
    print(f"{d:7d} | {contraste(V):9.2f} | {contraste(V + sigma * rng.normal(size=(n, d))):9.2f} | {contraste(rng.normal(size=(n, d))):9.2f}")

Without noise, the column stays at 8.08 from d=3d = 3 to d=1000d = 1000, because these are exactly the same distances. With noise it falls from 8.69 to 0.45, and the space-filling cloud goes from 7.62 to 0.10.

This motivates all the dimensionality reduction that follows. If intrinsic dimension is low, neighbor and density methods operate on a manifold of dimension mm where distances discriminate; and if the hypothesis holds, a representation with mm coordinates preserves relevant information. It is also why manifold methods (Isomap, LLE, t-SNE, UMAP) make sense. Learning theory says the same from another angle: many generalization bounds depend on intrinsic rather than ambient dimension (Rademacher bounds); for example, Kpotufe (2011) proves that k-neighbor regression converges at a rate set by local intrinsic dimension without needing to know it.

Intrinsic-dimension estimators

We still need to measure mm from a finite sample. Two maximum-likelihood estimators start from the same model: near x\vb{x} data behave like a Poisson process of (locally) constant intensity on an mm-dimensional manifold. The number of data points at distance less than rr is then Poisson with mean ρ Vm rm\rho\,V_m\,r^m, with ρ\rho local density and VmV_m unit-ball volume, and the ordered distances T1≤T2≤…T_1 \le T_2 \le \dots to neighbors satisfy that uj=ρVmTjmu_j = \rho V_m T_j^m are arrival times of a rate-1 Poisson process. Everything follows from this: it is the exponential–gamma family from the probability lesson, and a change of variables.

Levina and Bickel (2004). Given the kkth neighbor, times u1,…,uk−1u_1, \dots, u_{k-1} are order statistics of k−1k - 1 uniforms on [0,uk][0, u_k], and therefore ∑j=1k−1log⁡(uk/uj)∼Gamma(k−1,1)\sum_{j=1}^{k-1} \log(u_k/u_j) \sim \mathrm{Gamma}(k - 1, 1). Since log⁡(uk/uj)=mlog⁡(Tk/Tj)\log(u_k/u_j) = m\log(T_k/T_j), the sum S=∑j<klog⁡(Tk/Tj)S = \sum_{j<k}\log(T_k/T_j) follows a Gamma(k−1,1)\mathrm{Gamma}(k - 1, 1) distribution divided by mm, and the maximum-likelihood estimator at x\vb{x} is

m^k(x)=[1k−1∑j=1k−1log⁡Tk(x)Tj(x)]−1=k−1S.\hat m_k(\vb{x}) = \Big[\frac{1}{k-1}\sum_{j=1}^{k-1}\log\frac{T_k(\vb{x})}{T_j(\vb{x})}\Big]^{-1} = \frac{k - 1}{S}.

Two nuances matter. With S=G/mS = G/m, G∼Gamma(k−1,1)G \sim \mathrm{Gamma}(k-1, 1), we have E[1/G]=1/(k−2)\E[1/G] = 1/(k-2), so E[m^k]=m k−1k−2\E[\hat m_k] = m\,\frac{k-1}{k-2}: it is upward biased by factor (k−1)/(k−2)(k-1)/(k-2), which is 1.1251.125 for k=10k = 10 (the cell below measures it). The unbiased version uses k−2k - 2 in the numerator. When combining points, MacKay and Ghahramani observe in their comments on the paper that Levina and Bickel average local estimates and propose writing the joint likelihood (treating neighborhoods as independent), equivalent to averaging reciprocals: m^=[1/m^k(xi)‾]−1=(k−1)/Sˉ\hat m = [\overline{1/\hat m_k(\vb{x}_i)}]^{-1} = (k-1)/\bar S. Since S/(k−1)S/(k-1) is unbiased for 1/m1/m, the bias of the mean of m^k\hat m_k disappears without changing the numerator.

TwoNN (Facco, d’Errico, Rodriguez and Laio, 2017). It uses only the first two neighbors, with the advantage of looking at the smallest possible scale and making density disappear from the calculation.

Proof

With ui=ρVmrimu_i = \rho V_m r_i^m the arrival times of a rate-1 Poisson process, u1=E1u_1 = E_1 and u2−u1=E2u_2 - u_1 = E_2 with independent mean-1 exponentials E1,E2E_1, E_2. Then μm=u2/u1=1+E2/E1\mu^m = u_2/u_1 = 1 + E_2/E_1 (the constant ρVm\rho V_m cancels in the ratio). For s≥0s \ge 0,

P(E2E1>s)=∫0∞e−se e−e  ⁣de=11+s.\Pr\Big(\frac{E_2}{E_1} > s\Big) = \int_0^\infty e^{-s e}\,e^{-e}\,\dd e = \frac{1}{1 + s}.

Therefore P(μ>x)=P(μm>xm)=P(E2/E1>xm−1)=x−m\Pr(\mu > x) = \Pr(\mu^m > x^m) = \Pr(E_2/E_1 > x^m - 1) = x^{-m} for x≥1x \ge 1, which is 1−F(x)1 - F(x). Taking logarithms, −log⁡(1−F(μ))=mlog⁡μ-\log(1 - F(\mu)) = m\log\mu.

∎

This yields two estimators. TwoNN fits a line through the origin to points (log⁡μ(i), −log⁡(1−i/N))(\log\mu_{(i)},\, -\log(1 - i/N)), where μ(1)≤⋯≤μ(N)\mu_{(1)} \le \dots \le \mu_{(N)} are ordered ratios and i/Ni/N the empirical distribution function; slope is m^\hat m. To prevent heavy-tailed or noisy data dominating the fit, Facco et al. discard the highest 10% of μ\mu. In the paper, with 2500 points, they obtain 2.01 on the Swiss roll and 14.09 on a 14-dimensional hypercube with periodic conditions (13.91 after discarding that 10%), and 6.05 on a 20-dimensional Cauchy dataset, rising to 22.16 after discarding that 10%: with heavy tails the fit is unstable, which is why they discard it. The alternative is maximum likelihood: log likelihood of μ1,…,μN\mu_1, \dots, \mu_N with density mμ−m−1m\mu^{-m-1} is Nlog⁡m−(m+1)∑log⁡μiN\log m - (m + 1)\sum\log\mu_i, maximized at m^=N/∑ilog⁡μi\hat m = N/\sum_i\log\mu_i.

Scale changes everything

A single dimension number says nothing unless it says at what scale. With noise, at fine scale the nearest neighbors are closer than the noise thickness and the cloud looks like a volume. At intermediate scale the manifold appears. At large scale the neighborhood ball reaches other parts of the manifold (other turns of the roll) and the estimate is contaminated. To change scale without changing the estimator there are two levers: subsample (TwoNN: with fewer points, the second neighbor is farther away) or fix the neighborhood radius. Levina and Bickel also provide a version with radius RR instead of a neighbor count kk: with NN the number of neighbors within distance RR, m^R=N/SR\hat m_R = N/S_R with SR=∑j≤Nlog⁡(R/Tj)S_R = \sum_{j \le N}\log(R/T_j). Given NN, the NN times are uniform on [0,ρVmRm][0, \rho V_m R^m], so mSR∼Gamma(N,1)m S_R \sim \mathrm{Gamma}(N, 1) and SR/NS_R/N is unbiased for 1/m1/m: when combining points average those reciprocals as before. (Using N−1N - 1 in that average would bias it downward by (N−1)/N(N-1)/N, 25% with four neighbors.) Facco et al. propose exactly the first approach and look for a plateau of m^\hat m against number of points.

InteractiveIntrinsic dimension depends on scale
Noisy Swiss roll. Drag to rotate. Blue marks points retained by TwoNN. Red marks neighbors of the selected point within radius RR.
  • retained points
  • neighbors within RR
  • discarded points
TwoNN fit with 2000 points: −log⁡(1−F)-\log(1 - F) versus log⁡μ\log\mu, with μ=r2/r1\mu = r_2/r_1
slope 2slope 3fitted slope = 3.05
Estimated dimension versus scale on a logarithmic axis in the point cloud’s units
gap between turns
  • TwoNN (subsampling)
  • Levina–Bickel (radius)
  • sheet dimension 2
0.50
2000
2.7
TwoNN scale: mean distance to second neighbor0.96
TwoNN dimension (regression)3.05
TwoNN dimension (maximum likelihood)3.11
Levina–Bickel with radius RR2.37
Mean neighbors within RR23
At this scale the nearest neighbor lies closer than the noise thickness (σ=0.50\sigma = 0.50), so the cloud looks like a volume and TwoNN gives 3.05.
Two thousand Swiss-roll points with noise σ\sigma. Drag to rotate the scene. The first slider keeps fewer points (TwoNN with subsampling, blue); the second chooses Levina–Bickel neighborhood radius RR (red, with neighbors of the marked point inside the ball). The first chart is the TwoNN fit just proved: −log⁡(1−F)-\log(1-F) against log⁡μ\log\mu, with reference lines of slope 2 and 3. The second is estimated dimension against scale. With σ=0\sigma = 0 the sheet gives 2 at almost every scale; with σ=0.5\sigma = 0.5 it starts near 3, drops to a plateau near 2 and rises again when scale passes the separation between turns (2π≈6.32\pi \approx 6.3). Raise σ\sigma to 1 and compare.

In the interactive, with σ=0.5\sigma = 0.5, radius-based Levina–Bickel gives 2.57 with R=1.9R = 1.9, 2.05 with R=5R = 5 and 2.34 with R=8.5R = 8.5. Without noise, Levina–Bickel stays between 1.9 and 2.0 up to R=6.5R = 6.5 and rises to 2.29 with R=8.5R = 8.5. Curvature distortion is modest (from 2 to about 2.3) but systematic, and appears exactly where the ball starts touching the neighboring turn. Outside the interactive, two thousand scikit-learn Swiss-roll points (the full estimate) give 1.9 without noise and 3.0 with σ=0.5\sigma = 0.5: the same cloud, two dimensions, depending on whether there is noise at nearest-neighbor scale. Facco et al.’s paper shows the same with 50,000 points on a plane perturbed by Gaussian noise in 20 independent directions: estimated dimension versus number of points has a plateau at 2 (around N=1000N = 1000), rises as more points enter and scale drops to noise level, and falls toward 1 when very few remain. This is expected: noise adds a dimension existing only below one scale, and curvature connects distant parts above another.

Implementation from scratch

The cell implements TwoNN and three ways to average Levina–Bickel with cKDTree, and validates them where the answer is known: on a torus [0,1)m[0, 1)^m with periodic distance (density is exactly uniform and there is no boundary), and on datasets where theory deliberately fails (boundary, noise, unknown dimension).

[ ]TwoNN and Levina–Bickel from scratchBrowser
import numpy as np
from scipy.spatial import cKDTree
from sklearn.datasets import make_swiss_roll, load_digits

def distancias_vecinos(X, k, boxsize=None):
    """Distancias de cada punto a sus k primeros vecinos (columna j-1 = j-ésimo vecino)."""
    dist, _ = cKDTree(X, boxsize=boxsize).query(X, k=k + 1)
    return dist[:, 1:]

def twonn(X, descartar=0.1, boxsize=None):
    """TwoNN: regresión por el origen de -log(1 - F) sobre log mu, con mu = r2 / r1."""
    T = distancias_vecinos(X, 2, boxsize)
    mu = np.sort(T[T[:, 0] > 0, 1] / T[T[:, 0] > 0, 0])
    N = len(mu)
    F = np.arange(1, N + 1) / N
    n_ajuste = int(np.floor((1 - descartar) * N))          # se descarta el 10 % mayor de mu
    x, y = np.log(mu[:n_ajuste]), -np.log(1 - F[:n_ajuste])
    return float(x @ y / (x @ x))

def levina_bickel(X, k=10, boxsize=None):
    """Levina-Bickel con tres agregaciones: media de m_i (original), media de m_i sin sesgo y inverso de la media de 1/m_i."""
    T = distancias_vecinos(X, k, boxsize)
    S = np.log(T[:, -1:] / T[:, :-1]).sum(axis=1)           # sum_{j<k} log(T_k / T_j), uno por punto
    return float(np.mean((k - 1) / S)), float(np.mean((k - 2) / S)), float((k - 1) / np.mean(S))

rng = np.random.default_rng(0)
print("Toro [0,1)^m con distancia periódica (densidad exactamente uniforme), k = 10")
for m in [2, 3, 5]:
    X = rng.uniform(size=(3000, m))
    a, b, c = levina_bickel(X, 10, boxsize=1.0)
    print(f"  m = {m}: TwoNN {twonn(X, boxsize=1.0):5.2f}   LB original {a:5.2f}   LB sin sesgo {b:5.2f}   LB inverso {c:5.2f}   (a/m = {a / m:.3f}, (k-1)/(k-2) = {9 / 8:.3f})")

def esfera(n, m, d):
    Z = rng.normal(size=(n, m + 1)); Z /= np.linalg.norm(Z, axis=1, keepdims=True)
    return Z @ np.linalg.qr(rng.normal(size=(d, m + 1)))[0].T
conjuntos = {
    "esfera S^2 en R^50": esfera(2000, 2, 50),
    "Swiss roll": make_swiss_roll(2000, random_state=0)[0],
    "Swiss roll, ruido 0.5": make_swiss_roll(2000, noise=0.5, random_state=0)[0],
    "hipercubo [0,1]^8": rng.uniform(size=(2000, 8)),
    "gaussiana m = 5 en R^50": rng.normal(size=(2000, 5)) @ np.linalg.qr(rng.normal(size=(50, 5)))[0].T,
    "dígitos (64 píxeles)": load_digits().data,
}
print("\nConjuntos con borde, curvatura, ruido o dimensión desconocida (k = 10)")
for nombre, X in conjuntos.items():
    print(f"  {nombre:25s} TwoNN {twonn(X):5.2f}   LB sin sesgo {levina_bickel(X)[1]:5.2f}   LB inverso {levina_bickel(X)[2]:5.2f}")

Read what each row says. On the torus both estimators are accurate, and original LB overestimates by the factor 1.121.12 predicted by theory. On the curved sphere they are accurate. On the hypercube [0,1]8[0, 1]^8 they underestimate: with 2000 points in 8 dimensions most points are near the boundary and neighbors lie on only one side, so ball volume grows more slowly than r8r^8 (the boundary effect, eliminated by the torus). With noise, TwoNN, which looks closer, sees more dimensions than LB with k=10k = 10, which looks farther: the same scale dependence. On digits the estimates agree that intrinsic dimension (around 7 to 9) is much smaller than ambient dimension (64). Facco et al.’s paper reports 13.4 for MNIST “2”s and 3.5 for the Isomap face dataset, orders of magnitude comparable to those measured by other methods.

Module map: which family answers each question

With the four questions and geometry established, the rest of the module is an ordered catalog of answers, each using what you have seen here differently.

QuestionMethodsGeometry requiredLessons
Compact groupsk-means, k-medoids, hierarchicalk-means needs coordinates; the rest a dissimilarity matrix2, 3
Groups as dense regionsKDE, mean shift, DBSCAN, HDBSCANneighborhoods; affected by hubness and dimension4, 5
Groups as graph cutsspectral clusteringkk-neighbor graph6
Is there structure?validation indices, stabilitychosen dissimilarity7
Density with groupsGaussian mixtures, EMcoordinates and covariances8, 9
Linear subspacesPCA, PPCA, factor analysis, ICA, NMFcoordinates10 to 14
Curved manifoldsMDS, Isomap, LLE, t-SNE, UMAPneighborhoods, intrinsic dimension15 to 18
AnomaliesLOF, Isolation Forest, one-class SVMlocal density, neighbors19
Representationsautoencoders, contrastive learning, JEPAa criterion of “similarity” between views20 to 24

The thread is what you have seen in this lesson: before choosing a method, decide the question, the geometry you supply and the dimension at which the problem really operates.

Common mistakes

Exercises

QuizThe criterion matching the question
A team wants to score the rarity of authentication sessions using a model of p(x)p(\vb{x}). What measures whether p^\hat p is doing its job well?
QuizWhich question is each problem?
Assign each problem to its family: (i) compress 4096 pixels to 30 coordinates while preserving neighborhoods; (ii) segment customers by behavior without knowing how many segments there are; (iii) pretrain an encoder from two crops of the same document to classify them later with few labels; (iv) determine whether a transaction is rare relative to previous ones.
NumericGower dissimilarity of two records
Two records have ages 30 and 50 (the variable's range in the dataset is 50), the same country and different values for a symmetric binary variable. With all three weights equal to 1, what is their Gower dissimilarity?
NumericJaccard distance for two hosts
Host A has ports {22,80,443}\{22, 80, 443\} open and B has {80,443,3306,5432}\{80, 443, 3306, 5432\}. What is their Jaccard distance?
QuizFour data types, four dissimilarities
Choose the most reasonable dissimilarity for each scenario: (a) document TF-IDF vectors; (b) sets of open ports per host; (c) records with categorical and numeric variables; (d) sequences of process system calls.
QuizWhat asymmetric binary variables do
Two hosts have none of ten ports open and match on all other numeric and categorical variables. What happens to the ten ports in the Gower coefficient if treated as asymmetric?
QuizWho becomes a hub?
In a kk-neighbor graph of Gaussian data with high intrinsic dimension, which points tend to be hubs and why?
QuizAmbient versus intrinsic dimension
A set of 1000 points lives in R1000\R^{1000} on a 5-dimensional subspace (without noise). Compared with 1000 Gaussian points filling R5\R^{5}, what is expected of distance contrast (dmax⁡−dmin⁡)/dmin⁡(d_{\max} - d_{\min})/d_{\min}?
NumericRelative dispersion of distances
For X,Y∼iidN(0,Im)\vb{X}, \vb{Y} \iid \Normal(\vb{0}, \mat{I}_m) with m=200m = 200, approximately what is the coefficient of variation σD/μD\sigma_D/\mu_D of distance ∥X−Y∥\norm{\vb{X} - \vb{Y}}?
NumericDimension from the median of $\mu$
If the empirical median of μ=r2/r1\mu = r_2/r_1 in a dataset is 1.26, what intrinsic dimension does TwoNN's Pareto law indicate?
NumericLevina–Bickel at one point
At a point, distances to its first four neighbors are T1=1.0T_1 = 1.0, T2=1.2T_2 = 1.2, T3=1.5T_3 = 1.5 and T4=2.0T_4 = 2.0. Apply the Levina–Bickel maximum-likelihood estimator with k=4k = 4 (the one with k−1k - 1 in the numerator).
ProofTwoNN's Pareto law
Prove: If data near a point form a Poisson process of constant density ρ\rho on an mm-dimensional manifold, the ratio μ=r2/r1\mu = r_2/r_1 of distances to the second and first neighbors satisfies F(μ)=1−μ−mF(\mu) = 1 - \mu^{-m} for μ≥1\mu \ge 1, and therefore −log⁡(1−F(μ))=mlog⁡μ-\log(1 - F(\mu)) = m\log\mu.
0
Let VmV_m be the volume of the mm-dimensional unit ball, so the number of data points at distance less than rr is Poisson with mean ρVmrm\rho V_m r^m.

Step 1 of 4. What happens to ui=ρVmrimu_i = \rho V_m r_i^m, where r1≤r2≤…r_1 \le r_2 \le \dots are ordered distances to neighbors?

QuizReading dimension against scale
In the Swiss-roll interactive with noise σ=0.5\sigma = 0.5, TwoNN gives approximately 3.0, 2.8, 2.5, 2.4, 2.2, 2.0, 2.2 and 2.2 when points are reduced from 2000 to 1000, 500, 250, 125, 62, 31 and 15. Without knowing the cloud, what do you conclude about its intrinsic dimension?
CodeImplement TwoNN
Implement twonn_dimension(X), which takes a matrix X of shape (n, d) and returns intrinsic dimension estimated with TwoNN: ratio mu = r2 / r1 of distances to the second and first neighbors, a fit through the origin of -log(1 - F) on log mu (with F the empirical distribution function of ordered mu), discarding the largest 10% of mu. Ignore duplicate points (r1 = 0). Use scipy.spatial.cKDTree.
import numpy as np
from scipy.spatial import cKDTree

def twonn_dimension(X):
  """Dimensión intrínseca de X (n, d) con el estimador TwoNN."""
  X = np.asarray(X, dtype=float)
  # tu código: distancias al primer y segundo vecino, mu ordenados, F empírica,
  # ajuste por el origen descartando el 10 % mayor de mu
  return 0.0
Shift+Enter to run

Summary

Key idea
Before clustering or compressing, decide what question to ask of p(x)p(\vb{x}) and the geometry through which to view it: the difficulty of that geometry is governed not by the dimension of the space, but by the intrinsic dimension of the data and the scale at which it is measured.
  • There are four questions (density, clustering, dimensionality reduction, representations), each with its own success criterion; without labels, confusing them is the most common mistake.
  • Gower dissimilarity averages partial dissimilarities with weights and handles mixed variables. Without weights, 0/1 jumps weigh more than a range-scaled numeric variable, and rare binaries are treated as asymmetric; variance allocation by family can be measured exactly.
  • Mean k-occurrence NkN_k is always kk, but its skewness (hubness) grows with intrinsic dimension and saturates. Hubs are small-norm points, a handicap shared by every query. Local scaling and mutual proximity reduce it.
  • If data lie on a manifold of dimension mm, distances concentrate according to mm, not dd: without noise dd does not matter; with noise σ\sigma, it matters for d≳m/σ2d \gtrsim m/\sigma^2.
  • TwoNN follows from a proof: the ratio μ=r2/r1\mu = r_2/r_1 follows Pareto F=1−μ−mF = 1 - \mu^{-m} independently of density. Levina–Bickel is biased by (k−1)/(k−2)(k-1)/(k-2) and it is useful to average reciprocals.
  • Intrinsic dimension without scale means nothing: at fine scale noise dominates and at coarse scale curvature. Seek a plateau.