Cosine similarity between two tensors along a specified dimension.
Computes element-wise cosine similarity:
The result is a scalar (or tensor with dim reduced) in the range
, where indicates identical direction,
orthogonality, and opposite direction. The eps floor
on the denominator prevents division by zero for zero-norm vectors.
Parameters
dimint= 1Dimension along which cosine similarity is computed. Default:
1.epsfloat= 1e-08Small value added to the denominator for
numerical stability. Default:
1e-8.Notes
- Input
x1: or any shape broadcastable tox2. - Input
x2: or any shape broadcastable tox1. - Output: —
dimis reduced; same batch dimensions as input.
Examples
>>> import lucid
>>> import lucid.nn as nn
>>> m = nn.CosineSimilarity(dim=1)
>>> x1 = lucid.tensor([[1.0, 0.0], [0.0, 1.0]])
>>> x2 = lucid.tensor([[1.0, 0.0], [1.0, 0.0]])
>>> m(x1, x2)
tensor([1., 0.])
>>> # Comparing sentence embeddings along the feature dimension
>>> emb1 = lucid.randn(32, 768)
>>> emb2 = lucid.randn(32, 768)
>>> sim = nn.CosineSimilarity(dim=1)(emb1, emb2)
>>> sim.shape
(32,)Used by 1
Constructors
1Instance methods
2Return a string representation of the layer's configuration.