【问题标题】:Select Multiple slices from Numpy array at once一次从 Numpy 数组中选择多个切片
【发布时间】:2019-04-02 19:22:44
【问题描述】:

我想实现一个向量化的 SGD 算法,并且想一次生成多个小批量。

假设data = np.arange(0, 100)miniBatchSize=10n_miniBatches=10indices = np.random.randint(0, n_miniBatches, 5)(5 个小批量)。我想要实现的是

miniBatches = np.zeros(5, miniBatchSize)
for i in range(5):
     miniBatches[i] = data[indices[i]: indices[i] + miniBatchSize]

有没有办法避免for循环?

谢谢!

【问题讨论】:

  • 你必须做一些 Python 级别的循环。您可以像在此处那样组合切片,也可以生成索引范围、连接这些切片和一个索引。所有替代方案的速度大致相同。另一种选择是使用as_strided 生成此大小的所有切片,然后选择一个子集。

标签: python numpy indexing


【解决方案1】:

可以使用stride tricks:

from numpy.lib.stride_tricks import as_strided

a = as_strided(data[:n_miniBatches], shape=(miniBatchSize, n_miniBatches), strides=2*data.strides, writeable=False)    
miniBatches = a[:, indices].T


# E.g. indices = array([0, 7, 1, 0, 0])
Output:
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [ 7,  8,  9, 10, 11, 12, 13, 14, 15, 16],
       [ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10],
       [ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9]])

【讨论】:

    猜你喜欢
    • 2017-09-10
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    相关资源
    最近更新 更多