Vector normalization
Normalize feature vectors, embeddings, or geometric directions by dividing each vector by its length.
NumPy · Function
Computes vector or matrix norms for an array-like input. The norm type and dimensions being reduced are controlled by ord and axis.
Convert an array-like input into vector or matrix norms. Choose the norm order with ord, select vector or matrix axes with axis, and use keepdims to preserve reduced axes for broadcasting.
numpy.linalg.norm(x, ord=None, axis=None, keepdims=False)| Name | Type | Description |
|---|---|---|
x | array_like | Input array. |
ord | {int, float, inf, -inf, 'fro', 'nuc'}, optional | Order of the norm; supported values depend on whether a vector or matrix norm is selected. |
axis | {None, int, 2-tuple of ints}, optional | Axis selection: None, one integer for vector norms, or a two-integer tuple for matrix norms. |
keepdims | bool, optional | Whether normed axes remain in the output with size one. |
nfloat or ndarray — Norm of the matrix or vector(s).
import numpy as np
vectors = np.array([[3.0, 4.0], [5.0, 12.0]])
lengths = np.linalg.norm(vectors, axis=1, keepdims=True)
unit_vectors = vectors / lengths
print(lengths.ravel())
print(unit_vectors)Computes each row's Euclidean length, retains a singleton dimension for broadcasting, and normalizes the rows.
Normalize feature vectors, embeddings, or geometric directions by dividing each vector by its length.
Measure matrix size using Frobenius, nuclear, or induced norms selected by ord.
Compute one norm per vector in a batched array by selecting the vector axis.
It accepts an array-like x and returns a scalar or array containing vector or matrix norms. The selected norm depends on ord and, when supplied, axis.
Follow-up: How would you compute norms for rows in a two-dimensional array? Use axis=1; this selects the row dimension for vector norms and returns one value per row.
With axis=None, a one-dimensional x produces a vector norm and a two-dimensional x produces a matrix norm. If both axis and ord are None, x is flattened and its 2-norm is returned.
Follow-up: What is the default matrix norm in this case? For a two-dimensional input with ord=None, the documented table identifies it as the Frobenius norm.
ord selects the norm order, and supported values include integers, positive or negative infinity, 'fro', and 'nuc'. The page documents different supported combinations for matrices and vectors.
Follow-up: Which named orders are matrix-specific? 'fro' selects the Frobenius norm and 'nuc' selects the nuclear norm; these are not vector norm choices.
numpy.linalg.vector_normnumpy.linalg.matrix_normnumpy.linalg.svd