【python】numpy中的高效分块操作np.stride_tricks.as_strided

来源:互联网 发布:php 提现到银行卡 编辑:程序博客网 时间:2024/06/05 22:30

最近看代码的时候看到了这么一个函数
np.stride_tricks.as_strided(x, shap, strides, subok, writeable)

Parameters: x : ndarrayArray to create a new.shape : sequence of int, optionalThe shape of the new array. Defaults to x.shape.strides : sequence of int, optionalThe strides of the new array. Defaults to x.strides.subok : bool, optionalNew in version 1.10.If True, subclasses are preserved.writeable : bool, optionalNew in version 1.12.If set to False, the returned array will always be readonly. Otherwise it will be writable if the original array was. It is advisable to set this to False if possible (see Notes).Returns:    view : ndarray

详细可以见官方文档:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.lib.stride_tricks.as_strided.html#numpy.lib.stride_tricks.as_strided

看个实际案例便可以明白如何使用:

# 来源:NumPy Cookbook 2e Ch2.9import numpy as np# 数独是个 9x9 的二维数组# 包含 9 个 3x3 的九宫格sudoku = np.array([       [2, 8, 7, 1, 6, 5, 9, 4, 3],    [9, 5, 4, 7, 3, 2, 1, 6, 8],    [6, 1, 3, 8, 4, 9, 7, 5, 2],    [8, 7, 9, 6, 5, 1, 2, 3, 4],    [4, 2, 1, 3, 9, 8, 6, 7, 5],    [3, 6, 5, 4, 2, 7, 8, 9, 1],    [1, 9, 8, 5, 7, 3, 4, 2, 6],    [5, 4, 2, 9, 1, 6, 3, 8, 7],    [7, 3, 6, 2, 8, 4, 5, 1, 9]])# 要将其变成 3x3x3x3 的四维数组# 但不能直接 reshape,因为这样会把一行变成一个九宫格shape = (3, 3, 3, 3)# 大行之间隔 27 个元素,大列之间隔 3 个元素# 小行之间隔 9 个元素,小列之间隔 1 个元素strides = sudoku.itemsize * np.array([27, 3, 9, 1])squares = np.lib.stride_tricks.as_strided(sudoku, shape=shape, strides=strides) print(squares)'''[[[[2 8 7]    [9 5 4]    [6 1 3]]  [[1 6 5]    [7 3 2]    [8 4 9]]  [[9 4 3]    [1 6 8]    [7 5 2]]] [[[8 7 9]    [4 2 1]    [3 6 5]]  [[6 5 1]    [3 9 8]    [4 2 7]]  [[2 3 4]    [6 7 5]    [8 9 1]]] [[[1 9 8]    [5 4 2]    [7 3 6]]  [[5 7 3]    [9 1 6]    [2 8 4]]  [[4 2 6]    [3 8 7]    [5 1 9]]]]'''

其实说到底,就是按shape的形状对一个矩阵进行切块

参考:http://www.johnvinyard.com/blog/?p=268
http://blog.csdn.net/wizardforcel/article/details/72793092