代码之家  ›  专栏  ›  技术社区  ›  mchaudh4

使用np.random.randint避免重复选择

  •  1
  • mchaudh4  · 技术社区  · 2 年前

    我是python的新手,特别是与机器学习相关的python。下面的代码行从 distinct_zeros 数组,但它正在进行重复选择。我该怎么做才能不选择重复项。

    import numpy as np
    
    distinct_zeros =np.array( [[0.17857143, 0.28571429, 0.32142857, 0.35714286, 0.35714286],
     [0.64285714, 0.60714286, 0.35714286, 0.39285714, 0.57142857 ]])
    
    
    train_zero_indices = np.random.randint(low=0, high= len(distinct_zeros[0]), size= int(0.5* len(distinct_zeros[0])))
    print(train_zero_indices)
    
    
       (pennylane_study) m992c693@alveo:~/RESEARCH_WORK$ python np.random.randint.py 
        [3 3]
    

    编辑

    rng = np.random.default_rng()
    train_zero_indices= rng.choice(len(distinct_zeros[0]), int(0.5* len(distinct_zeros[0])), replace=False)
    print(train_zero_indices) 
    

    上面的行给出了正确的结果,但没有设置低值的选项。默认情况下,低值为0。

    1 回复  |  直到 2 年前
        1
  •  2
  •   RomanPerekhrest    2 年前

    使用 random.Generator.choice 具有 replace=False (避免多次选择一个值):

    rng = np.random.default_rng()
    rng.choice(distinct_zeros.shape[1], distinct_zeros.shape[1] // 2, replace=False)
    

    随机抽样:

    array([4, 2]) 
    

    设置 低的 高的 您可以通过各自的边界 range(low, high) 作为第一个论点。但是要小心,你 不能 要求 size=3 来自 range(3, 5) 具有重复数据消除要求。所以这仍然取决于你的良心。

    rng.choice(range(2, distinct_zeros.shape[1]), distinct_zeros.shape[1] // 2, replace=False)
    array([3, 2])