fn

pairwise_distance

Tensor
pairwise_distance(x1: Tensor, x2: Tensor, p: float = 2.0, eps: float = 1e-06, keepdim: bool = False)
source

Element-wise LpL_p distance between two equally-shaped tensors.

Computes the per-row LpL_p norm of the difference — the standard metric in metric-learning triplet and contrastive losses.

Parameters

x1Tensor
Tensors of the same shape. Distance is reduced over the last dimension.
x2Tensor
Tensors of the same shape. Distance is reduced over the last dimension.
pfloat= 2.0
Order of the norm. 2 for Euclidean, 1 for Manhattan. Default 2.0.
epsfloat= 1e-06
Small constant added to |x1 - x2| before the power so the derivative is finite even at coincident points. Default 1e-6.
keepdimbool= False
If True, retain the reduced dimension with size 1. Default False.

Returns

Tensor

Distance tensor.

Notes

dp(x1,x2)=x1x2+ϵp=(i(x1,ix2,i+ϵ)p)1/pd_p(x_1, x_2) = \big\| |x_1 - x_2| + \epsilon \big\|_p = \Big(\sum_i (|x_{1,i} - x_{2,i}| + \epsilon)^p\Big)^{1/p}

The eps shift inside the norm matters for gradient stability — at x1=x2x_1 = x_2 the bare LpL_p distance is non-differentiable when p<2p < 2; the offset converts the kink into a finite-slope smooth point.

Examples

>>> import lucid
>>> from lucid.nn.functional import pairwise_distance
>>> a = lucid.tensor([[1.0, 2.0]])
>>> b = lucid.tensor([[4.0, 6.0]])
>>> pairwise_distance(a, b, p=2.0)
Tensor([5.0000])