What is use of numpy.random.seed()


When we write np.random.seed(any_number), and every time we call random function the result will be same. The random function will output a set of numbers which are unique to the argument any_number.

You can set any number to any_number as see(0) or seed(2) . See the Python code below :

>>> import numpy as np
>>> np.random.seed(0);np.random.rand(3)
array([ 0.5488135 , 0.71518937, 0.60276338])
>>> np.random.seed(0);np.random.rand(3)
array([ 0.5488135 , 0.71518937, 0.60276338])
# You may set any number to seed
>>> np.random.seed(2);np.random.rand(3)
array([ 0.4359949 , 0.02592623, 0.54966248])
>>> np.random.seed(2);np.random.rand(3)
array([ 0.4359949 , 0.02592623, 0.54966248])

If random seed is not reset, different number will come each time.

>>> np.random.rand(3)
array([ 0.43532239, 0.4203678 , 0.33033482])
>>> np.random.rand(3)
array([ 0.20464863, 0.61927097, 0.29965467])

Where to use np.random.seed():

To debug a code that uses random number, we should set the seed before each run so that each time code does same thing.
In artificial neural network, while training neural network from scratch, we randomly initialize the weights. The model is trained on these weights. After training we get trained weights. Every time we start training the neural network, the weights are randomly initialized and trained weights may differ each time because of each time random weights are generated different. So to deal this situation we can use numpy.random.seed(). Using this every time randomly generated weights are same. So after training the trained weights are same every time.

Where not to use np.random.seed():

In multithreaded programming it is not safe to use numpy.random.seed(), because it is not guaranteed to work if two different threads are being executed at same time. The better way in the multithreaded programming scenario is to use random.seed(). Here random module directly imported as import random.

Previous Post: Different Ways to Load Images in Python from Scratch



Comments