How to normalize array in Numpy?

Let’s learn about how to normalize an array in Numpy Python library. We will use linalg norm function for that purpose.

Numpy normalize array

Steps to normalize an array in Numpy

To normalize an array in Numpy you need to divide your array by np.linalg.norm of your array. Just take a look at below example or normalization.

import numpy as np

my_array = np.array([[1, 3, 5],
                     [7, 9, 11],
                     [13, 15, 17]])

print(f"My array: \n{my_array}")

my_normalized_array = my_array / np.linalg.norm(my_array)
print(f"My normalized array: \n{my_normalized_array}")

Python returned normalized array as an output.

See also  How to convert Numpy array to Python list?

Numpy normalize array

In this code, we start with the my_array and use the np.linalg.norm function to calculate the L2 norm of the array. We then divide each element in my_array by this L2 norm to obtain the normalized array, my_normalized_array.

Running this code results in a normalized array where the values are scaled to have a magnitude of 1.0.

See also  How to save array as csv file with Numpy?

By normalizing your data, you can ensure that all features have the same scale, which is often a crucial step in various machine learning algorithms and data analysis tasks. NumPy’s np.linalg.norm function makes this process efficient and straightforward.