Skip to content
fn

cosine_similarity

→Tensor
cosine_similarity(x1: Tensor, x2: Tensor, dim: int = 1, eps: float = 1e-08)

Cosine similarity between two tensors along a dimension.

Measures the angle between two vectors irrespective of their magnitudes — the natural similarity metric for unit-norm embedding spaces (contrastive learning, retrieval, face verification).

Parameters

Tensors that broadcast together; both are expanded to the common shape first, and the norms are taken over the expanded tensors, so a 0-d operand is the scalar repeated along dim. Operands of two floating dtypes meet in their promoted dtype, a 0-d one counting as the dimensioned tensor it has become.
Tensors that broadcast together; both are expanded to the common shape first, and the norms are taken over the expanded tensors, so a 0-d operand is the scalar repeated along dim. Operands of two floating dtypes meet in their promoted dtype, a 0-d one counting as the dimensioned tensor it has become.
dimint= 1
Dimension of the broadcast shape along which the dot product / norms are taken. Default 1.
epsfloat= 1e-08
Lower bound on the denominator to avoid division by zero. Default 1e-8.

Returns

Tensor

Similarity tensor whose shape matches the inputs with dim reduced, values in [−1,1][-1, 1].

Notes

cosine_sim(x1,x2)=x1⋅x2max⁡(∥x1∥2 ∥x2∥2, ϵ)\text{cosine\_sim}(x_1, x_2) = \frac{x_1 \cdot x_2}{\max(\|x_1\|_2 \, \|x_2\|_2,\, \epsilon)}

For pairwise similarity matrices, use unsqueeze to broadcast the inputs into rank-3 tensors before calling this function.

Examples

>>> import lucid
>>> from lucid.nn.functional import cosine_similarity
>>> a = lucid.tensor([[1.0, 0.0]])
>>> b = lucid.tensor([[1.0, 1.0]])
>>> cosine_similarity(a, b, dim=1)
tensor([0.7071])

Used by 1