You could keep the global random state in a temporary variable and reset it once your function is done:
import contextlib
import numpy as np
@contextlib.contextmanager
def temp_seed(seed):
state = np.random.get_state()
np.random.seed(seed)
try:
yield
finally:
np.random.set_state(state)
Demo:
>>> np.random.seed(0)
>>> np.random.randn(3)
array([1.76405235, 0.40015721, 0.97873798])
>>> np.random.randn(3)
array([ 2.2408932 , 1.86755799, -0.97727788])
>>> np.random.seed(0)
>>> np.random.randn(3)
array([1.76405235, 0.40015721, 0.97873798])
>>> with temp_seed(5):
... np.random.randn(3)
array([ 0.44122749, -0.33087015, 2.43077119])
>>> np.random.randn(3)
array([ 2.2408932 , 1.86755799, -0.97727788])
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…