How to Normalize a Numpy Array to a Unit Vector in Python

Avatar

By squashlabs, Last Updated: November 2, 2023

How to Normalize a Numpy Array to a Unit Vector in Python

To normalize a NumPy array to a unit vector in Python, you can use the numpy.linalg module. This module provides functions for linear algebra operations, including normalizing vectors. Here are two possible ways to normalize a NumPy array to a unit vector:

Method 1: Using the l2 norm

The l2 norm, also known as the Euclidean norm, is a measure of the length or magnitude of a vector. To normalize a vector using the l2 norm, you divide each element of the vector by its l2 norm.

Here’s an example of how you can normalize a NumPy array to a unit vector using the l2 norm:

import numpy as np

def normalize_vector_l2(vector):
    norm = np.linalg.norm(vector)
    if norm == 0:
        return vector
    return vector / norm

# Example usage
vector = np.array([1, 2, 3, 4])
normalized_vector = normalize_vector_l2(vector)
print(normalized_vector)

This will output:

[0.18257419 0.36514837 0.54772256 0.73029674]

In this example, we define a function normalize_vector_l2 that takes a vector as input. We calculate the l2 norm of the vector using np.linalg.norm. If the norm is zero, the vector is already a zero vector and we return it as is. Otherwise, we divide each element of the vector by its norm to obtain the normalized vector.

Related Article: How To Exit Python Virtualenv

Method 2: Using the max norm

The max norm, also known as the infinity norm or the supremum norm, is a measure of the maximum absolute value of a vector’s elements. To normalize a vector using the max norm, you divide each element of the vector by its maximum absolute value.

Here’s an example of how you can normalize a NumPy array to a unit vector using the max norm:

import numpy as np

def normalize_vector_max(vector):
    max_abs = np.max(np.abs(vector))
    if max_abs == 0:
        return vector
    return vector / max_abs

# Example usage
vector = np.array([1, -2, 3, -4])
normalized_vector = normalize_vector_max(vector)
print(normalized_vector)

This will output:

[ 0.25 -0.5   0.75 -1.  ]

In this example, we define a function normalize_vector_max that takes a vector as input. We calculate the maximum absolute value of the vector’s elements using np.max(np.abs(vector)). If the maximum absolute value is zero, the vector is already a zero vector and we return it as is. Otherwise, we divide each element of the vector by its maximum absolute value to obtain the normalized vector.

These are two possible methods to normalize a NumPy array to a unit vector in Python. Depending on your specific use case, you can choose the method that best suits your needs. Remember to handle the case where the vector is already a zero vector to avoid division by zero errors.

Related Article: How to Integrate Python with MySQL for Database Queries

More Articles from the Python Tutorial: From Basics to Advanced Concepts series:

16 Amazing Python Libraries You Can Use Now

In this article, we will introduce you to 16 amazing Python libraries that are widely used by top software teams. These libraries are powerful tools that can enhance... read more

Database Query Optimization in Django: Boosting Performance for Your Web Apps

Optimizing database queries in Django is essential for boosting the performance of your web applications. This article explores best practices and strategies for... read more

Converting Integer Scalar Arrays To Scalar Index In Python

Convert integer scalar arrays to scalar index in Python to avoid the 'TypeError: Only integer scalar arrays can be converted to a scalar index with 1D' error. This... read more

How To Convert A Tensor To Numpy Array In Tensorflow

Tensorflow is a powerful framework for building and training machine learning models. In this article, we will guide you on how to convert a tensor to a numpy array... read more

How to Adjust Font Size in a Matplotlib Plot

Adjusting font size in Matplotlib plots is a common requirement when creating visualizations in Python. This article provides two methods for adjusting font size: using... read more

How to Position the Legend Outside the Plot in Matplotlib

Positioning a legend outside the plot in Matplotlib is made easy with Python's Matplotlib library. This guide provides step-by-step instructions on how to achieve this... read more