I am a bit confused on what random.seed()
does in Python. For example, why does the below trials do what they do (consistently)?
>>> i
Seed() can be used for later use ---
Example:
>>> import numpy as np
>>> np.random.seed(12)
>>> np.random.rand(4)
array([0.15416284, 0.7400497 , 0.26331502, 0.53373939])
>>>
>>>
>>> np.random.seed(10)
>>> np.random.rand(4)
array([0.77132064, 0.02075195, 0.63364823, 0.74880388])
>>>
>>>
>>> np.random.seed(12) # When you use same seed as before you will get same random output as before
>>> np.random.rand(4)
array([0.15416284, 0.7400497 , 0.26331502, 0.53373939])
>>>
>>>
>>> np.random.seed(10)
>>> np.random.rand(4)
array([0.77132064, 0.02075195, 0.63364823, 0.74880388])
>>>
Set the seed(x)
before generating a set of random numbers and use the same seed to generate the same set of random numbers. Useful in case of reproducing the issues.
>>> from random import *
>>> seed(20)
>>> randint(1,100)
93
>>> randint(1,100)
88
>>> randint(1,100)
99
>>> seed(20)
>>> randint(1,100)
93
>>> randint(1,100)
88
>>> randint(1,100)
99
>>>
All the other answers don't seem to explain the use of random.seed(). Here is a simple example (source):
import random
random.seed( 3 )
print "Random number with seed 3 : ", random.random() #will generate a random number
#if you want to use the same random number once again in your program
random.seed( 3 )
random.random() # same random number as before
In this case, random is actually pseudo-random. Given a seed, it will generate numbers with an equal distribution. But with the same seed, it will generate the same number sequence every time. If you want it to change, you'll have to change your seed. A lot of people like to generate a seed based on the current time or something.
Here is a small test that demonstrates that feeding the seed()
method with the same argument will cause the same pseudo-random result:
# testing random.seed()
import random
def equalityCheck(l):
state=None
x=l[0]
for i in l:
if i!=x:
state=False
break
else:
state=True
return state
l=[]
for i in range(1000):
random.seed(10)
l.append(random.random())
print "All elements in l are equal?",equalityCheck(l)
Here is my understanding. Every time we set a seed value, a "label" or " reference" is generated. The next random.function call is attached to this "label", so next time you call the same seed value and random.function, it will give you the same result.
np.random.seed( 3 )
print(np.random.randn()) # output: 1.7886284734303186
np.random.seed( 3 )
print(np.random.rand()) # different function. output: 0.5507979025745755
np.random.seed( 5 )
print(np.random.rand()) # different seed value. output: 0.22199317108973948