NumPy.Random.Seed(101) Explained
While working with Machine Learning or Deep Learning, we all must have come across the buzz word “NumPy”. So, What is NumPy?
According to SciPy.org, NumPy is the fundamental package for scientific computing in Python. It is a Python library that provides a multidimensional array object, various derived objects (such as masked arrays and matrices), and an assortment of routines for fast operations on arrays, including mathematical, logical, shape manipulation, sorting, selecting, I/O etc.
In machine learning and data science, at times we have to work with randomly generated data. In this blog, I will discuss about what NumPy.random.seed( which is also called np.random.seed or numpy.random.seed) does. So, let’s get started.
In order to understand this particular function, firstly, we are supposed to know about pseudo-random numbers.
What is Pseudo-Random Number?
As the name suggests, pseudo-random number is pretty much a number which appears to be random but it isn’t. Confusing, right?
Well. That’s what it is. The prefix “pseudo” is used to differentiate it from a “truly” random number.
A proper definition would be that pseudo-random numbers are computer generated numbers that look like they are random,but are actually pre-determined.
How is it even important ?
We all know, computers are designed to be deterministic. They are designed in such a way that some meaningful or logical results will be given to us when a process is run in a computer. They can never provide us with random results.
If the input is the same, then the output will be the same.
THAT’S HOW COMPUTERS WORK.
Then, how can we generate random results using a computer?
Pseudo-random numbers comes to our rescue. Computer scientists have created a set of algorithms for creating pseudo random numbers, called “pseudo-random number generators.”
These algorithms can be executed on a computer.
As such, they are completely deterministic. However, the numbers that they produce have properties that approximate the properties of random numbers.
Everything you need to know about Numpy.random.seed()….
Now, that you know about pseudo-random numbers, I think you are ready to work around Numpy.random.seed(). As discussed previously, pseudo-random number generators help us in coping with the restriction of computers being deterministic. One such way is to use the NumPy library.
np.random.seed() is used to generate random numbers. The np.random.seed function provides an input for the pseudo-random number generator in Python. It allows us to provide a “seed” value to NumPy’s random number generator.
Syntax:
The syntax mostly used is :
Here, “np” stands for NumPy.
“random” is the function name.
The value inside the seed function is the input value that we will use to seed the pseudo random generator.
One thing which we should keep in mind while using this syntax is that “np” stands for NumPy and we are using the abbreviation of NumPy. But, in order to do that , we need to import NumPy with the code “import numpy as np”.
Are they really generating random numbers?
Here, I have discussed that np.random.seed() is used to generate random numbers in computer which in itself is deterministic. But pseudo-random generators are purely deterministic. They are operated by an algorithm.
Now, what does this algorithm depends upon? The seed value.
What this means is that if we provide the same seed, we will get the same output. And if the seed value is changes, the output will be changed.
Examples:
- To run the function properly, first we need to abbreviate the name of “NumPy”.
2. Here, we’re going to use NumPy to generate a random integer. To do this, we’re going to use the NumPy random randint function (AKA, np.random.randint).
If we run the code once again, we will get the same result. Go ahead and check it now.
So, what exactly should we put as my random seed?
Basically, it doesn’t matter.
We can use numpy.random.seed(101) , or numpy.random.seed(4) , or any other number.
The only important point we need to understand is that using different seeds will cause NumPy to produce different pseudo-random numbers. The output of a numpy.random function will depend on the seed that you use.
How does np.random.seed( ) helps in Machine Learning or Deep Learning ?
Machine Learning and Deep Learning requires splitting of training and test datasets.
Performing simple tasks like splitting datasets into training and test sets requires random sampling. In turn, random sampling almost always requires pseudo-random numbers.
numpy.random.seed() Функция в NumPy

Это руководство объяснит функцию numpy.random.seed() в NumPy.
numpy.random.seed() Функция
Функция numpy.random.seed() используется для установки начального числа для алгоритма генератора псевдослучайных чисел в Python. Алгоритм генератора псевдослучайных чисел выполняет некоторые предопределенные операции с начальным числом и выдает псевдослучайное число на выходе. Начальное число выступает в качестве отправной точки для алгоритма. Псевдослучайное число — это число, которое кажется случайным, но на самом деле это не так. Фактически, компьютеры неспособны генерировать действительно случайные числа, потому что компьютеры детерминированы и последовательно следуют заданному набору инструкций. Идея заключается в том, что мы всегда будем получать один и тот же набор случайных чисел для одного и того же начального числа на любой машине.
В приведенном выше коде мы устанавливаем случайное начальное число NumPy равным 0 и генерируем последовательность из пяти псевдослучайных чисел на основе этого начального числа. Затем мы сбрасываем начальное число в 0 и снова генерируем последовательность из пяти псевдослучайных чисел на основе этого начального числа. Обратите внимание, что оба раза мы получаем одну и ту же последовательность значений. Оба раза случайные числа генерируются путем применения одних и тех же операций к одним и тем же начальным числам. Этот предетерминированный тип генерации случайных чисел полезен, когда мы хотим сгенерировать одну и ту же последовательность случайных чисел на разных машинах.
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
random.seed(): What does it do?
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 couldn’t find good documentation on this.
![]()
12 Answers 12
Pseudo-random number generators work by performing some operation on a value. Generally this value is the previous number generated by the generator. However, the first time you use the generator, there is no previous value.
Seeding a pseudo-random number generator gives it its first «previous» value. Each seed value will correspond to a sequence of generated values for a given random number generator. That is, if you provide the same seed twice, you get the same sequence of numbers twice.
Generally, you want to seed your random number generator with some value that will change each execution of the program. For instance, the current time is a frequently-used seed. The reason why this doesn’t happen automatically is so that if you want, you can provide a specific seed to get a known sequence of numbers.
All the other answers don’t seem to explain the use of random.seed(). Here is a simple example (source):
![]()
Let’s say ‘random.seed’ gives a value to random value generator (‘random.randint()’) which generates these values on the basis of this seed. One of the must properties of random numbers is that they should be reproducible. When you put same seed, you get the same pattern of random numbers. This way you are generating them right from the start. You give a different seed- it starts with a different initial (above 3).
Given a seed, it will generate random numbers between 1 and 10 one after another. So you assume one set of numbers for one seed value.
![]()
A random number is generated by some operation on previous value.
If there is no previous value then the current time is taken as previous value automatically. We can provide this previous value by own using random.seed(x) where x could be any number or string etc.
Hence random.random() is not actually perfect random number, it could be predicted via random.seed(x) .
Hence, generating a random number is not actually random, because it runs on algorithms. Algorithms always give the same output based on the same input. This means, it depends on the value of the seed. So, in order to make it more random, time is automatically assigned to seed() .
![]()
![]()
Execute the above program multiple times.
1st attempt: prints 5 random integers in the range of 1 — 100
2nd attempt: prints same 5 random numbers appeared in the above execution.
3rd attempt: same
Explanation: Every time we are running the above program we are setting seed to 10, then random generator takes this as a reference variable. And then by doing some predefined formula, it generates a random number.
Hence setting seed to 10 in the next execution again sets reference number to 10 and again the same behavior starts.
As soon as we reset the seed value it gives the same plants.
Note: Change the seed value and run the program, you’ll see a different random sequence than the previous one.
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.
![]()
Imho, it is used to generate same random course result when you use random.seed(samedigit) again.
![]()
![]()
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.
![]()
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.
random.seed(a, version) in python is used to initialize the pseudo-random number generator (PRNG).
PRNG is algorithm that generates sequence of numbers approximating the properties of random numbers. These random numbers can be reproduced using the seed value. So, if you provide seed value, PRNG starts from an arbitrary starting state using a seed.
Argument a is the seed value. If the a value is None , then by default, current system time is used.
and version is An integer specifying how to convert the a parameter into a integer. Default value is 2.
If you want the same random number to be reproduced then provide the same seed again
If you don’t provide the seed, then it generate different number and not 1 as before
If you provide different seed than before, then it will give you a different random number
So, in summary, if you want the same random number to be reproduced, provide the seed. Specifically, the same seed.
What is the Seed() Function in NumPy?
The seed() function in NumPy is used to set the random seed of the NumPy pseudo-random number generator. It offers a crucial input that NumPy needs to produce pseudo-random integers for random processes and other applications.
By default, the random number generator uses the current system time. We need to call the seed() function before calling any other random module function. To get a better understanding of the seed() function, let's understand what pseudo-random numbers are in Numpy.
Introduction to Pseudo-Random Numbers
Pseudo-Random Numbers Appear to Be Random
As the name suggests, pseudo-random numbers are a set of partially random numbers. They appear to be random but are not random. According to Wikipedia, a pseudo-random number is a computer-generated random number. It cannot be random because it was generated by a computer; instead, it is predetermined. To generate a seemingly random number, various computations are made. Therefore, we refer to it as partially random. Let's examine why NumPy requires pseudo-random numbers.
Pseudo-Random Numbers are Generated by Algorithms When we work on software, testing it is an integral part of its development, as we need the software to be robust and handle any errors that happen. The problem with that is what happens when we use computers/applications to work with random processes. Since computers are deterministic (not random), they will follow some instructions and produce an output. If we give a computer the same inputs, it will provide the same outputs over and over again. Hence, we will never be able to generate random numbers. To overcome this problem, we create pseudo-random numbers , which in turn are created using algorithms. The essence of computers (being deterministic) can never be changed, but pseudo-random numbers produce numbers that approximate the random numbers.
Pseudo-Random Numbers Can Be Re-Created Exactly Because of np random seed values, we can re-create random numbers according to our liking. When we set an np random seed value, the values returned by the random() function will always be constant. As we set an np random seed value, the algorithm that generates random values takes in the np random seed value. This ensures that the values remain constant throughout.
Even if we run the code a lot of times, the random value returned would always be the same.
Output
Why We Need Pseudo-Random Numbers
As computers are deterministic, they cannot generate random values intrinsically, as to generate random values, we need the system to be random. With the help of pseudo-random numbers, we can generate random values as the np random seed value goes into an algorithm.
This algorithm generates a random number (approximately a random number), which lies between 0 and 1.
Syntax Expounded
The syntax for seed() function in NumPy is:
Its parameters are:
- val: This is the input seed value to generate repeated random numbers. It's a mandatory parameter.
NumPy Random Seed Functions
Random Function As discussed earlier in this article, the pseudo-random numbers help us to get the same set of random numbers every time we call the seed() function. This is possible because we set the np random seed value as a specific number, and NumPy then processes that number and gives us the random numbers.
Output
As we can see, a float value is generated. It's between 0 and 1. If we run the code again, we will see that the same value will be returned. This happens because we set our np random seed as 0. If we change the np random seed value, then the random numbers will also be changed.
Random Integer Function
To generate random integers in NumPy, we use the numpy.random.randint function.
Output
We set the np random seed value as 4 in this case. The parameters low and high help us to set the limits of our random values, and size helps us to select the number of elements that we want.
Random Shuffle Function
We'll change the sequence of an array using the shuffle function in NumPy.
Output
Random Standard Exponential Function
The standard exponential function helps us to draw samples from the standard exponential distribution. It takes in two parameters; size (The shape of the output) and out (The samples)
Output
As we can see, a set of random samples are returned when we use the standard_exponential() function.
Random Triangular Function
The triangular function in NumPy helps us to generate a random value between two data points, and it also has a bias parameter, which can be used to create a random value near any of the two data points.
Output
As we can see, we've got 19 as our generated random number. This happened because we set our bias (mode) as 20. Hence we got a number closer to our mode (20).
Use of NumPy Random Seed
Some of the applications of the Random Seed function in NumPy are:
- NumPy Random Seed function is used in creating encryption keys in computer and network security. This is done because of pseudo-generated random numbers that we talked about earlier in this article. These keys are secret keys and are important to protect against the misuse of data over the internet.
- In the software lifecycle, an integral part of it is software testing . The random Seed function helps us to make codes optimized where we use random numbers for testing. When we use random numbers and values to test our data, it makes our software robust, as it understands and comprehends different data and use cases.
Conclusion
In this article, we discovered the seed() function and how we use it to generate random numbers in NumPy. We understood how computers, being completely deterministic, end up generating random numbers with the help of pseudo-random numbers.