0
0
NumPydata~5 mins

np.linalg.norm() for vector norms in NumPy

Choose your learning style9 modes available
Introduction

We use np.linalg.norm() to find the length or size of a vector. It helps us understand how big or small a vector is in simple terms.

To measure the distance of a point from the origin in space.
To find how far apart two points are by subtracting their coordinates and measuring the vector length.
To check the size of a vector in machine learning, like weights or feature vectors.
To normalize vectors so they have length 1, making comparisons easier.
Syntax
NumPy
np.linalg.norm(x, ord=None, axis=None, keepdims=False)

x is the input vector or array.

ord specifies the type of norm (default is Euclidean norm).

Examples
Calculate the Euclidean length of vector [3, 4], which is 5.
NumPy
import numpy as np
v = np.array([3, 4])
norm = np.linalg.norm(v)
Calculate the 1-norm (sum of absolute values) of the vector.
NumPy
np.linalg.norm([1, -1, 1], ord=1)
Calculate the infinity norm (maximum absolute value) of the vector.
NumPy
np.linalg.norm([2, -3, 6], ord=np.inf)
Sample Program

This program shows how to calculate different norms of the same vector. It prints the vector and its Euclidean, 1-norm, and infinity norm values.

NumPy
import numpy as np

# Define a vector
vector = np.array([3, 4])

# Calculate Euclidean norm (default)
euclidean_norm = np.linalg.norm(vector)

# Calculate 1-norm (sum of absolute values)
one_norm = np.linalg.norm(vector, ord=1)

# Calculate infinity norm (max absolute value)
inf_norm = np.linalg.norm(vector, ord=np.inf)

print(f"Vector: {vector}")
print(f"Euclidean norm (length): {euclidean_norm}")
print(f"1-norm (sum of abs): {one_norm}")
print(f"Infinity norm (max abs): {inf_norm}")
OutputSuccess
Important Notes

The default norm is the Euclidean norm, which is like the straight-line distance.

You can use different ord values to get other types of norms.

Works for vectors and matrices, but here we focus on vectors.

Summary

np.linalg.norm() finds the size or length of a vector.

Default is Euclidean norm, but you can choose others like 1-norm or infinity norm.

Useful for measuring distances and normalizing vectors in data science.