Unit-normalize a NumPy Array: A Practice Guide – NumPy Tutorial

By | August 18, 2022

We often need to unit-normalize a numpy array, which can make the length of this arry be 1. In this tutorial, we will introduce you how to do.

First, we need compute the L2 norm of this numpy array. We will use numpy.linalg.norm() to do it.

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

Then, we will create a numpy function to unit-normalize an array.

For example:

import numpy as np

def unit(x, axis = 0):
    l2_norm = np.linalg.norm(x, keepdims=True, axis= axis) + 1e-12
    x_norm = x / l2_norm

    return x_norm

Then, we can evaluate it.

Unit-normalize a numpy vector

For example:

x = np.random.random((10))
y = unit(x)
print(x)
print(y)

x1 = np.sum(y*y)
print(x1)

Here x is a vector, run this code, we will get:

x = np.random.random((10))
y = unit(x)
print(x)
print(y)

x1 = np.sum(y*y)
print(x1)

Our unit() function work correctly.

Unit-normalize a numpy matrix

For example:

x = np.random.random((10, 10))
y = unit(x, axis = 1)
print(x)
print(y)

x1 = np.sum(np.square(y), axis = 1)
print(x1)

Here x is 10*10 matrix, run this code, we will get:

[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]

The answer is also right.

Leave a Reply