Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Distances

Open in Colab

A common task when dealing with data is computing the distance between two points.

We can use scipy.spatial.distance to compute a variety of distances.

A data set is a collection of observations, each of which may have several features. We’ll consider the situation where the data set is a matrix X, where each row X[i] is an observation. We’ll use n to denote the number of observations and p to denote the number of features, so X is a n×pn \times p matrix.

For example, we might sample from a circle (with some gaussian noise)

<Figure size 432x288 with 1 Axes>

We might also call a data set a “point cloud”, or a collection of points in some space.

Similarity, Dissimilarity, and Metric

A similarity between two points x,y∈Xx, y\in X is a function s:X×X→Rs: X \times X \to \mathbb{R}, where ss is larger if x,yx,y are more similar.

Cosine similarity is an an example of similarity for points in a real vector space. We can define it as

c(x,y)=xTy∥x∥2∥y∥2c(x,y) = \frac{x^T y}{\|x\|_2 \|y\|_2}

Note c(x,x)=1c(x,x) = 1, and if x,yx,y are orthogonal, then c(x,y)=0c(x,y) = 0.

A dissimilarity between two points x,y∈Xx,y \in X is a function d:X×X→R+d: X \times X \to \mathbb{R}_+, where dd is smaller if x,yx,y are more similar. Sometimes, disimilarity functions will be called distances.

Cosine distance is an example of a dissimilarity for points in a real vector space. It is defined as

d(x,y)=1−c(x,y)d(x,y) = 1 - c(x,y)

Note d(x,x)=0d(x,x) = 0, and d(x,y)=1d(x,y) = 1 if x,yx,y are orthogonal.

A metric is a disimilarity dd that satisfies the metric axioms

  1. d(x,y)=0d(x,y) = 0 iff x=yx=y (identity)

  2. d(x,y)=d(y,x)d(x,y) = d(y,x) (symmetry)

  3. d(x,y)≤d(x,z)+d(z,y)d(x,y) \le d(x,z) + d(z,y) (triangle inequality)

You are probably most familiar with the Euclidean metric

d(x,y)=∥x−y∥2d(x,y) = \|x - y\|_2

Exercise

Write functions for the cosine similarity, cosine distance, and euclidean distance between two numpy arrays treated as vectors.

Solution:

Computing Distances

SciPy provides a variety of functionality for computing distances in scipy.spatial.distance.

1.4142135623730951
1.0

the L1L_1 / Manhattan / City block distance

d(x,y)=∥x−y∥1=∑i∣xi−yi∣d(x,y) = \|x - y\|_1 = \sum_i |x_i - y_i|
2.0

The L∞L_\infty / Chebyshev distance

d(x,y)=∥x−y∥∞=max⁡i∣xi−yi∣d(x,y) = \|x - y\|_\infty = \max_i |x_i - y_i|
1.0

More generally, the Minkowski distance

d(x,y)=∥x−y∥p=(∑i(xi−yi)p)1/pd(x,y) = \|x - y\|_p = \big( \sum_i (x_i - y_i)^p \big)^{1/p}
1.2599210498948732
1.2599210498948734

The Mahalanobis distance. Note that this is defined in terms of an inverse covariance matrix. In fact, you can use it to compute distances based on the AA-norm where AA is any symmetric positive definite (SPD) matrix.

d(x,y)=∥x−y∥A=(x−y)TA(x−y)d(x,y) = \| x- y \|_A = \sqrt{(x - y)^T A (x - y)}
2.666670669798328

You can also weight many distances with a vector ww. The entry wiw_i will weight the comparison between the iith entries of xx and yy. E.g. weighted euclidean distance

d(x,y;w)=∑iwi(xi−yi)2d(x, y; w) = \sqrt{\sum_i w_i(x_i - y_i)^2}
1.7320508075688774
3.0
1.4422495703074083

Exercise

Compute a weighted euclidean distance using the Mahalanobis distance.

Pairwise Distances

In general, we often want to compute distances between many points all at once. This typically boils down to computing a matrix DD, where Di,j=d(xi,xj)D_{i,j} = d(x_i, x_j).

Here’s a simple function that would do just that

array([[0. , 1.94237948, 1.90940651, 1.69649549, 2.062052 ], [1.94237948, 0. , 0.07479893, 0.52887254, 0.74132462], [1.90940651, 0.07479893, 0. , 0.56782601, 0.67473708], [1.69649549, 0.52887254, 0.56782601, 0. , 1.20893148], [2.062052 , 0.74132462, 0.67473708, 1.20893148, 0. ]])
array([[0. , 2.35348345, 2.33298607, 1.88832923, 2.59101514], [2.35348345, 0. , 0.07387947, 0.56261554, 0.72452761], [2.33298607, 0.07387947, 0. , 0.57903245, 0.65586844], [1.88832923, 0.56261554, 0.57903245, 0. , 1.16755777], [2.59101514, 0.72452761, 0.65586844, 1.16755777, 0. ]])

There are a couple of inneficiencies above:

  1. D is symmetric (we do redundant computation)

  2. For some metrics, it can be more efficient to compute many distances at once

As an example of point 2, pairwise euclidean distances are

d(xi,xj)=(xi−xj)T(xi−xj)=xiTxi−2xiTxj+xjTxjd(x_i, x_j) = \sqrt{(x_i - x_j)^T (x_i -x_j)}\\ = \sqrt{x_i^T x_i - 2 x_i^T x_j + x_j^T x_j}

Let x2x^2 denote the vector of length nn where xi2=xiTxix_i^2 = x_i^T x_i, and let 1 denote the vector of ones (of length nn). Then

D=1x2T+x21T−2XXTD = \sqrt{1 x^{2T} + x^2 1^T - 2 X X^T}

Thus, we can take advantage of BLAS level 3 operations to compute the distance matrix

1.3184628807076516e-15

We can also use BLAS syr2 for the rank-2 update:

a = dsyr2(alpha,x,y,[lower,incx,offx,incy,offy,n,a,overwrite_a])

Wrapper for ``dsyr2``.

Parameters
----------
alpha : input float
x : input rank-1 array('d') with bounds (*)
y : input rank-1 array('d') with bounds (*)

Other Parameters
----------------
lower : input int, optional
    Default: 0
incx : input int, optional
    Default: 1
offx : input int, optional
    Default: 0
incy : input int, optional
    Default: 1
offy : input int, optional
    Default: 0
n : input int, optional
    Default: ((len(x)-1-offx)/abs(incx)+1 <=(len(y)-1-offy)/abs(incy)+1 ?(len(x)-1-offx)/abs(incx)+1 :(len(y)-1-offy)/abs(incy)+1)
a : input rank-2 array('d') with bounds (n,n)
overwrite_a : input int, optional
    Default: 0

Returns
-------
a : rank-2 array('d') with bounds (n,n)

1.2414222253120274e-15
pairwise : 0.14259719848632812 sec.
pairwise_euclidean : 0.0009162425994873047 sec.
pairwise_euclidean_blas : 0.0005114078521728516 sec.

Exercise

Write a version of pairwise_euclidean which uses Numba. How does this compare to the BLAS implementation?

pdist

You don’t need to implement these faster methods yourself. scipy.spatial.distance.pdist has built-in optimizations for a variety of pairwise distance computations. You can use scipy.spatial.distance.cdist if you are computing pairwise distances between two data sets X,YX, Y.

The output of pdist is not a matrix, but a condensed form which stores the lower-triangular entries in a vector.

(4950,)

to get a square matrix, you can use squareform. You can also use squareform to go back to the condensed form.

(100, 100)
(4950,)

pdist takes in a keyword argument metric, which determines the distance computed

array([2.08938154, 3.11065611, 0.93840319, ..., 2.2620697 , 1.07479868, 1.64700974])

Let’s compare to our implementations

pairwise : 0.22939705848693848 sec.
pairwise_euclidean : 0.0007569789886474609 sec.
pairwise_euclidean_blas : 0.00044345855712890625 sec.
pdist : 0.00022459030151367188 sec.

If we form the squareform:

pairwise : 0.1943039894104004 sec.
pairwise_euclidean : 0.0005679130554199219 sec.
pairwise_euclidean_blas : 0.0003407001495361328 sec.
sq_pdist : 0.00029754638671875 sec.
(30, 70)

Exercise

Use pdist to compute ’braycurtis’, ‘canberra’, ‘chebyshev’, ‘cityblock’, ‘correlation’, ‘cosine’, and ‘euclidean’, distances on a random X. Are there noticeable differences in the time it takes to compute each distance?