Norm#
There is a numpy.linalg.norm
function which allows you to get norms for arrays.
import numpy as np
Basic Example#
Here is an example that calculates the norm for an arbitrary array.
arr = np.array([1, 2, 3])
np.linalg.norm(arr)
3.7416573867739413
axis
argument#
If you pass a matrix, it will also calculate the norm for all numbers as a single array.
arr = np.array([
[1, 2, 3],
[4, 2, 1]
])
np.linalg.norm(arr)
5.916079783099616
By specifying axis
you can choose whether to calculate norms by columns or by rows.
The following example shows that by specifying
axis=0
you can compute the norm for each column of the matrix;axis=1
you can compute the norm for each row of the matrix.
arr = np.array([
[1, 2, 3],
[4, 2, 1]
])
print(np.linalg.norm(arr, axis=0))
print(np.linalg.norm(arr, axis=1))
[4.12310563 2.82842712 3.16227766]
[3.74165739 4.58257569]
keepdims
argument#
The keepdims
argument allows you to retain the reduced dimensions with size one when calculating the norm. This is useful when you want the output array to have the same number of dimensions as the input array, even after the reduction.
If you normalise by columns - you get a row of norms. If you normalise by rows - you’ll get a column of rows. If you normalise the whole matrix, you’ll just have one number wrapped in the same number of layers as the original array.
arr = np.array([
[1, 2, 3],
[4, 2, 1]
])
print(np.linalg.norm(arr, keepdims=True))
print(np.linalg.norm(arr, axis=0, keepdims=True))
print(np.linalg.norm(arr, axis=1, keepdims=True))
[[5.91607978]]
[[4.12310563 2.82842712 3.16227766]]
[[3.74165739]
[4.58257569]]