How to cancel the effect of numpy seed()?

孤街浪徒 提交于 2019-12-22 09:41:33

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/49966770/how-to-cancel-the-effect-of-numpy-seed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!