normalize matrix numpy code example

Example 1: how to normalize a 1d numpy array

# Foe 1d array
an_array = np.array([0.1,0.2,0.3,0.4,0.5])

norm = np.linalg.norm(an_array)
normal_array = an_array/norm
print(normal_array)

#[0.2,0.4,0.6,0.8,1] (Should be, I didin't run the code)

Example 2: numpy normalize

def normalize(v):
    norm = np.linalg.norm(v)
    if norm == 0: 
       return v
    return v / norm

Example 3: normalize rows in matrix numpy

def normalize_rows(x: numpy.ndarray):
    """
    function that normalizes each row of the matrix x to have unit length.

    Args:
     ``x``: A numpy matrix of shape (n, m)

    Returns:
     ``x``: The normalized (by row) numpy matrix.
    """
    return x/numpy.linalg.norm(x, ord=2, axis=1, keepdims=True)

Example 4: numpy normalize matrix

import numpy as np
x= np.random.random((3,3))
print("Original Array:")
print(x)
xmax, xmin = x.max(), x.min()
x = (x - xmin)/(xmax - xmin)
print("After normalization:")
print(x)

Tags:

Misc Example