Numpy中能否通过调整reshape与strides参数移除初始transpose操作?
问题:移除Numpy代码中的transpose函数,调整reshape与strides的索引顺序
可以通过调整shape、strides的参数以及后续的维度操作,完全移除开头的transpose函数,以下是具体实现和说明:
原代码及输入输出
原代码
import numpy as np # 输入数据 array = np.array([[1, 60], [2, 70], [3, 80], [4, 90]]) depth = 3 # 处理逻辑 n_rows, n_cols = array.shape array = array.T # transpose函数在此处 shape = array.shape[:-1] + (array.shape[-1] - depth + 1, depth - 1) strides = array.strides + (array.strides[-1],) array = np.lib.stride_tricks.as_strided(array, shape=shape, strides=strides) reshaped = np.reshape( np.swapaxes(array, 0, 1), (n_rows-depth+1, (depth - 1) * n_cols), )
输入与输出
# 输入array array([[ 1, 60], [ 2, 70], [ 3, 80], [ 4, 90]]) # 输出reshaped array([[ 1, 2, 60, 70], [ 2, 3, 70, 80]])
移除transpose的修改版本
修改后代码
import numpy as np # 输入数据 array = np.array([[1, 60], [2, 70], [3, 80], [4, 90]]) depth = 3 # 处理逻辑(移除transpose) n_rows, n_cols = array.shape # 直接基于原数组构造滑动窗口的shape:(滑动窗口数量, 窗口内行数, 列数) shape = (n_rows - depth + 1, depth - 1, n_cols) # 构造对应strides:行滑动步长、窗口内行偏移步长、列偏移步长 strides = (array.strides[0], array.strides[0], array.strides[1]) array = np.lib.stride_tricks.as_strided(array, shape=shape, strides=strides) # 无需swapaxes,直接reshape得到目标格式 reshaped = array.reshape((n_rows - depth + 1, (depth - 1) * n_cols))
核心调整说明
- shape参数调整:原代码转置后在列维度(原行维度)做滑动窗口,现在直接在原数组的行维度构造滑动窗口,shape设为
(滑动窗口数, 窗口内行数, 列数),对应(4-3+1, 3-1, 2)即(2,2,2)。 - strides参数调整:利用原数组的行、列步长,设置滑动时每次移动一行(
array.strides[0]),窗口内取连续行(同样用array.strides[0]),列维度正常偏移(array.strides[1])。 - 移除swapaxes:调整shape后维度顺序已经符合reshape需求,不需要再交换轴,直接reshape即可得到和原代码一致的输出。
内容的提问来源于stack exchange,提问作者pierre_j
相关产品推荐
相关产品推荐

