pairwise_cosine_similarity

pairwise_cosine_similarity#

class braintools.metric.pairwise_cosine_similarity(X, Y=None, eps=1e-08)#

Compute the pairwise cosine similarity matrix between samples in X and Y.

Cosine similarity measures the cosine of the angle between two vectors, providing a similarity metric that is independent of vector magnitude. It ranges from -1 (opposite directions) to 1 (same direction).

The cosine similarity between two vectors \(\mathbf{a}\) and \(\mathbf{b}\) is defined as:

\[\text{similarity}(\mathbf{a}, \mathbf{b}) = \frac{\mathbf{a} \cdot \mathbf{b}}{\lVert \mathbf{a} \rVert\, \lVert \mathbf{b} \rVert}\]

where \(\lVert \cdot \rVert\) denotes the L2 norm.

This function returns the full pairwise matrix of similarities (every row of X against every row of Y). For an element-wise similarity between paired samples, see braintools.metric.cosine_similarity().

Parameters:
  • X (Array | ndarray | bool | number | bool | int | float | complex | Quantity) – Input array with shape (n_samples_X, n_features). Each row is a sample/vector. brainunit.Quantity inputs are accepted; because cosine similarity is scale invariant, the result is always dimensionless.

  • Y (Array | ndarray | bool | number | bool | int | float | complex | Quantity | None) – Input array with shape (n_samples_Y, n_features). If None, computes pairwise similarities within X.

  • eps (float) – Lower bound applied to each row norm (not their product) to avoid division by zero. Only norms below eps are affected, so similarities between small but non-zero vectors are computed exactly; pairs that involve a zero vector still yield a similarity of 0.

Returns:

Cosine similarity matrix:

  • If Y is provided: shape (n_samples_X, n_samples_Y).

  • If Y is None: shape (n_samples_X, n_samples_X).

Element (i, j) is the cosine similarity between sample i of X and sample j of Y (or X if Y is None).

Return type:

Array

See also

cosine_similarity

Element-wise cosine similarity between paired samples.

cosine_distance

Element-wise cosine distance (1 - similarity).

Notes

Each row norm is floored at eps (rather than adding eps to the norm product), so that the value and the gradient remain finite for zero vectors while non-zero vectors – including very small ones – are unaffected. This avoids both the NaN-gradient hazard of the naive dot / (norm_product + eps) formulation and the magnitude-coupling bug of flooring the product of the two norms.

Examples

>>> import jax.numpy as jnp
>>> import braintools
>>> X = jnp.array([[1., 0., 0.], [0., 1., 0.], [1., 1., 0.]])
>>> sim_matrix = braintools.metric.pairwise_cosine_similarity(X)
>>> print(sim_matrix)
[[1.         0.         0.70710677]
 [0.         1.         0.70710677]
 [0.70710677 0.70710677 1.0000001 ]]

>>> Y = jnp.array([[1., 1., 1.], [0., 0., 1.]])
>>> braintools.metric.pairwise_cosine_similarity(X, Y).shape
(3, 2)