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 and nothing else. In supervised learning the label 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 : 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 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
Suppose in , with unknown . Everything done without labels asks a question about 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.
| Question | What is sought | Success criterion | Covered in |
|---|---|---|---|
| Density | log likelihood on held-out data | lesson 4, lesson 8 | |
| Clustering | partition or hierarchy | stability, internal indices, usefulness for the motivating task | lessons 2 to 7 |
| Dimensionality reduction | reconstruction error, preserved neighborhoods | lessons 10 to 18 | |
| Representations | performance of a linear probe or k-NN on | lessons 20 to 24 |
The density criterion is the only one with a closed form. For any with where ,
where is the differential entropy of (it does not depend on the model). Maximizing expected log likelihood of is equivalent to minimizing , and is estimated by averaging over data not used to fit . 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 , Mahalanobis and cosine distance are three general-purpose choices for real vectors.
- Concentration. If , then and the distance is with . Its coefficient of variation is exactly , which for large is (this is norm concentration, and in k-NN the curse of dimensionality):
| 1 | 2 | 5 | 50 | 500 | |
|---|---|---|---|---|---|
| exact | 0.756 | 0.523 | 0.323 | 0.100 | 0.032 |
| 0.707 | 0.500 | 0.316 | 0.100 | 0.032 |
With 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 in the formula is not the dimension 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 with ; a distance additionally requires the triangle inequality and only when the data coincide. Algorithms using only the matrix (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 . If vectors are normalized, , so cosine and Euclidean distance give the same ordering.
- Sets (open ports per host, installed packages): Jaccard distance, , which is a metric. Two hosts with and have 2 ports in common out of 5 distinct ones: . 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 , and
in . 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 -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 ; it is the same thing. Four properties worth remembering:
- It is a weighted mean, so , and missing values and shared absences simply leave the average (changing the denominator).
- It reduces to known distances. If all variables are numeric with equal weights, : Manhattan distance on range-scaled variables, divided by . The first cell checks this against
scipy. If all variables are asymmetric binary with equal weights, is exactly the Jaccard distance between sets of active variables. - It is Euclidean after a square root. Gower proved that, without missing values or asymmetric binaries, the matrix is positive semidefinite. It is then a Gram matrix, with , and . Thus 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.
- Weights are a modeling choice. Each variable contributes times a jump , and not all jumps are comparable.
The fourth property causes the most harm in practice. A categorical variable with equiprobable levels is 0 with probability and 1 otherwise: its variance, , is 0.25 with and 0.076 with . A Gaussian numeric variable scaled by its range (the expected range of 60 Gaussian values is ) contributes , because and 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 comes from each family can be measured exactly, because (with the part contributed by family ) and therefore
and each term divided by total variance is the share of variance contributed by that family.
With all weights at 1, the ten ports make up 71% of variables and contribute about three quarters of the variance of , 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 , 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 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, % 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.
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 (), reproduces 0.4667 and matrix 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.
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 , 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 -neighbor graph: an arrow from to if is among the nearest neighbors of . 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 lists has entries and each entry increments exactly one k-occurrence. (b) Let be a point and let be points to its left ordered by closeness to . If , points lie between and , so they are closer to than ; because is one of the nearest to , there are at most of them, meaning . The same holds on the right. Therefore at most points on each side have in their list.
∎The bound in (b) is the case of a general fact. Cover around with cones of aperture . If and fall in the same cone and , the triangle’s angle at is at most , so the other two sum to at least ; the one at is the larger of those two (opposite the longer side, ), so it is at least and at least as large as the angle at . Opposite sides and angles have the same ordering, so : is at least as close to as . Thus if has in its list, its cone contains at most points closer to than it is (without ties): from each cone only the closest to can point to it, and . Radovanović et al. (section 5.2) note that for the maximum is 2 in , 5 in the plane and 11 in , 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 is freed.
Why central points become hubs
Take centered data, . Then
Standardize , with approximately (the variance of is ), and with approximately . This gives
Fix query . Ranking candidates depends only on , which has variance . And is a point-specific handicap for 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 changes from query to query and averages out. One third of ranking variance () is this shared handicap, and the effect accumulates over many queries. Quantify it: enters ‘s list if falls in the lowest fraction, a Gaussian tail, yielding
where is the standard normal cumulative distribution function. With and , , and a point with (squared norm two standard deviations below) appears in about 68 lists, one with in about 3, and one with in 0.02: almost never. Expectation over gives exactly again, as required by the theorem. This is a heuristic model (it applies the central limit theorem to and , which is not exact in low dimensions), but predicts three things the simulation below confirms: hubness saturates as 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 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 correlates more with intrinsic dimension, measured by the Levina–Bickel estimator introduced below, than ambient dimension.
Effects on neighbors, clustering and search
Hubness is not merely a curiosity of the distribution of : 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 th 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: , with the mean distance from to its neighbors (this is Jegou et al.’s NICDM variant, used in their experiments; the original Zelnik-Manor and Perona form is with distance to the th neighbor). A hub has nearby neighbors, so is small, inflating distances from it.
- Mutual proximity. Reinterpret as a probability. With the distribution of distances from all points to and the distribution from all points to ,
the probability that an arbitrary point is farther from than and farther from than . Estimate it from empirical distributions of matrix rows; the independent variant, , is used here. Dissimilarity is . The effect is that each distance is read on the scale of both endpoints: if is a hub, distance is small from ‘s perspective, but not from ‘s, which has many nearby points, so 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 it rises from 95.2% to 98.8%. Across 30 real collections, mean skewness 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 (): 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.
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 is always , skewness goes from with to 0.94 with , 3.29 with and 4.14 with , and the limiting model gives 4.48: it rises and saturates. With no point appears in more than 16 lists, while with one reaches 133. Antihubs make up 15.4% with and 17.8% with (the model, the limit, gives 26%: convergence is slow). And is strongly negatively correlated with squared norm ( and ), as the handicap predicted.
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 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 image is a point in , 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 “-dimensional” at a point, the number of data points in a ball of radius grows like , because an -dimensional ball has volume proportional to .
Now the connection to earlier sections. If data are with having orthonormal columns (an -dimensional subspace inside , rotated arbitrarily), then because an isometry preserves distances. All distance-concentration properties are those of : they depend on , not . 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 noise in the coordinates, a term with mean is added to , and ambient dimension matters again: noise dominates when is comparable to , that is, for .
The next cell measures the same outside the interactive, with , and 100 points: median relative contrast for a noiseless manifold does not change with , that of the same noisy manifold falls as grows (the threshold marks the order of magnitude where noise weighs as much as the manifold), and that of a space-filling cloud plunges much sooner.
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 to , 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 where distances discriminate; and if the hypothesis holds, a representation with 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 from a finite sample. Two maximum-likelihood estimators start from the same model: near data behave like a Poisson process of (locally) constant intensity on an -dimensional manifold. The number of data points at distance less than is then Poisson with mean , with local density and unit-ball volume, and the ordered distances to neighbors satisfy that 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 th neighbor, times are order statistics of uniforms on , and therefore . Since , the sum follows a distribution divided by , and the maximum-likelihood estimator at is
Two nuances matter. With , , we have , so : it is upward biased by factor , which is for (the cell below measures it). The unbiased version uses 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: . Since is unbiased for , the bias of the mean of 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 the arrival times of a rate-1 Poisson process, and with independent mean-1 exponentials . Then (the constant cancels in the ratio). For ,
Therefore for , which is . Taking logarithms, .
∎This yields two estimators. TwoNN fits a line through the origin to points , where are ordered ratios and the empirical distribution function; slope is . To prevent heavy-tailed or noisy data dominating the fit, Facco et al. discard the highest 10% of . 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 with density is , maximized at .
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 instead of a neighbor count : with the number of neighbors within distance , with . Given , the times are uniform on , so and is unbiased for : when combining points average those reciprocals as before. (Using in that average would bias it downward by , 25% with four neighbors.) Facco et al. propose exactly the first approach and look for a plateau of against number of points.
In the interactive, with , radius-based Levina–Bickel gives 2.57 with , 2.05 with and 2.34 with . Without noise, Levina–Bickel stays between 1.9 and 2.0 up to and rises to 2.29 with . 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 : 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 ), 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 with periodic distance (density is exactly uniform and there is no boundary), and on datasets where theory deliberately fails (boundary, noise, unknown dimension).
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 predicted by theory. On the curved sphere they are accurate. On the hypercube 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 (the boundary effect, eliminated by the torus). With noise, TwoNN, which looks closer, sees more dimensions than LB with , 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.
| Question | Methods | Geometry required | Lessons |
|---|---|---|---|
| Compact groups | k-means, k-medoids, hierarchical | k-means needs coordinates; the rest a dissimilarity matrix | 2, 3 |
| Groups as dense regions | KDE, mean shift, DBSCAN, HDBSCAN | neighborhoods; affected by hubness and dimension | 4, 5 |
| Groups as graph cuts | spectral clustering | -neighbor graph | 6 |
| Is there structure? | validation indices, stability | chosen dissimilarity | 7 |
| Density with groups | Gaussian mixtures, EM | coordinates and covariances | 8, 9 |
| Linear subspaces | PCA, PPCA, factor analysis, ICA, NMF | coordinates | 10 to 14 |
| Curved manifolds | MDS, Isomap, LLE, t-SNE, UMAP | neighborhoods, intrinsic dimension | 15 to 18 |
| Anomalies | LOF, Isolation Forest, one-class SVM | local density, neighbors | 19 |
| Representations | autoencoders, contrastive learning, JEPA | a criterion of “similarity” between views | 20 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
Step 1 of 4. What happens to , where are ordered distances to neighbors?
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.0Summary
- 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 is always , 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 , distances concentrate according to , not : without noise does not matter; with noise , it matters for .
- TwoNN follows from a proof: the ratio follows Pareto independently of density. Levina–Bickel is biased by 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.