【问题标题】:Passing random seed to numpy random.choice function将随机种子传递给 numpy random.choice 函数
【发布时间】:2020-03-12 11:32:41
【问题描述】:

假设我有一个函数,它采用random_state 参数来确保可复制性

def replicable_function(random_seed):
    choice = np.random.choice(X, 10)
    #do more stuff here with choice
    return f(choice)

这是我的两个要求:

  1. 传递相同的random_seed(可以是整数或np.random.RandomState 对象)意味着replicable_function 总是输出相同的东西
  2. 我不会更改全局 numpy 随机种子状态(试图对用户友好,而不是更改她不期望的事情)

理想情况下,我想将这个random_state 传递给np.random.choice 函数,但它似乎不接受这样的参数(see the source code here!)

【问题讨论】:

    标签: numpy random-seed


    【解决方案1】:

    我在这里询问后立即想到了这个答案。 不过我不确定这是不是最好的解决方案,所以我很高兴收到其他建议。

    我最终使用了来自 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多