1

I have a function which do some random things..

And I want to input seed to it, so for same seeds the output will be the same..

But initiating the seed at the beggining like this:

def generate_random_number(seed): np.random.seed(seed) magics = np.random.random(1) more_magics = ... return magics, more_magics 

Will result that after calling this method, the seed is ruined.

Is there a way to "save" the current seed state and restore it later?

So it will look something like this:

def generate_random_number_without_ruining_for_others(seed): old_seed = np.random.get_seed() np.random.seed(seed) magics = np.random.random(1) more_magics = ... np.random.seed(old_seed) return magics, more_magics 

Of course, the command: np.random.get_seed() is a made-up function.. is there something like this? Or alternative approach to generate "random" (up to seed input) output without destroying everyone's randomness state?

(The actual random process is much more complicated in practice, it generates matrices in loop so I would like to stick with the format of initiating seed at the beggining for simplicity)

1 Answer 1

2

AFAIK, you cannot reset the default random generator. Actually the documentation of seed say not to use it:

This is a convenience, legacy function.

The best practice is to not reseed a BitGenerator, rather to
recreate a new one. This method is here for legacy reasons.
This example demonstrates best practice.

>>> from numpy.random import MT19937
>>> from numpy.random import RandomState, SeedSequence
>>> rs = RandomState(MT19937(SeedSequence(123456789)))

Based on this, you can build your own random engine and save the random state. Here is an example:

import numpy as np rs = np.random.RandomState(np.random.MT19937(np.random.SeedSequence(123456789))) savedState = rs.get_state() # Save the state v1 = rs.randint(0, 100, 7) # array([28, 72, 18, 84, 6, 78, 92]) v2 = rs.randint(0, 100, 7) # array([60, 91, 4, 29, 43, 68, 52]) rs.set_state(savedState) # Reset the state v3 = rs.randint(0, 100, 7) # array([28, 72, 18, 84, 6, 78, 92]) v4 = rs.randint(0, 100, 7) # array([60, 91, 4, 29, 43, 68, 52]) assert(np.array_equal(v1, v3)) # True assert(np.array_equal(v2, v4)) # True 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.