How to Use numpy.random.seed()

numpy.random.seed() provides a seed, which acts as a starting point number generator algorithm. For the same seed, we will always get the same set of random numbers on any machine.

If you prefer to have different sets of random numbers every time you run the code, do not set the seed. In contrast, if you want to reproduce the same results everytime you run number generator algorithm, you want to set the seed.

The following shows two examples comparing not using numpy.random.seed() (Example 1) and using numpy.random.seed() (Example 2).

Example 1: Not Using numpy.random.seed()

The following code does not use numpy.random.seed(). As we can see, the outputs of two times are not the same.

# run it first time
import numpy as np
np.random.rand(3)

Output:

array([0.48667505, 0.91232046, 0.573781  ])
# run it second time
import numpy as np
np.random.rand(3)

Output:

array([0.59898269, 0.89518967, 0.2414096 ])

Example 2: Using numpy.random.seed()

The following code use numpy.random.seed(). As we can see, the outputs of two times are the same.

import numpy as np
# run it first time
np.random.seed(0)
np.random.rand(3)

Output:

array([0.5488135 , 0.71518937, 0.60276338])
# run it second time
np.random.seed(0)
np.random.rand(3)

Output:

array([0.5488135 , 0.71518937, 0.60276338])

Example 3: use numpy.random.seed() to generate a normal distribution data

We can also use numpy.random.seed() to generate a normal distribution data.

import numpy as np
# set sead
np.random.seed(0)
# mean and standard deviation
mu, sigma = 5, 1 
# generate normal distribution data
y = np.random.normal(mu, sigma, 5)
print(y)

Output:

[6.76405235 5.40015721 5.97873798 7.2408932  6.86755799]

Further Reading