我在这里询问后立即想到了这个答案。
不过我不确定这是不是最好的解决方案,所以我很高兴收到其他建议。
我最终使用了来自 sklearn 的实用函数,如果需要,它会将整数输入转换为 RandomState 实例。
def check_random_state(seed):
"""Turn seed into a np.random.RandomState instance
Parameters
----------
seed : None | int | instance of RandomState
If seed is None, return the RandomState singleton used by np.random.
If seed is an int, return a new RandomState instance seeded with seed.
If seed is already a RandomState instance, return it.
Otherwise raise ValueError.
"""
if seed is None or seed is np.random:
return np.random.mtrand._rand
if isinstance(seed, (numbers.Integral, np.integer)):
return np.random.RandomState(seed)
if isinstance(seed, np.random.RandomState):
return seed
raise ValueError('%r cannot be used to seed a numpy.random.RandomState'
' instance' % seed)
因此,我可以写:
from sklearn.utils import check_random_state
def replicable_function(random_seed):
random_seed = check_random_state(random_seed)
choice = random_seed.choice(X, 10) #instead of np.random.choice(X, 10)
#do more stuff here with choice
return f(choice)