When aiming for reproducibility in Python code using random number generators, the recommended approach seems to be to construct separate RandomState objects. Unfortunately, some essential packages like scipy.stats cannot (to the best of my knowledge) be set to use a specific RandomState and will just use the current state of numpy.random. My current workaround is to use a context manager which saves the state of the RNG and then resets it upon exiting as follows:
class FixedSeed:
def __init__(self, seed):
self.seed = seed
self.state = None
def __enter__(self):
self.state = rng.get_state()
np.random.seed(self.seed)
def __exit__(self, exc_type, exc_value, traceback):
np.random.set_state(self.state)
There are a lot of warnings in the documentation about changing the state in any way - is the above approach safe in general? (in the sense that the change is local to the context and that the rest of my code will be unaffected)
Aucun commentaire:
Enregistrer un commentaire