Skip to content
AI.info

Unsupervised learning

Distance, Similarity, and Neighborhoods

Compare common distance and similarity measures, understand their invariances, and design neighborhoods that reflect the task.

By the end you can

Comparison

The same pair of customers under four rulers

Which metric is useful depends on whether volume, composition, overlap, or correlated deviation matters. The gap between those questions has been measured. MTEB, the Massive Text Embedding Benchmark, put 33 models through 8 embedding tasks over 58 datasets and 112 languages. Its headline finding was not that one relation won. “We find that no particular text embedding method dominates across all tasks,” says its abstract, published in 2023. The measure that ranks first at semantic textual similarity is not the measure that ranks first at clustering or reranking. That is the practical content of the four columns below. They are not four styles of one measurement. They are four different questions, and 58 datasets say that being good at one of them does not make a system good at another.

FigureComparison · 4 columns

Euclidean distance

Straight-line difference after numeric scaling.

  • Sensitive to units and outliers
  • Matches centroid-based objectives
  • Assumes coordinate differences combine geometrically
  • Works poorly with arbitrary one-hot expansion

Manhattan distance

Sum of absolute coordinate differences.

  • Less dominated by one large coordinate
  • Natural for additive movement across axes
  • Still depends on feature scaling
  • Produces diamond-shaped neighborhoods

Cosine similarity

Angle between vectors after length normalization.

  • Useful for sparse text and embeddings
  • Downplays total activity volume
  • Can join tiny and massive profiles with similar proportions
  • Does not guarantee semantic equivalence

Jaccard similarity

Overlap divided by union for sets or binary attributes.

  • Ignores shared absences in its common form
  • Fits baskets, tags, and memberships
  • Treats rare and common items equally unless weighted
  • Requires a clear definition of item presence

Visual

What each relation preserves

Common measures answer different versions of the question “How alike are these observations?” Magnitude-sensitive geometry responds to absolute coordinate differences. Direction-sensitive geometry compares orientation and largely ignores length. Set-overlap measures look only at shared and unshared discrete items. Covariance-aware geometry rescales directions using an estimated covariance structure. Task-specific relations — edit distance, dynamic time warping, learned metrics, graph distances — encode specialized invariances. Reading down that list is the same as reading a list of assumptions you are about to make about your data.

FigureHierarchy · 5 levels
  • Magnitude-sensitive geometry

    Euclidean and Manhattan distances respond to absolute coordinate differences.

    • Direction-sensitive geometry

      Cosine similarity compares orientation and largely ignores vector length.

      • Set overlap

        Jaccard-style measures focus on shared and unshared discrete items.

        • Covariance-aware geometry

          Mahalanobis distance rescales directions using an estimated covariance structure.

          • Task-specific relations

            Edit distance, dynamic time warping, learned metrics, and graph distances encode specialized invariances.

A similarity measure defines which transformations leave relationships unchanged.

Two documents that are close for one reason and far for another

A legal brief and a short email both mention “contract termination” five times. Their raw word counts differ sharply. Yet their normalized term directions may look similar. Distance is not a neutral ruler. It decides whether magnitude, direction, shared categories, correlated movement, or local connectivity counts as resemblance.

The metric is part of the model, not a formatting choice.

Case

When the nearest point stops being near

Add enough dimensions and the nearest point stops being near. Beyer and colleagues at the University of Wisconsin-Madison proved it, and put the result in one sentence. “We show that under a broad set of conditions (much broader than independent and identically distributed dimensions), as dimensionality increases, the distance to the nearest data point approaches the distance to the farthest data point,” their abstract says. The paper appeared in 1999, after circulating as a Wisconsin technical report in 1998.

This is not a caution about a thousand dimensions. Their experiments on real and synthetic data show the effect “can occur for as few as 10-15 dimensions”. At that point the closest record and the most distant record in the whole data set sit at almost the same distance from the query. The ranking still comes back, sorted, with a first row. The word “nearest” has simply stopped carrying information.

The next move was to change the ruler instead of the data. Aggarwal and colleagues examined the whole Lk norm family in 2001 and found that “the problem of meaningfulness in high dimensionality is sensitive to the value of k”. The concentration Beyer and colleagues proved is not a property of high-dimensional space by itself. It is a property of high-dimensional space measured a particular way. Manhattan distance, they report, “is consistently more preferable than the Euclidean distance metric” for high dimensional data mining applications. Same points, same dimensionality, one changed exponent, a different answer to which neighbor is nearest. The ruler is a modeling decision, and it has been benchmarked.

Example

Counterexamples that reveal a bad metric

Testing deliberately chosen pairs is often more informative than inspecting an average score. One of these is not a thought experiment. It is a published measurement in which the data was held fixed and only the definition of similarity moved.

  • Near-duplicate web pages: one corpus, two definitions of document similarity, and the definition alone decided the outcome. Monika Henzinger ran Broder et al.'s shingling, which treats a page as a set and asks about resemblance, against Charikar's random-projection fingerprint. “We compare the two algorithms on a very large scale, namely on a set of 1.6B distinct web pages,” she wrote in 2006. The result: “Since Charikar's algorithm finds more near-duplicate pairs on different sites, it achieves a better precision overall, namely 0.50 versus 0.38 for Broder et al.'s algorithm.” Her hybrid beat both — “We present a combined algorithm which achieves precision 0.79 with 79% of the recall of the other algorithms”. A year later Google's crawler team reported building its web-crawl near-duplicate system on the fingerprint approach, since “With simhash, for 8B web pages, 64-bit fingerprints suffice”. The pages never changed. The definition of “the same document” did.
  • Shopping baskets: Shared non-purchases dominate binary Euclidean distance across thousands of products, while Jaccard focuses on purchased overlap.
  • Fraud analysis: A transaction can be normal globally but unusual relative to peers with the same merchant and time context.
  • Sensor health: Temperature and pressure move together, so covariance-aware distance may treat coordinated change differently from independent deviation.
  • Mobility: Two trajectories visit the same places in different orders, making set overlap high while sequence-aware distance remains large.

Key idea

Nearest does not mean similar in the domain

A nearest-neighbor query always returns something unless the system permits rejection. In a sparse region, the closest point may still be operationally unrelated.

NIST measured what that costs in a deployed system. Its Face Recognition Vendor Test Part 3: Demographic Effects, published in December 2019, is 81 pages of exactly this problem at scale: “Together these datasets allowed us to process a total of 18.27 million images of 8.49 million people through 189 mostly commercial algorithms from 99 developers”. The executive summary's finding is one sentence long. “Across demographics, false positives rates often vary by factors of 10 to beyond 100 times.” A false positive here is a returned neighbor who is not the person. Same ruler, same setting, wrong up to a hundred times more often depending on who is standing in front of the camera. The U.S. Commission on Civil Rights restated the measurement in September 2024 and named the knob: “false positives and false negative rates are determined by a cutoff threshold set for the algorithm by the user”. The abstention rule is not a detail bolted onto the system. It is the system's decision about when a neighbor counts.

In one U.S. city that decision is now a court order. Robert Williams was wrongfully arrested in 2020 after a facial-recognition match. On 28 June 2024 the U.S. District Court for the Eastern District of Michigan closed the case he brought, Williams v. City of Detroit. “Police will be prohibited from arresting people based solely on facial recognition results, or on the results of photo lineups directly following a facial recognition search,” the ACLU announced that day. An independent case-law record describes the same order as “prohibiting arrests based solely on FRT results, an audit of all DPD cases in which FRT was used to obtain an arrest warrant since February 22, 2017, and a DPD training program about FRT required for 4 years from the effective date of the agreement”. Williams' own summary of why the rule was needed is the shortest statement of the risk in this lesson: “The scariest part is that what happened to me could have happened to anyone”.

Inspect absolute distances, neighbor stability, and reference examples. Consider a maximum radius or abstention rule when forced matches would mislead downstream users. Detroit's version of that rule is enforceable in federal court for four years.

A ranking of neighbors is not evidence that a good neighbor exists.

Analogy

A tailor choosing where to measure a garment

A tailor compares jackets by sleeve length, chest width, fabric pattern, and overall silhouette. One tape measure cannot capture every kind of resemblance.

A tailor can switch criteria mid-conversation, whereas an algorithm applies one encoded relation across the dataset. The ruler is chosen once, before any pair is compared.

Choose the ruler that respects the distinction the task cares about.

Steps

Audit a candidate similarity measure

Design tests around pairs that should be close, pairs that should be far, and transformations that should not matter. Name the invariances first: state whether scale, translation, length, order, rotation, or shared absence should affect similarity. Build contrast pairs whose relationship domain experts can explain before seeing the metric. Normalize deliberately, according to feature semantics. Then inspect neighborhoods across dense, sparse, common and rare regions. Finally, stress the relation by perturbing irrelevant fields, and confirm that neighborhoods stay stable when they should.

The last two steps have a number attached to them, which makes them a test rather than an intention. Radovanović and colleagues named the failure mode in the Journal of Machine Learning Research in 2010. “Through theoretical and empirical analysis involving synthetic and real data sets we show that under commonly used assumptions this distribution becomes considerably skewed as dimensionality increases, causing the emergence of hubs, that is, points with very high k-occurrences which effectively represent "popular" nearest neighbors.” A hub is a record that turns up in everyone's neighbor list while treating almost none of them as its own neighbor. The relation has quietly stopped being symmetric.

That asymmetry is directly measurable. Take the k nearest neighbors of every point and count what fraction of those relations are returned in both directions. Roman Feldbauer and Arthur Flexer ran that count across an unusually wide sweep: “We evaluate the previously described methods on 50 different public machine learning data sets”. Their untreated starting point is “Baseline DS=0.50”. Half of all neighbor relations are one-way. Repairing the geometry moves that number, and by how much depends on the repair: “All local and global scaling methods consistently increase the number of symmetric neighborhood relations in nearly all cases (MP: DS=0.73, MPGaussI: DS=0.65, LS: DS=0.74, NICDM: DS=0.75)”, with localized centering and local DisSim both reaching 0.76. Run the same count on your own neighborhoods before you build anything on top of them. 0.50 is what an unaudited space looks like.

FigureProcess · 5 steps
  1. 1. Name invariances

    State whether scale, translation, length, order, rotation, or shared absence should affect similarity.

  2. 2. Build contrast pairs

    Collect examples whose relationship domain experts can explain before seeing the metric.

  3. 3. Normalize deliberately

    Apply scaling, weighting, or vector normalization according to feature semantics.

  4. 4. Inspect neighborhoods

    Review nearest examples across dense, sparse, common, and rare regions.

  5. 5. Stress the relation

    Perturb irrelevant fields and confirm that neighborhoods remain stable when they should.

Similarity is a policy about evidence

A metric determines which differences count, how dimensions trade off, and whether magnitude matters. That policy should be documented as clearly as a model architecture. Later clustering and anomaly methods inherit this geometry. If the neighborhoods are wrong, a sophisticated algorithm can only organize the wrong relationships more confidently.

The encouraging half of the evidence is that geometry is adjustable, and the adjustment can be measured. The Lk norm study did not stop at comparing Manhattan with Euclidean. It extended the norm to fractional values of k, and reported that those metrics gave “more meaningful results both from the theoretical and empirical perspective”. Fractional distances, its authors found, “can significantly improve the effectiveness of standard clustering algorithms such as the k-means algorithm”. The same is true of every choice in this lesson. 0.38 became 0.50 on an unchanged corpus of web pages. 0.50 became 0.76 on 50 data sets. And a threshold that varies in accuracy by factors of 10 to beyond 100 became, in one jurisdiction, a rule about when the system is not allowed to answer. A geometry is a hypothesis. It can be tested.

Validate neighborhoods before trusting structures built from them.

Key takeaways