【问题标题】:In numpy, how to efficiently list all fixed-size submatrices?在 numpy 中,如何有效地列出所有固定大小的子矩阵?
【发布时间】:2013-10-25 05:34:00
【问题描述】:

我有一个任意的 NxM 矩阵,例如:

1 2 3 4 5 6
7 8 9 0 1 2
3 4 5 6 7 8
9 0 1 2 3 4

我想得到这个矩阵中所有 3x3 子矩阵的列表:

1 2 3       2 3 4               0 1 2
7 8 9   ;   8 9 0   ;  ...  ;   6 7 8
3 4 5       4 5 6               2 3 4

我可以用两个嵌套循环来做到这一点:

rows, cols = input_matrix.shape
patches = []
for row in np.arange(0, rows - 3):
    for col in np.arange(0, cols - 3):
        patches.append(input_matrix[row:row+3, col:col+3])

但是对于一个大的输入矩阵,这很慢。 有没有办法用 numpy 更快地做到这一点?

我查看了np.split,但这给了我不重叠的子矩阵,而我想要所有可能的子矩阵,而不管重叠。

【问题讨论】:

  • 不确定是否有 numpy 方法可以做到这一点,但切换到列表理解应该会有所帮助。

标签: python numpy matrix


【解决方案1】:

你想要一个窗口视图:

from numpy.lib.stride_tricks import as_strided

arr = np.arange(1, 25).reshape(4, 6) % 10
sub_shape = (3, 3)
view_shape = tuple(np.subtract(arr.shape, sub_shape) + 1) + sub_shape
arr_view = as_strided(arr, view_shape, arr.strides * 2
arr_view = arr_view.reshape((-1,) + sub_shape)

>>> arr_view
array([[[[1, 2, 3],
         [7, 8, 9],
         [3, 4, 5]],

        [[2, 3, 4],
         [8, 9, 0],
         [4, 5, 6]],

        ...

        [[9, 0, 1],
         [5, 6, 7],
         [1, 2, 3]],

        [[0, 1, 2],
         [6, 7, 8],
         [2, 3, 4]]]])

这样做的好处是您没有复制任何数据,您只是以不同的方式访问原始数组的数据。对于大型数组,这可以节省大量内存。

【讨论】:

  • 倒数第二行没有右括号。
猜你喜欢
  • 2015-12-18
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 2021-08-19
  • 2011-04-17
  • 2021-09-01
  • 2017-02-19
  • 1970-01-01
相关资源
最近更新 更多