Understand numpy.linalg.norm() with Examples: Calculate Matrix or Vector Norm – NumPy Tutorial

By | August 18, 2022

In this tutorial, we will introduce how to use numpy.linalg.norm() in python. It can allow us to calculate matrix or vector norm easily.

numpy.linalg.norm()

It is defined as:

linalg.norm(x, ord=None, axis=None, keepdims=False)[source]

It will calculate matrix or vector norm of x array.

As to ord parameter, it can be:

ord norm for matrices norm for vectors
None Frobenius norm 2-norm
‘fro’ Frobenius norm
‘nuc’ nuclear norm
inf max(sum(abs(x), axis=1)) max(abs(x))
-inf min(sum(abs(x), axis=1)) min(abs(x))
0 sum(x != 0)
1 max(sum(abs(x), axis=0)) as below
-1 min(sum(abs(x), axis=0)) as below
2 2-norm (largest sing. value) as below
-2 smallest singular value as below
other sum(abs(x)**ord)**(1./ord)

In order to understand Frobenius Norm, you can read:

Understand Frobenius Norm: A Beginner Guide – Deep Learning Tutorial

How to use numpy.linalg.norm()?

Here we will use some examples to show you how to use this function.

Example 1:

import numpy as np

x = np.random.random((2,3))
print(x)

y = np.linalg.norm(x, ord = np.inf)
print(y)

Here x is a matrix and ord = np.inf, which mean we will get max(sum(abs(x), axis=1))

Run this code, we will get:

[[0.01452971 0.3832144  0.17549253]
 [0.64189317 0.93303077 0.98318939]]
2.5581133288856686

Example 2:

x2 = np.random.random((3,))
print(x2)
y = np.linalg.norm(x2, ord = np.inf)
print(y)

Here x2 is the vector and ord = np.inf, which means we will calculate max(abs(x))

Run this code, we will get:

[0.28094103 0.703004   0.13909213]
0.7030039972017319

Example 3: calculate L2 norm

in order to calculate frobenius norm or l2-norm, we can set ord = None.

For example:

import numpy as np

x = np.random.random((2,3))
print(x)

y = np.linalg.norm(x)
print(y)

y = np.linalg.norm(x, axis= 1)
print(y)

Run this code, we will see:

[[0.71908539 0.46834462 0.86676793]
 [0.77600852 0.12518566 0.4155249 ]]
1.5093835600025909
[1.2197201  0.88911282]

Leave a Reply