A store describes each customer by the distance to the store in kilometers and the number of orders per week. Which two customers are most alike? Similarity-based methods such as k-nearest neighbors and clustering answer with a number computed from the feature vectors, and that number depends on the units, on how the features are weighted and on how many features there are. This lesson compares Euclidean distance with cosine similarity, shows the weights hidden in a choice of units, and works out exactly how distances concentrate in one stated high-dimensional model.
Key terms
Distance measure
Definition A distance measure, or dissimilarity, assigns a number to two feature vectors and in , with smaller values meaning more alike. It is a metric when, for all vectors , and , it is zero exactly when the two vectors are equal, it is symmetric, , and it satisfies the triangle inequality
The Euclidean and Manhattan distances
are metrics on . The squared Euclidean distance is not a metric, because it can break the triangle inequality, yet it is the quantity that k-means minimizes. Every such number is computed in the representation supplied, so the choice of features, units and weights is part of the model.
In plain words A distance turns the question of how alike two records are into one number. Euclidean distance is the straight-line length of the difference vector, and Manhattan distance adds the absolute differences coordinate by coordinate. Neither knows what one unit of a feature means, so the number is only as meaningful as the representation it is computed in.
Example For and in a common dimensionless scale, the difference is . The Euclidean distance is , the Manhattan distance is and the squared Euclidean distance is 25. For the points 0, 1 and 2 on a line, the squared distances are 1 from 0 to 1, 1 from 1 to 2 and 4 from 0 to 2. Since , the squared distance breaks the triangle inequality.
Cosine similarity
Definition For nonzero vectors and in , the cosine similarity is
the cosine of the angle between the two vectors. By the Cauchy-Schwarz inequality it lies in . It equals 1 exactly when for some , it equals exactly when , and it does not change when either vector is multiplied by a positive number. It is undefined when either vector is zero, since a norm in the denominator is then 0. The cosine distance is a common dissimilarity but not a metric, since it is 0 for different vectors that point the same way and it can break the triangle inequality. After each nonzero vector is divided by its norm,
so ranking candidates from most to least similar by cosine similarity gives the same order as ranking the unit vectors from nearest to farthest by Euclidean distance.
In plain words Cosine similarity compares directions and ignores lengths. Two profiles with the same proportions score 1, however different their totals are. That suits questions about mix or composition, such as the word proportions of documents, and it is the wrong choice when the size itself carries the signal, such as total demand.
Example For and , the dot product is and the norms are and , so
an angle of about 7.1 degrees. The vector has cosine similarity 1 with , although its Euclidean distance from is . For the triangle inequality, take , and . The cosine distance from the first vector to the third is , while each of the two steps through has cosine distance , a total of about 0.586.
Feature weighting
Definition A weighted squared Euclidean distance with weights is
Feature weighting is the choice of these weights, made on purpose or implied by the units. Measuring feature in a unit that is times smaller multiplies its values by and its squared differences by , which is the same as multiplying by . Standardization with the training mean and training standard deviation of each feature gives the weights in the original units. These statistics are computed on the training data only and applied unchanged to validation, test and new cases. A feature with in the training data needs a declared rule, such as dropping it, because the division is undefined. A weight of zero removes a feature from the comparison.
In plain words Every distance on several features already contains weights, and the units choose them unless someone chooses on purpose. Standardization makes one training standard deviation the unit on every axis, which removes the dependence on units. Equal scale is not equal importance, though. A feature of pure noise gets the same standardized influence as a meaningful one, so domain knowledge, feature selection or a learned metric may set better weights.
Example Multiply the second coordinate of and by 100, as a switch to a unit 100 times smaller would. The difference becomes and the distance becomes instead of 5, although the observations did not change. Now suppose the training standard deviations of the two features are 1.5 and 2 in the original units. The standardized differences are and , so the standardized distance is . In the new unit the second standard deviation is 200 and the second difference is 400, so the standardized difference is still 2 and the standardized distance does not change.
Curse of dimensionality
Definition The curse of dimensionality is the collective name for difficulties that grow with the number of features when the amount of data does not grow fast enough. Three of them concern distances. The first is coverage. Splitting the range of each feature into bins gives cells, so a fixed number of examples leaves almost every cell empty as grows. The second is the size of neighborhoods. For data spread uniformly over the unit cube , a smaller cube that holds a fraction of the data needs edge length , which tends to 1 as grows, so a neighborhood that holds only a few points is no longer local. The third is irrelevant features. Euclidean distance adds the squared differences of all features, so many features unrelated to the target can outweigh the few that matter. How strong these effects are depends on the data distribution. Data with many recorded features often lie near a structure of much lower dimension, and then the number of columns alone overstates the difficulty.
In plain words Each added feature multiplies the room the data must fill. With many independent features, the nearest neighbors stop being near in any absolute sense, and sums over many noisy coordinates can drown a useful signal. Methods built on local neighborhoods, such as k-nearest neighbors and clustering, feel these effects first.
Example With 10 bins per axis there are 10 cells in one dimension, 100 in two and in twenty. A million examples occupy at most of those cells, a fraction of at most . For uniform data in ten dimensions, a cube that holds 1 percent of the data has edge length , so it spans 63 percent of the range of every feature.
Distance concentration
Definition Distance concentration is the tendency, under some data distributions, of distances to vary little relative to their typical size as the dimension grows, so that the nearest and the farthest points of a sample lie at nearly the same distance in ratio. One model where this can be computed exactly takes two independent random points and in whose coordinates are independent and uniform on . Each coordinate difference has and , so . The squared distance is a sum of independent terms, so
The relative spread shrinks like . More generally, take a fixed number of points whose squared distances from a query share one distribution with finite variance. If its relative spread tends to 0 as grows, Chebyshev’s inequality shows that each ratio tends to 1 in probability, and then so does the ratio of the largest to the smallest distance. The conclusion needs that condition, and it can fail. Correlated coordinates, a low intrinsic dimension, heavy tails or a few strongly informative directions can keep distances informative.
In plain words In this model, almost every pair of points is about the same distance apart when measured against the typical distance. The absolute spread does not vanish. In simulations the distance keeps a standard deviation between about 0.23 and 0.25 for every dimension tried from 1 to 1000, while its mean grows roughly like . Nearest-neighbor methods rely on the gap between near and far relative to the typical distance, so with such data the nearest neighbor is, in ratio, barely nearer than a typical point. The computation describes one stated distribution and does not prove that all high-dimensional distances are useless.
Example The relative spread of the squared distance is at and at . A seeded simulation of the same model draws 100 points and one query 200 times in each dimension and records the ratio of the farthest to the nearest distance. Its median falls from about 21 at to about 2.6 at , 1.3 at and 1.09 at .
import numpy as np
rng = np.random.default_rng(5312)
for d in (2, 10, 100, 1000):
ratios = []
for _ in range(200): # 200 repetitions
X = rng.random((100, d)) # 100 points, uniform coordinates
q = rng.random(d) # one query from the same model
dist = np.sqrt(((X - q) ** 2).sum(axis=1))
ratios.append(dist.max() / dist.min())
print(d, np.median(ratios)) # farthest over nearestCheck yourself
- Two constructed purchase profiles count the items bought in two product types, and . Find their Euclidean distance and their cosine similarity. Which comparison suits grouping customers by their relative purchasing mix, and what does it leave out?
Show the answer
The difference is , so the Euclidean distance is . The second profile is 1.5 times the first, so the cosine similarity is 1. The direct computation agrees, since the dot product is and the product of the norms is .
Cosine similarity suits relative mix, because both customers buy the two types in the proportion 1 to 2, and it rightly calls them identical in that respect. It discards the total volume, 6 items against 9. For a question such as inventory planning, where volume matters, a comparison that keeps magnitude is needed, such as Euclidean distance on suitably scaled counts or a separate feature for the total.
- A query and two stored points have ten standardized features, and only the first feature is related to the target. Point B differs from the query by 0.1 in the first feature and by 1 in each of the other nine. Point C differs by 2 in the first feature and agrees with the query in the other nine. Which point is nearer in Euclidean distance, and which is nearer on the first feature alone?
Show the answer
The squared distances are for B and for C, so C is nearer, at distance 2 against about 3.002. On the first feature alone B is nearer, at 0.1 against 2.
Standardization does not prevent this, because the features are already on a common scale. The nine irrelevant features add noise to every distance and reverse the ranking. Giving them weight zero, or selecting features, restores the comparison that matters, and such choices should be made with training and validation data rather than the test set.
- In the uniform model of this lesson, find and the relative spread of at . Then suppose instead that every coordinate of a point equals one uniform variable, so that and with and independent and uniform on . Find the relative spread of in this model. What does the comparison show?
Show the answer
At the mean is and the variance is , so the standard deviation is and the relative spread is
In the second model . Its mean is and its variance is , so the relative spread is
for every . The points lie on the diagonal of the cube, a one-dimensional structure inside dimensions, and their distances do not concentrate at all. Concentration depends on the distribution of the data, not on the number of columns alone.