A norm measures the magnitude or length of a vector or matrix. NumPy provides the numpy.linalg.norm() function, which computes different types of vector and matrix norms depending on the parameters used. This allows evaluating size, strength, or distance of data in numerical and linear algebra operations.
Example: This example computes the Euclidean norm (default norm) of a vector using numpy.linalg.norm().
import numpy as np
v = np.array([3, 4])
out = np.linalg.norm(v)
print(out)
Output
5.0
Explanation: np.linalg.norm(v) computes the Euclidean distance √(3² + 4²).
Syntax
numpy.linalg.norm(x, ord=None, axis=None)
Parameters:
- x: Input vector or matrix.
- ord: Type of norm (e.g., 1-norm, 2-norm, ∞-norm).
- axis: Axis along which vector norms are computed; when None, computes entire array norm.
Examples
Example 1: This example computes the 1-norm (sum of absolute values) of a vector using ord=1.
import numpy as np
v = np.array([1, -2, 3, -4])
out = np.linalg.norm(v, ord=1)
print(out)
Output
10.0
Explanation: ord=1 -> computes |1| + |-2| + |3| + |-4|.
Example 2: This example computes the Frobenius norm of a matrix (default norm for 2-D arrays).
import numpy as np
m = np.array([[2, 3],
[6, 1]])
out = np.linalg.norm(m)
print(out)
Output
7.0710678118654755
Explanation: np.linalg.norm(m) calculates √(2² + 3² + 6² + 1²).
Example 3: This example computes the ∞-norm of each row in a matrix using axis=1, which returns the maximum absolute value in each row.
import numpy as np
m = np.array([[1, -7, 3],
[4, 2, -9]])
out = np.linalg.norm(m, ord=np.inf, axis=1)
print(out)
Output
[7. 9.]
Explanation:
- ord=np.inf row-wise maximum absolute value.
- axis=1 compute norm for each row separately.