Cosine distance function.
Functions
cosine_distance(x1: np.ndarray, x2: np.ndarray) -> float
Compute cosine distance between two points.
Cosine distance measures the angular dissimilarity between two vectors, defined as 1 - \text{cosine\_similarity}.
Theory
d(x, y) = 1 - \frac{x \cdot y}{\|x\|_2 \, \|y\|_2}
Score interpretation:
- d = 0 -- Vectors have the same direction
- d = 1 -- Vectors are orthogonal
- d = 2 -- Vectors point in opposite directions
Parameters
x1
np.ndarray of shape (n_features,)
First point.
x2
np.ndarray of shape (n_features,)
Second point.
Returns
dist
float
Cosine distance in the range [0, 2].
Notes
Complexity:
- Time: O(n) where n is the number of features.
Orthogonal vectors have cosine distance 1.0:
python
>>> import numpy as np
>>> from tuiml.algorithms.clustering.distance import cosine_distance
>>> x1 = np.array([1, 0])
>>> x2 = np.array([0, 1])
>>> cosine_distance(x1, x2)
1.0
cosine_pairwise(X: np.ndarray, Y: np.ndarray=None) -> np.ndarray
Compute pairwise cosine distances.
Parameters
X
np.ndarray of shape (n_samples_X, n_features)
First set of samples.
Y
np.ndarray of shape (n_samples_Y, n_features)
= None
Second set of samples. Defaults to X.
Returns
dist_matrix
np.ndarray of shape (n_samples_X, n_samples_Y)
Distance matrix.