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
x1TensorTensors 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.x2TensorTensors 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= 1Dimension of the broadcast shape along which the dot product / norms
are taken. Default
1.epsfloat= 1e-08Lower bound on the denominator to avoid division by zero.
Default
1e-8.Returns
TensorSimilarity tensor whose shape matches the inputs with dim
reduced, values in .
Notes
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])