Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel the effect of numpy seed()?

I would like to use np.random.seed() in the first part of my program and cancel it in the second part. Again,

  • in the first part of my python file, I want the same random numbers to be generated at each execution
  • in the second part , I want different random numbers to be generated at each execution
like image 606
u2gilles Avatar asked Apr 22 '18 14:04

u2gilles


People also ask

What does NumPy seed do?

The numpy random seed is a numerical value that generates a new set or repeats pseudo-random numbers. The value in the numpy random seed saves the state of randomness. If we call the seed function using value 1 multiple times, the computer displays the same random numbers.

What does seed () do in Python?

The seed() method is used to initialize the random number generator. The random number generator needs a number to start with (a seed value), to be able to generate a random number. By default the random number generator uses the current system time.

What is NP random seed 101?

NumPy. random. seed(101) sets the random seed to '101'. The pseudo-random numbers generated with seed value '101' will start from the same point every time.

Why are seeds random?

Seed function is used to save the state of a random function, so that it can generate same random numbers on multiple executions of the code on the same machine or on different machines (for a specific seed value). The seed value is the previous value number generated by the generator.


1 Answers

In the first part initialize the seed with a constant, e.g. 0:

numpy.random.seed(0)

In the second part initialize the seed with time:

import time
t = 1000 * time.time() # current time in milliseconds
np.random.seed(int(t) % 2**32)

(the seed must be between 0 and and 2**32 - 1)

Note: you obtain a similar effect by calling np.random.seed() with no arguments, i.e. a new (pseudo)-unpredictable sequence.

Each time you initialize the seed with the same constant, you get the same sequence of numbers:

>>> np.random.seed(0)
>>> [np.random.randint(10) for _ in range(10)]
[5, 0, 3, 3, 7, 9, 3, 5, 2, 4]
>>> [np.random.randint(10) for _ in range(10)]
[7, 6, 8, 8, 1, 6, 7, 7, 8, 1]
>>> np.random.seed(0)
>>> [np.random.randint(10) for _ in range(10)]
[5, 0, 3, 3, 7, 9, 3, 5, 2, 4]

Hence initalizing with the current number of milliseconds gives you some pseudo-random sequence.

like image 100
fferri Avatar answered Oct 11 '22 16:10

fferri