Random Seed
Random¶
Numpy has many functions that will allow us to create random sequences of numbers for different reasons. You actually saw some of these in the very beginning of this course for data creation. The first important thing is understanding what a seed is and how it can be used to set the randomness to be repeatable.
Random Seed¶
With computers, there is never true randomness. There is a specialized math function which can find the next random number to compute, but this function can be set in such a way that if you repeat a piece of code you can get the same numbers out. Let’s first see how this works when we do not set the seed. The function uniform in np.random will give back a number between a starting argument and ending argument where every point in between has equal probability. If we run it twice, in both cases we get back totally random numbers. Try it below.
import numpy as np
#Test 1
print(np.random.uniform(0, 1))
#Test 2
print(np.random.uniform(0, 1))
If you set np.random.seed() and pass in an integer, then you can set the seed which will ensure any sort of random number generation you did will yield the same numbers in this program as well as across other programs. For example, these two numbers will be the same as one and other in the code, but also you should on your computer be getting the same numbers.
#Set the seed to 0
np.random.seed(0)
#Test 1
print(np.random.uniform(0, 1))
#Set the seed to 0 again
np.random.seed(0)
#Test 2
print(np.random.uniform(0, 1))
It is a good practice when you need an experiment to be random but repeatable to use a seed. This way whoever uses it later won't see totally different things because of different random numbers.
Multiple Random Numbers¶
All the random functions for numpy are not just limited to single random values, you can get back random numbers in any sort of shape by adding on another argument for either the length or shape of the random numbers. Let's go back to the uniform random function. What if we wanted to see 10 numbers between 0 and 5? We would need to set the second argument to 5, and then we can add a third argument of 10 for the sample number!
#Set the seed to 0
np.random.seed(0)
#Sample 10 random numbers between 0-5
print(np.random.uniform(0, 5, 10))
You can also pass in a shape as a tuple to get back that shape in terms of samples. Notice that with seed set before we are actually getting the same numbers. This data is the same as taking the original data and reshaping it to be 5x2.
#Set the seed to 0
np.random.seed(0)
#Sample 10 random numbers between 0-5 in the shape of 5x2
print(np.random.uniform(0, 5, (5,2)))