【问题标题】:Randomly pick index with constant interval以恒定间隔随机选取索引
【发布时间】:2020-01-02 10:18:04
【问题描述】:

有没有办法随机选择具有恒定间隔的 numpy 数组的索引。

例如, 我有一个形状为 (1, 150) 的数组,它是 5*30 个元素。我想随机选择 x 个索引,其中每 30 个元素 x

首先,我尝试使用np.chocie,但我不能使用np.choice,因为它看起来不是恒定的间隔。

我可以对每个元素进行循环迭代,但我觉得这不是有效的方法。

numpy有什么办法吗?

我试过了,它给出了所需的结果。但我想改进代码

frames_picker = np.zeros(30*5)
samples=[]
for i in range(5):
    sample = (np.random.choice(frames_picker[0: 30].shape[0], 5, replace=False))+(i*30)
    samples.append(sample)
samples=np.array(samples)
frames_picker[np.sort(samples)]=1

【问题讨论】:

标签: python numpy random


【解决方案1】:
>>> np.random.choice(30, size=(5,5), replace=False) + np.arange(0, 150, 30)[:,None]

array([[ 18,  28,  13,   6,   8],
       [ 40,  56,  44,  57,  32],
       [ 83,  71,  65,  81,  64],
       [114, 115,  97,  90, 106],
       [137, 121, 129, 142, 149]])

然后您可以将它们展平和排序。这为您提供了每个区间 [0, 29]、[30, 59]、...、[120, 149] 中的 5 个随机索引。

【讨论】:

    【解决方案2】:

    您可以将一维数组转换为更合适的二维矩阵,然后应用采样。例如:

    data = np.array(...) # 1D array with 5*30 elements
    m = np.asmatrix(np.split(data, 5))  # chunk and convert to a matrix
    sample = m[np.random.randint(m.shape[0], size=30), :]  # get random 30 slices from the matrix
    np.ravel(sample)  # convert back to 1D array
    

    【讨论】:

      猜你喜欢
      • 2015-12-24
      • 1970-01-01
      • 1970-01-01
      • 2013-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-28
      • 2012-09-13
      相关资源
      最近更新 更多