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.
import time
import numpy as np
import scipy.linalg as la
import scipy.spatial.distance as distance
from scipy.spatial.distance import cdist, pdist, squareform
import matplotlib.pyplot as pltA 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 matrix.
For example, we might sample from a circle (with some gaussian noise)
def sample_circle(n, r=1, sigma=0.1):
"""
sample n points from a circle of radius r
add Gaussian noise with variance sigma^2
"""
X = np.random.randn(n,2)
X = r * X / np.linalg.norm(X,axis=1).reshape(-1,1)
return X + sigma * np.random.randn(n,2)
X = sample_circle(100)
plt.scatter(X[:,0], X[:,1])
plt.show()
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 is a function , where is larger if are more similar.
Cosine similarity is an an example of similarity for points in a real vector space. We can define it as
Note , and if are orthogonal, then .
A dissimilarity between two points is a function , where is smaller if 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
Note , and if are orthogonal.
A metric is a disimilarity that satisfies the metric axioms
iff (identity)
(symmetry)
(triangle inequality)
You are probably most familiar with the Euclidean metric
Exercise¶
Write functions for the cosine similarity, cosine distance, and euclidean distance between two numpy arrays treated as vectors.
## Your code here
Solution:¶
Computing Distances¶
SciPy provides a variety of functionality for computing distances in scipy.spatial.distance.
x = [1.0, 0.0]
y = [0.0, 1.0]
distance.euclidean(x, y) # sqrt(2)1.4142135623730951distance.cosine(x, y)1.0the / Manhattan / City block distance
distance.cityblock(x, y)2.0The / Chebyshev distance
distance.chebyshev(x, y)1.0More generally, the Minkowski distance
distance.minkowski(x, y, 3)1.2599210498948732np.cbrt(2) # cube root of 21.2599210498948734The 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 -norm where is any symmetric positive definite (SPD) matrix.
A = np.random.randn(3,2)
A = A.T @ A
distance.mahalanobis(x, y, A)2.666670669798328You can also weight many distances with a vector . The entry will weight the comparison between the th entries of and . E.g. weighted euclidean distance
w = [1, 2]
for d in (distance.euclidean, distance.cityblock, lambda x, y, w : distance.minkowski(x, y, 3, w)):
print(d(x, y, w))1.7320508075688774
3.0
1.4422495703074083
Exercise¶
Compute a weighted euclidean distance using the Mahalanobis distance.
## Your code here
Pairwise Distances¶
In general, we often want to compute distances between many points all at once. This typically boils down to computing a matrix , where .
Here’s a simple function that would do just that
def pairwise(X, dist=distance.euclidean):
"""
compute pairwise distances in n x p numpy array X
"""
n, p = X.shape
D = np.empty((n,n), dtype=np.float64)
for i in range(n):
for j in range(n):
D[i,j] = dist(X[i], X[j])
return DX = sample_circle(5)
pairwise(X)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. ]])pairwise(X, dist=lambda x, y : distance.minkowski(x, y, 3, [1.0, 2.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:
D is symmetric (we do redundant computation)
For some metrics, it can be more efficient to compute many distances at once
As an example of point 2, pairwise euclidean distances are
Let denote the vector of length where , and let 1 denote the vector of ones (of length ). Then
Thus, we can take advantage of BLAS level 3 operations to compute the distance matrix
def pairwise_euclidean(X):
"""
Compute pairwise euclidean distances in X
"""
XXT = X @ X.T
x2 = np.diag(XXT)
one = np.ones(X.shape[0])
D = np.outer(x2, one) + np.outer(one, x2) - 2*XXT
return np.sqrt(D)
la.norm(pairwise_euclidean(X) - pairwise(X))1.3184628807076516e-15We can also use BLAS syr2 for the rank-2 update:
print(la.blas.dsyr2.__doc__)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)
def pairwise_euclidean_blas(X):
"""
Compute pairwise euclidean distances in X
use syrk2 for rank-2 update
"""
XXT = X @ X.T
x2 = np.diag(XXT)
one = np.ones(X.shape[0])
D = la.blas.dsyr2(1.0, x2, one, a=-2*XXT) # this only updates upper triangular part
D = np.triu(D) # extract upper triangular part
return np.sqrt(D + D.T)
la.norm(pairwise_euclidean_blas(X) - pairwise(X))1.2414222253120274e-15import time
# generate data set
n = 100
d = 2
X = np.random.randn(n, d)
for d in (pairwise, pairwise_euclidean, pairwise_euclidean_blas):
t0 = time.time()
D = d(X)
t1 = time.time()
print("{} : {} sec.".format(d.__name__, t1 - t0))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?
## Your code here
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 .
from scipy.spatial.distance import pdist, cdistD = pdist(X)The output of pdist is not a matrix, but a condensed form which stores the lower-triangular entries in a vector.
D.shape(4950,)to get a square matrix, you can use squareform. You can also use squareform to go back to the condensed form.
from scipy.spatial.distance import squareform
D = squareform(D)
D.shape(100, 100)squareform(D).shape(4950,)pdist takes in a keyword argument metric, which determines the distance computed
pdist(X, metric='cityblock')array([2.08938154, 3.11065611, 0.93840319, ..., 2.2620697 , 1.07479868,
1.64700974])Let’s compare to our implementations
import time
# generate data set
n = 100
d = 2
X = np.random.randn(n, d)
for d in (pairwise, pairwise_euclidean, pairwise_euclidean_blas, pdist):
t0 = time.time()
D = d(X)
t1 = time.time()
print("{} : {} sec.".format(d.__name__, t1 - t0))pairwise : 0.22939705848693848 sec.
pairwise_euclidean : 0.0007569789886474609 sec.
pairwise_euclidean_blas : 0.00044345855712890625 sec.
pdist : 0.00022459030151367188 sec.
If we form the squareform:
import time
# generate data set
n = 100
d = 2
X = np.random.randn(n, d)
def sq_pdist(X, **kwargs):
return squareform(pdist(X, **kwargs))
for d in (pairwise, pairwise_euclidean, pairwise_euclidean_blas, sq_pdist):
t0 = time.time()
D = d(X)
t1 = time.time()
print("{} : {} sec.".format(d.__name__, t1 - t0))pairwise : 0.1943039894104004 sec.
pairwise_euclidean : 0.0005679130554199219 sec.
pairwise_euclidean_blas : 0.0003407001495361328 sec.
sq_pdist : 0.00029754638671875 sec.
D = cdist(X[:30],X[30:])
D.shape(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?
## Your code here