[toc]
Introduction
random is an in-built module in Python which generates pseudo-random numbers. Now, the random data generated by this module is not completely random. Instead it is pseudo-random, as mentioned previously.
Note: A “True Random Number” can be generated by a TRNG (true random number generator) while a “pseudo-random number” is generated by a PRNG (pseudorandom number generator).
⚠️ TRNG is outside the scope of the discussion in this article.
So, what is a PRNG (pseudorandom number generator)?
PRNG initially generates a random number known as seed. Then an algorithm is used to generate a pseudo-random sequence of bits based on it. In simple words, it is an algorithm that generates seemingly random numbers; however, these numbers are still reproducible.
The random module has a set of methods that help us to generate random elements (numbers). In this tutorial, we will be focusing on the seed() method of the random module.
Random seed() Method in Python
The random number generator needs a starting point, i.e., it needs a seed value to start generating a sequence of random numbers. Thus, it is the
seed()
method that is used to initialize the random number generator.
By default, current system time is used by the random number generator as a start-point. To customize the start number of the random number generator, you must use the seed() method.
Syntax:
Example:
import random random.seed(10) print(random.random())
Output:
0.5714025946899135
How To Generate The Same Random Integer Every Time?
If you set the same seed value before calling any random module function, you will get the same number repeatedly.
Example:
import random for i in range(3): # setting seed value to 10 random.seed(10) print("i[{}]={}".format(i,random.randint(12, 30)))
Output:
i[0]=30 i[1]=30 i[2]=30
Explanation: In the above output, we got the same number as the output because the same seed was set before using randint
every time.
random.seed() and random.choice()
➥ choice()
is a method of the random
module that selects a random element from a specified sequence (string
, range
, list
, tuple
).
You can use a custom seed value to receive the same choice value again and again. Let’s have a look at the following example.
Example
import random x = "PNEUMONOULTRAMICROSCOPICSILICOVOLCANOCONIOSIS" print("Output Without Setting A Seed: ") for i in range(3): print(random.choice(x)) print("Output After Setting A Seed: ") for i in range(3): random.seed(5) print(random.choice(x))
Output:
Output Without Setting A Seed: R C N Output After Setting A Seed: N N N
What is NumPy Random Seed?
The np.random.seed
function provides a seed value, i.e., a base input value to NumPy's pseudo-random number generator in Python.
Syntax:
Example 1:
import numpy as np for i in range(3): np.random.seed(101) print('i[{}]={}'.format(i, np.random.randint(low=1, high=10, size=10)))
Output:
i[0]=[2 7 8 9 5 9 6 1 6 9] i[1]=[2 7 8 9 5 9 6 1 6 9] i[2]=[2 7 8 9 5 9 6 1 6 9]
Here’s another example for you to visualize the effects of numpy.random.seed
.
Example 2:
import numpy as np print("GENERATE SAME RANDOM NUMBER WITH NUMPY.RANDOM.RANDOM") for i in range(2): np.random.seed(101) print('i[{}]={}'.format(i, np.random.random())) print("\nSELECT A RANDOM SAMPLE FROM AN INPUT ARRAY") for i in range(2): np.random.seed(0) print('i[{}]={}'.format(i, np.random.choice(a=[1, 2, 3, 4, 5, 6], size=5)))
Output:
GENERATE SAME RANDOM NUMBER WITH NUMPY.RANDOM.RANDOM i[0]=0.5163986277024462 i[1]=0.5163986277024462 SELECT A RANDOM SAMPLE FROM AN INPUT ARRAY i[0]=[5 6 1 4 4] i[1]=[5 6 1 4 4]
Application of numpy.random.seed
- Machine Learning
- Splitting datasets into test set and training sets require random sampling. And random sampling, in turn, requires pseudo-random random numbers. Therefore if you play around with ML models, then Numpy’s random.seed() is almost a certainty!
- Deep Learning
- Just like ML problems, Deep Learning problems also require splitting the dataset into test set and training set with the help of pseudo-random numbers.
- Random Sampling
- Probability and Statistics
Frequently Asked Questions
Should I Use numpy.random.seed or random.seed?
- The answer to this question depends on whether you are using Numpy’s random generator in your code or the one in the normal random module.
- The random generators in
random
andnumpy.random
have completely different/separate internal states. This meansrandom.seed()
won’t affect the random sequences generated bynumpy.random.randn()
, etc. Similarly,numpy.random.seed()
will not affect the random sequences generated byrandom.random()
, etc. - In case you have used both
numpy.random
andrandom
in your code, then you have to separately set seeds for both.
What Number Should I Use in random.seed?
It does not matter what number you use within the numpy.random.seed()
method. Using different seeds will only cause Random
module (or Numpy in case of numpy.random.seed
) to generate different pseudo-random numbers. Thus, the output of a random function depends on the value of random.seed()
but the choice of the seed value is arbitrary.
Example:
import random print("SEED VALUE = 10") for i in range(3): # setting seed value to 10 random.seed(10) print("i[{}]={}".format(i,random.randint(12, 30))) print("SEED VALUE = 15") for i in range(3): # setting seed value to 15 random.seed(15) print("i[{}]={}".format(i,random.randint(12, 30)))
Output:
SEED VALUE = 10 i[0]=30 i[1]=30 i[2]=30 SEED VALUE = 15 i[0]=18 i[1]=18 i[2]=18
How Do I Get random.seed() to Use System Time?
Since time keeps changing, hence using it as a seed value to generate random numbers will ensure that the seed value keeps changing and you will get a different random sequence/number upon every execution.
Example:
import random import time random.seed(int(time.time())) c = 'abcdefghijklmnopqrstuvwxyz0123456789%^*(-_=+)' password = ''.join([c[random.randint(0, len(c) - 1)] for i in range(10)]) print("New Password: ", password)
Output:
New Password: za2arj+hjz
Conclusion
I hope this article helped you to understand the importance and uses of random.seed
in Python. Please subscribe and stay tuned for more interesting concepts. Happy coding!?
- Do you want to master the most popular Python IDE fast?
- This course will take you from beginner to expert in PyCharm in ~90 minutes.
- For any software developer, it is crucial to master the IDE well, to write, test and debug high-quality code with little effort.
Join the PyCharm Masterclass now, and master PyCharm by tomorrow!