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

前端 未结 4 1814
没有蜡笔的小新
没有蜡笔的小新 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:23

    This answer complements important details others missed. First, to rephrase the conclusion:

    Original random seeds (set via np.random.seed) cannot be retrieved after generating numbers, but intermediates (current state) can.

    Refer to @vestland's answer; it may, however, mislead: the generated numbers differ not due to inability to map states, but that an incomplete encoding is used: get_state()[1]. The complete representation includes pos = get_state()[2]. To illustrate:

    import numpy as np
    
    state0 = np.random.get_state()
    rand0  = np.random.randint(0, 10, 1)
    state1 = np.random.get_state()
    rand1  = np.random.randint(0, 10, 1)
    
    assert all(s0 == s1 for s0, s1 in zip(state0[1], state1[1]))
    

    We generated a number, yet get_state()[1] remained identical. However:

    np.random.set_state(state0)
    assert np.random.randint(0, 10, 1) == rand0
    

    and likewise for state1 & rand1. Hence, @vestland's numbers differ because when not setting a seed, pos = 623 - whereas if we use np.random.seed, pos = 624. Why the inconvenient discrepancy? No clue.


    In summary on np.random.seed(s):

    • get_state()[1][0] immediately after setting: retrieves s that exactly recreates the state
    • get_state()[1][0] after generating numbers: may or may not retrieve s, but it will not recreate the current state (at get_state())
    • get_state()[1][0] after generating many numbers: will not retrieve s. This is because pos exhausted its representation.
    • get_state() at any point: will exactly recreate that point.

    Lastly, behavior may also differ due to get_state()[3:] (and of course [0]).

提交回复
热议问题