How can I retrieve the current seed of NumPy's random number generator?

前端 未结 4 1831
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 05:21

The following imports NumPy and sets the seed.

import numpy as np
np.random.seed(42)

However, I\'m not interested in setting the seed but m

4条回答
  •  感动是毒
    2020-12-13 06:15

    The short answer is that you simply can't (at least not in general).

    The Mersenne Twister RNG used by numpy has 219937-1 possible internal states, whereas a single 64 bit integer has only 264 possible values. It's therefore impossible to map every RNG state to a unique integer seed.

    You can get and set the internal state of the RNG directly using np.random.get_state and np.random.set_state. The output of get_state is a tuple whose second element is a (624,) array of 32 bit integers. This array has more than enough bits to represent every possible internal state of the RNG (2624 * 32 > 219937-1).

    The tuple returned by get_state can be used much like a seed in order to create reproducible sequences of random numbers. For example:

    import numpy as np
    
    # randomly initialize the RNG from some platform-dependent source of entropy
    np.random.seed(None)
    
    # get the initial state of the RNG
    st0 = np.random.get_state()
    
    # draw some random numbers
    print(np.random.randint(0, 100, 10))
    # [ 8 76 76 33 77 26  3  1 68 21]
    
    # set the state back to what it was originally
    np.random.set_state(st0)
    
    # draw again
    print(np.random.randint(0, 100, 10))
    # [ 8 76 76 33 77 26  3  1 68 21]
    

提交回复
热议问题