class
CosineSimilarity
extends
ModuleCosineSimilarity(dim: int = 1, eps: float = 1e-08)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,)Methods (3)
dunder
__init__
→None__init__(dim: int = 1, eps: float = 1e-08)Initialise the CosineSimilarity module. See the class docstring for parameter semantics.
fn
forward
→Tensorforward(x1: Tensor, x2: Tensor)Apply the activation function element-wise.
Parameters
inputTensorInput tensor of arbitrary shape.
Returns
TensorOutput tensor of the same shape as input.
fn
extra_repr
→strextra_repr()Return a string representation of the layer's configuration.