pairwise_cosine_similarity#
- class braintools.metric.pairwise_cosine_similarity(X, Y=None, eps=1e-08)#
Compute the pairwise cosine similarity matrix between samples in
XandY.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) to1(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
Xagainst every row ofY). For an element-wise similarity between paired samples, seebraintools.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.Quantityinputs 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). IfNone, computes pairwise similarities withinX.eps (
float) – Lower bound applied to each row norm (not their product) to avoid division by zero. Only norms belowepsare affected, so similarities between small but non-zero vectors are computed exactly; pairs that involve a zero vector still yield a similarity of0.
- Returns:
Cosine similarity matrix:
If
Yis provided: shape(n_samples_X, n_samples_Y).If
YisNone: shape(n_samples_X, n_samples_X).
Element
(i, j)is the cosine similarity between sampleiofXand samplejofY(orXifYisNone).- Return type:
Array
See also
cosine_similarityElement-wise cosine similarity between paired samples.
cosine_distanceElement-wise cosine distance (
1 - similarity).
Notes
Each row norm is floored at
eps(rather than addingepsto 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 naivedot / (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)