Created
February 5, 2020 10:11
-
-
Save VictorDarvariu/6cede9c79900c6215b5f848993d283c6 to your computer and use it in GitHub Desktop.
Example of managing NumPy seed with contextmanager
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import contextlib | |
| import numpy as np | |
| # For info on contextlib, see https://docs.python.org/3/library/contextlib.html | |
| @contextlib.contextmanager | |
| def local_seed(seed): | |
| state = np.random.get_state() | |
| np.random.seed(seed) | |
| try: | |
| yield | |
| finally: | |
| np.random.set_state(state) | |
| if __name__ == '__main__': | |
| my_seed = 42 | |
| with local_seed(my_seed): | |
| value = np.random.rand(1) | |
| print(f"sampled {value} using seed {my_seed}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment