There is no direct method to obtain the seed of a NumPy Generator
. Here are a few alternative approaches to achieve this:
__getstate__()
and __setstate__()
# Save the state of the old Generator
s_old = rng.__getstate__()
# Create a new Generator with any seed
rng = np.random.default_rng(seed=123123)
# Update the new Generator's state with the old seed
rng.__setstate__(s_old)
# Verify if the seed was successfully restored
s_recovered = rng.__getstate__()
print(s_old == s_recovered)
Method 2: Utilizing bit_generator.state
# Get the state of the old Generator
s_old = rng.bit_generator.state
# Create a new Generator with any seed
rng = np.random.default_rng(seed=123123)
# Update the new Generator's state with the old seed
rng.bit_generator.state = s_old
# Verify if the seed was successfully restored
s_recovered = rng.bit_generator.state
print(s_old == s_recovered)
Method 3: Generating a Random Number and Logging It
# Generate a random number using the old Generator
random_number = rng.random()
# Log the random number for future reference
# Create a new Generator with any seed
rng = np.random.default_rng(seed=None)
# Manually set the seed of the new Generator using the logged random number
rng.seed(random_number)
# Verify if the seed was successfully restored by generating the same random number
random_number_new = rng.random()
print(random_number == random_number_new)
Note:
* Using the above methods, you can effectively replicate the randomness generated by the original Generator
in a new instance.
* The seed obtained may not be the exact numerical value used by the Generator
internally, but it will produce the same sequence of random numbers.
* These methods are compatible with recent versions of NumPy (1.20 and above). For older versions, you may need to adapt the code accordingly.