How to Use np.linalg.norm in NumPy for Vector and Matrix Norms
Use
np.linalg.norm to calculate the length (norm) of vectors or matrices in NumPy. You can specify the type of norm with the ord parameter, such as Euclidean norm (default) or other norms like L1 or infinity norm.Syntax
The basic syntax of np.linalg.norm is:
np.linalg.norm(x, ord=None, axis=None, keepdims=False)
Where:
x: Input array (vector or matrix).ord: Order of the norm (default is 2 for Euclidean norm for vectors, Frobenius norm for matrices).axis: Axis or axes along which to compute the norm.keepdims: Whether to keep the dimensions of the result.
python
np.linalg.norm(x, ord=None, axis=None, keepdims=False)
Example
This example shows how to calculate the Euclidean norm of a vector and the Frobenius norm of a matrix using np.linalg.norm.
python
import numpy as np # Vector example vector = np.array([3, 4]) vector_norm = np.linalg.norm(vector) # Default ord=2 (Euclidean norm) # Matrix example matrix = np.array([[1, 2], [3, 4]]) matrix_norm = np.linalg.norm(matrix) # Frobenius norm by default print(f"Vector norm (Euclidean): {vector_norm}") print(f"Matrix norm (Frobenius): {matrix_norm}")
Output
Vector norm (Euclidean): 5.0
Matrix norm (Frobenius): 5.477225575051661
Common Pitfalls
Common mistakes when using np.linalg.norm include:
- Not specifying
ordwhen a different norm is needed (default is Euclidean norm for vectors). - Confusing vector norms with matrix norms; the default for matrices is the Frobenius norm.
- Not using the
axisparameter correctly when working with multi-dimensional arrays.
Example of a wrong and right way to calculate the L1 norm of each row in a matrix:
python
import numpy as np matrix = np.array([[1, -2, 3], [-4, 5, -6]]) # Wrong: forgetting axis, returns a single norm for whole matrix wrong_norm = np.linalg.norm(matrix, ord=1) # Right: specify axis=1 to get L1 norm of each row right_norm = np.linalg.norm(matrix, ord=1, axis=1) print(f"Wrong L1 norm (whole matrix): {wrong_norm}") print(f"Right L1 norm (each row): {right_norm}")
Output
Wrong L1 norm (whole matrix): 15.0
Right L1 norm (each row): [6. 15.]
Quick Reference
Summary of common ord values for np.linalg.norm:
| ord value | Norm type | Description |
|---|---|---|
| None or 2 | Euclidean norm | Default for vectors; Frobenius norm for matrices |
| 1 | L1 norm | Sum of absolute values |
| np.inf | Infinity norm | Maximum absolute value |
| -np.inf | Negative infinity norm | Minimum absolute value |
| 'fro' | Frobenius norm | Square root of sum of squares for matrices |
Key Takeaways
Use np.linalg.norm to calculate vector or matrix norms easily in NumPy.
The default norm is Euclidean (L2) for vectors and Frobenius for matrices.
Specify the ord parameter to calculate different types of norms like L1 or infinity norm.
Use the axis parameter to compute norms along specific dimensions in arrays.
Common mistakes include forgetting axis or using the wrong ord value for your data.