Skip to content
fn

pairwise_distance

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

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

Tensors of the same shape. Distance is reduced over the last dimension.
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 norm, as the reference does. Default 1e-6.
keepdimbool= False
If True, retain the reduced dimension with size 1. Default False.

Returns

Tensor

Distance tensor.

Notes

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

The eps shift keeps coincident points off the norm's kink. With eps=0 they sit on it, and their gradient is 0 — the subgradient the reference picks — not nan. The shift used to be added to |x1 - x2| instead, which differs by up to 2 * eps per entry where x1 < x2.

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.])

Used by 1