class
PairwiseDistance
extends
ModulePairwiseDistance(p: float = 2.0, eps: float = 1e-06, keepdim: bool = False)Pairwise distance between corresponding rows of two tensors.
Computes the norm of the difference vector for each pair of rows:
A small is added before the norm computation for
numerical stability. With p=2 this yields the standard Euclidean
distance; with p=1 the Manhattan distance.
Parameters
pfloat= 2.0The exponent of the norm. Default:
2.0.epsfloat= 1e-06Small added to the difference for numerical
stability. Default:
1e-6.keepdimbool= FalseIf
True, the reduced dimension is retained as a size-1 dimension
in the output. Default: False.Notes
- Input
x1: . - Input
x2: . - Output: if
keepdim=False, else .
Commonly used in Siamese networks and metric-learning objectives such as contrastive loss and triplet loss, where the distance between paired embeddings must be differentiable.
Examples
>>> import lucid
>>> import lucid.nn as nn
>>> m = nn.PairwiseDistance(p=2.0)
>>> x1 = lucid.tensor([[1.0, 0.0], [0.0, 1.0]])
>>> x2 = lucid.tensor([[0.0, 0.0], [0.0, 0.0]])
>>> m(x1, x2)
tensor([1.0000, 1.0000])
>>> # Euclidean distance for embedding comparison in a Siamese network
>>> emb1 = lucid.randn(64, 128)
>>> emb2 = lucid.randn(64, 128)
>>> dist = nn.PairwiseDistance(p=2.0)(emb1, emb2)
>>> dist.shape
(64,)Methods (3)
dunder
__init__
→None__init__(p: float = 2.0, eps: float = 1e-06, keepdim: bool = False)Initialise the PairwiseDistance 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.