scipy.spatial.distance.

cosine#

scipy.spatial.distance.cosine(u, v, w=None)[source]#

Compute the Cosine distance between two arrays.

The Cosine distance between u and v, is defined as

\[1 - \frac{u \cdot v} {\|u\|_2 \|v\|_2}.\]

where \(u \cdot v\) is the dot product of \(u\) and \(v\).

Parameters:
u(…, N) array_like of floats

Input array.

v(…, N) array_like of floats

Input array.

w(…, N) array_like of floats, optional

The weights for each value in u and v. Default is None, which gives each value a weight of 1.0

Returns:
cosinefloat or array

The Cosine distance between arrays u and v.

Notes

Array API Standard Support

cosine has support for Python Array API Standard compatible backends in addition to NumPy. The following combinations of backend and device (or other capability) are supported.

Library

CPU

GPU

NumPy

✅

n/a

CuPy

n/a

✅

PyTorch

✅

✅

JAX

✅

✅

Dask

✅

n/a

See Support for the array API standard for more information.

Examples

>>> from scipy.spatial import distance
>>> distance.cosine([1, 0, 0], [0, 1, 0])
1.0
>>> distance.cosine([100, 0, 0], [0, 1, 0])
1.0
>>> distance.cosine([1, 1, 0], [0, 1, 0])
0.29289321881345254