【问题标题】:Selecting multiple slices from a numpy array at once一次从 numpy 数组中选择多个切片
【发布时间】:2017-09-10 20:01:16
【问题描述】:

我正在寻找一种方法来一次从一个 numpy 数组中选择多个切片。假设我们有一个 1D 数据数组,并且想要提取它的三个部分,如下所示:

data_extractions = []

for start_index in range(0, 3):
    data_extractions.append(data[start_index: start_index + 5])

之后data_extractions 将是:

data_extractions = [
    data[0:5],
    data[1:6],
    data[2:7]
]

有没有什么方法可以在没有 for 循环的情况下执行上述操作? numpy 中的某种索引方案可以让我从数组中选择多个切片并将它们作为多个数组返回,比如在 n+1 维数组中?


我想也许我可以复制我的数据,然后从每一行中选择一个跨度,但是下面的代码会抛出一个 IndexError

replicated_data = np.vstack([data] * 3)
data_extractions = replicated_data[[range(3)], [slice(0, 5), slice(1, 6), slice(2, 7)]

【问题讨论】:

  • 那里的n 是什么?
  • stride_tricks 可能是一种方式
  • @Divakar - 维度。为了简单起见,我给出了一个 1D 示例,但需要一个通用解决方案(我真正的问题是 4D)。

标签: python numpy slice


【解决方案1】:

您可以使用索引将您想要的行选择为适当的形状。 例如:

 data = np.random.normal(size=(100,2,2,2))

 # Creating an array of row-indexes
 indexes = np.array([np.arange(0,5), np.arange(1,6), np.arange(2,7)])
 # data[indexes] will return an element of shape (3,5,2,2,2). Converting
 # to list happens along axis 0
 data_extractions = list(data[indexes])

 np.all(data_extractions[1] == data[1:6])
 True

最后比较的是原始数据。

【讨论】:

  • 该死,我尝试了上述方法,但使用indexes 作为范围列表以及切片列表,这些会导致IndexErrors。没有意识到我需要将indexes 的外部列表包装在一个 numpy 数组中^^
  • 我认为当您将列表放入 numpy 选择器时,它会尝试按轴过滤(即第一项是第一个轴的过滤器等)。实际上,将它放在另一个列表中,如indexes = [[np.arange(0,5), np.arange(1,6), np.arange(2,7)]] 可以解决它。
【解决方案2】:

stride_tricks 可以做到这一点

a = np.arange(10)
b = np.lib.stride_tricks.as_strided(a, (3, 5), 2 * a.strides)
b
# array([[0, 1, 2, 3, 4],
#        [1, 2, 3, 4, 5],
#        [2, 3, 4, 5, 6]])

请注意ba 引用相同的内存,实际上是多次引用(例如b[0, 1]b[1, 0] 是相同的内存地址)。因此,在使用新结构之前制作副本是最安全的。

nd 可以用类似的方式完成,例如 2d -> 4d

a = np.arange(16).reshape(4, 4)
b = np.lib.stride_tricks.as_strided(a, (3,3,2,2), 2*a.strides)
b.reshape(9,2,2) # this forces a copy
# array([[[ 0,  1],
#         [ 4,  5]],

#        [[ 1,  2],
#         [ 5,  6]],

#        [[ 2,  3],
#         [ 6,  7]],

#        [[ 4,  5],
#         [ 8,  9]],

#        [[ 5,  6],
#         [ 9, 10]],

#        [[ 6,  7],
#         [10, 11]],

#        [[ 8,  9],
#         [12, 13]],

#        [[ 9, 10],
#         [13, 14]],

#        [[10, 11],
#         [14, 15]]])

【讨论】:

  • 很好,我不知道np.lib.stride_tricks.as_strided,谢谢你,保罗。
  • @Puchatek 很高兴为您提供帮助。只是要小心那些东西。据我所知,它不会检查范围,因此它很乐意让您访问超出范围的内存等。
  • 是的,在 Ipython 中玩弄它,很快意识到如果不小心使用它会吹到我的脸上^^
  • @Puchatek 如果您使用正确的形状和步幅,应该没问题。
【解决方案3】:

在这篇文章中是strided-indexing scheme 使用np.lib.stride_tricks.as_strided 的方法,它基本上在输入数组中创建一个视图,因此创建非常有效,并且作为一个视图不再占用内存空间。 此外,这适用于具有通用维数的 ndarray。

这是实现 -

def strided_axis0(a, L):
    # Store the shape and strides info
    shp = a.shape
    s  = a.strides

    # Compute length of output array along the first axis
    nd0 = shp[0]-L+1

    # Setup shape and strides for use with np.lib.stride_tricks.as_strided
    # and get (n+1) dim output array
    shp_in = (nd0,L)+shp[1:]
    strd_in = (s[0],) + s
    return np.lib.stride_tricks.as_strided(a, shape=shp_in, strides=strd_in)

4D 数组案例的示例运行 -

In [44]: a = np.random.randint(11,99,(10,4,2,3)) # Array

In [45]: L = 5      # Window length along the first axis

In [46]: out = strided_axis0(a, L)

In [47]: np.allclose(a[0:L], out[0])  # Verify outputs
Out[47]: True

In [48]: np.allclose(a[1:L+1], out[1])
Out[48]: True

In [49]: np.allclose(a[2:L+2], out[2])
Out[49]: True

【讨论】:

    【解决方案4】:

    您可以使用准备好的切片数组对数组进行切片

    a = np.array(list('abcdefg'))
    
    b = np.array([
            [0, 1, 2, 3, 4],
            [1, 2, 3, 4, 5],
            [2, 3, 4, 5, 6]
        ])
    
    a[b]
    

    但是,b 不必以这种方式手动生成。它可以更加动态

    b = np.arange(5) + np.arange(3)[:, None]
    

    【讨论】:

    • 所以我虽然考虑了这种方法,但由于没有将创建索引的列表列表包装到一个 numpy 数组中,因此无法让它发挥作用。我猜我很傻。
    【解决方案5】:

    在一般情况下,您必须在构建索引或收集结果时进行某种迭代和连接。只有当切片模式本身是规则的时,您才能通过as_strided 使用广义切片。

    接受的答案构造一个索引数组,每片一行。所以这是对切片的迭代,arange 本身就是一个(快速)迭代。 np.array 将它们连接到一个新的轴上(np.stack 概括了这一点)。

    In [264]: np.array([np.arange(0,5), np.arange(1,6), np.arange(2,7)])
    Out[264]: 
    array([[0, 1, 2, 3, 4],
           [1, 2, 3, 4, 5],
           [2, 3, 4, 5, 6]])
    

    indexing_tricks 做同样事情的便捷方法:

    In [265]: np.r_[0:5, 1:6, 2:7]
    Out[265]: array([0, 1, 2, 3, 4, 1, 2, 3, 4, 5, 2, 3, 4, 5, 6])
    

    这采用切片符号,将其扩展为 arange 并连接。它甚至可以让我扩展并连接成 2d

    In [269]: np.r_['0,2',0:5, 1:6, 2:7]
    Out[269]: 
    array([[0, 1, 2, 3, 4],
           [1, 2, 3, 4, 5],
           [2, 3, 4, 5, 6]])
    
    In [270]: data=np.array(list('abcdefghijk'))
    In [272]: data[np.r_['0,2',0:5, 1:6, 2:7]]
    Out[272]: 
    array([['a', 'b', 'c', 'd', 'e'],
           ['b', 'c', 'd', 'e', 'f'],
           ['c', 'd', 'e', 'f', 'g']], 
          dtype='<U1')
    In [273]: data[np.r_[0:5, 1:6, 2:7]]
    Out[273]: 
    array(['a', 'b', 'c', 'd', 'e', 'b', 'c', 'd', 'e', 'f', 'c', 'd', 'e',
           'f', 'g'], 
          dtype='<U1')
    

    索引后连接结果也可以。

    In [274]: np.stack([data[0:5],data[1:6],data[2:7]])
    

    我对其他 SO 问题的记忆是,相对时间处于同一数量级。例如,它可能会随着切片数量与其长度的关系而变化。总的来说,必须从源复制到目标的值的数量是相同的。

    如果切片的长度不同,则必须使用平面索引。

    【讨论】:

    • 幸运的是,我必须按照常规模式处理切片。谢谢你的详细回答:)
    【解决方案6】:

    无论您选择哪种方法,如果 2 个切片包含相同的元素,则它不能正确支持数学运算,除非您使用可能比循环更低效的 ufunc.at。测试:

    def as_strides(arr, window_size, stride, writeable=False):
        '''Get a strided sub-matrices view of a 4D ndarray.
    
        Args:
            arr (ndarray): input array with shape (batch_size, m1, n1, c).
            window_size (tuple): with shape (m2, n2).
            stride (tuple): stride of windows in (y_stride, x_stride).
            writeable (bool): it is recommended to keep it False unless needed
        Returns:
            subs (view): strided window view, with shape (batch_size, y_nwindows, x_nwindows, m2, n2, c)
    
        See also numpy.lib.stride_tricks.sliding_window_view
        '''
        batch_size = arr.shape[0]
        m1, n1, c = arr.shape[1:]
        m2, n2 = window_size
        y_stride, x_stride = stride
    
        view_shape = (batch_size, 1 + (m1 - m2) // y_stride,
                      1 + (n1 - n2) // x_stride, m2, n2, c)
        strides = (arr.strides[0], y_stride * arr.strides[1],
                   x_stride * arr.strides[2]) + arr.strides[1:]
        subs = np.lib.stride_tricks.as_strided(arr,
                                               view_shape,
                                               strides=strides,
                                               writeable=writeable)
        return subs
    
    
    import numpy as np
    np.random.seed(1)
    
    Xs = as_strides(np.random.randn(1, 5, 5, 2), (3, 3), (2, 2), writeable=True)[0]
    print('input\n0,0\n', Xs[0, 0])
    np.add.at(Xs, np.s_[:], 5)
    print('unbuffered sum output\n0,0\n', Xs[0,0])
    np.add.at(Xs, np.s_[:], -5)
    Xs = Xs + 5
    print('normal sum output\n0,0\n', Xs[0, 0])
    

    【讨论】:

      【解决方案7】:

      我们可以为此使用列表推导

      data=np.array([1,2,3,4,5,6,7,8,9,10])
      data_extractions=[data[b:b+5] for b in [1,2,3,4,5]]
      data_extractions
      

      结果

      [array([2, 3, 4, 5, 6]), array([3, 4, 5, 6, 7]), array([4, 5, 6, 7, 8]), array([5, 6, 7, 8, 9]), array([ 6,  7,  8,  9, 10])]
      

      【讨论】:

      • 这并不能避免 for 循环 ;)
      • 我同意 :) 但不是原生 for 循环 :)
      猜你喜欢
      • 2019-04-02
      • 2018-08-05
      • 1970-01-01
      • 1970-01-01
      • 2016-12-19
      • 1970-01-01
      • 2021-02-12
      • 1970-01-01
      相关资源
      最近更新 更多