Find a matrix or vector norm using NumPy

Find a matrix or vector norm using NumPy

NumPy provides a function called norm in the numpy.linalg module to compute the norm of a vector or matrix. Here's how to compute various norms using NumPy:

1. Vector Norms:

L2 norm (Euclidean norm): This is the default norm, often referred to as the "magnitude" of the vector.

import numpy as np vector = np.array([1, 2, 3]) l2_norm = np.linalg.norm(vector) print(l2_norm) 

L1 norm: This is the sum of the absolute values of the vector.

l1_norm = np.linalg.norm(vector, ord=1) print(l1_norm) 

Infinity norm: This gives the maximum absolute value from the vector.

inf_norm = np.linalg.norm(vector, ord=np.inf) print(inf_norm) 

2. Matrix Norms:

Frobenius norm: This is analogous to the L2 norm for vectors and is the default for matrices.

matrix = np.array([[1, 2], [3, 4]]) fro_norm = np.linalg.norm(matrix) print(fro_norm) 

L1 norm (maximum absolute column sum):

l1_norm = np.linalg.norm(matrix, ord=1) print(l1_norm) 

L infinity norm (maximum absolute row sum):

linf_norm = np.linalg.norm(matrix, ord=np.inf) print(linf_norm) 

The ord parameter in the norm function is used to specify the type of norm you want. For vectors, you can use ord=1 for L1 norm, ord=2 for L2 norm (which is the default), and so on. For matrices, the most common norms are the Frobenius norm (default), L1 norm, and L infinity norm. There are other matrix norms you can compute as well by specifying different values for the ord parameter.


More Tags

android-screen-support higher-order-functions hbase maven-3 python-importlib openid-connect azure-pipelines-build-task ubuntu-12.04 strlen jersey-2.0

More Programming Guides

Other Guides

More Programming Examples