Skip to content
fn

normalize

→Tensor
normalize(input: Tensor, p: float = 2.0, dim: DimLike = 1, eps: float = 1e-12)

Normalize a tensor to unit LpL_p norm along a dimension.

Parameters

inputTensor
Input tensor.
pfloat= 2.0
Exponent of the norm (default: 2.0 for Euclidean norm).
dimint, sequence of int, or None= 1
Dimension(s) along which to normalize (default: 1). A sequence takes the norm over all of them together; None over every element.
epsfloat= 1e-12
Lower bound on the denominator, for numerical stability.

Returns

Tensor

Normalized tensor with unit LpL_p norm along dim.

Notes

x^i=ximax⁡ ⁣(∥x∥p, ϵ),∥x∥p=(∑i∣xi∣p)1/p\hat{x}_i = \frac{x_i}{\max\!\big(\|x\|_p,\, \epsilon\big)}, \qquad \|x\|_p = \Big(\sum_i |x_i|^p\Big)^{1/p}

along the chosen dimension. The eps clamp avoids division by zero when the slice is all zeros. Use p=2 for cosine-similarity style embeddings, p=1 for probability-simplex projection-like behaviour, and p=inf for max-norm clipping. An integer or bool input is refused with a DtypeMismatch, as the reference refuses it.

Examples

>>> import lucid
>>> import lucid.nn.functional as F
>>> x = lucid.tensor([[3.0, 4.0]])
>>> F.normalize(x, p=2, dim=1)
tensor([[0.6, 0.8]])
>>> F.normalize(lucid.tensor([[3.0], [4.0]]), dim=None)
tensor([[0.6], [0.8]])

Used by 3