In machine learning, Normalizing is a must. It is a technique in data preprocessing to change the value of the numerical columns in the dataset to a common scale. Its mostly require when the features of the datasets have different ranges. In this entire tutorial, I will show you how to normalize a NumPy array.
Methods to Normalize a Numpy Array
In order to get a complete understanding of this concept execute the steps that I have defined here. I am doing all the work on Pycharm IDE.
Step 1: Import the necessary libraries
The most important step is to import all the required libraries before continuing the execution.
import numpy as np
from sklearn.preprocessing import normalize
import transformations as tr
Step 2: Create a Numpy array
Here for the demonstration purpose, I am creating a random NumPy array. You can get different values of the array in your computer.
array = np.random.rand(50) * 5
Step 3: Use the Methods defined here
Method 1: Using the Numpy Python Library
To use this method you have to divide the NumPy array with the numpy.linalg.norm() method. It returns the norm of the matrix form. You can read more about the Numpy norm.
normalize1 = array / np.linalg.norm(array)
Method 2: Using the sci-kit learn Python Module
The second method to normalize a NumPy array is through the sci-kit python module. Here you have to import normalize object from the sklearn. preprocessing and pass your array as an argument to it. I have already imported it step 1.
normalize2 = normalize(array[:, np.newaxis], axis=0).ravel()
Here np.newaxis is used to increase the dimension of the array. That is if the array is 1D then it will make it to 2D and so on.
And also passing axis = 0 to do all the tasks along rows. The ravel() method returns the contiguous flattened array. You can read more about it on numpy ravel official documentation.
Method 3: Using the Transformation Module
The third method to normalize a NumPy array is using transformations. You can easily transform the NumPy array to the unit vector using the unit_vector() method. Use the code below.
normalize3 = tr.unit_vector(array)
These are the best method to normalize a NumPy array. I will keep adding the new methods I will find. If you have any other methods to normalize a NumPy array then you can contact us to review and add here.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.