python 实施 numpy.lib.stride_tricks.as_strided

python implementation of numpy.lib.stride_tricks.as_strided

我正在尝试将 NumPy 的 as_strided 函数转换为 Python 中的函数,当我 运行 将步数提前到根据变量类型的变量数量(对于 float32,我将步幅除以 4,等等)。

我实现的代码:

def as_strided(x, shape, strides):
    x = x.flatten()
    size = 1
    for value in shape:
        size *= value
    arr = np.zeros(size, dtype=np.float32)
    curr = 0
    for i in range(shape[0]):
        for j in range(shape[1]):
            for k in range(shape[2]):
                arr[curr] = x[i * strides[0] + j * strides[1] + k * strides[2]]
                curr = curr + 1
    return np.reshape(arr, shape)

为了测试功能我写了2个辅助函数:

def sliding_window(x, shape, strides):
    f_mine = as_strided(x, shape, [stride // 4 for stride in strides])
    f_np = np.lib.stride_tricks.as_strided(x, shape=shape, strides=strides).copy()
    check_strides(x.flatten(), f_mine)
    check_strides(x.flatten(), f_np)
    return f_mine, f_np

def check_strides(original, strided):
    s1 = int(np.where(original == strided[1][0][0])[0])
    s2 = int(np.where(original == strided[0][1][0])[0])
    s3 = int(np.where(original == strided[0][0][1])[0])
    print([s1, s2, s3])
    return [s1, s2, s3]

在主要代码中,我选择了一些形状和步幅值以及 运行 2 个案例:

  1. 上传了一个包含 float32 矩阵的 .npy 文件 - 变量 x。
  2. 已创建 运行与变量 x - 变量 y 大小和类型相同的 dom 矩阵。

当我检查结果矩阵的步幅时,我得到了一个 st运行ge 现象。 对于案例 1 - 使用 NumPy 函数获得的最终结果步幅与所需步幅(以及我的实现)不同。 对于情况 2 - 输出相同。

主要代码:

shape = (30, 818, 300)
strides = (4, 120, 120)

# case 1
x = np.load('x.npy')
s_mine, s_np = sliding_window(x, shape, strides)
print(np.array_equal(s_mine, s_np))

#case 2
y = np.random.randn(x.shape[0], x.shape[1]).astype(np.float32)
s_mine, s_np = sliding_window(y, shape, strides)
print(np.array_equal(s_mine, s_np))

Here 您可以在 numpy 函数中找到导致所需步幅更改的 x.npy 文件。如果有人能向我解释为什么会这样,我会很高兴。

我下载了 x.npy 并加载了它。 运行 as_strided y。我没看过你的代码。

通常在玩 as_strided 时,我喜欢看阵列,但在这种情况下,它们足够大,我会更加关注步幅和形状。

In [39]: x.shape, x.strides
Out[39]: ((30, 1117), (4, 120))
In [40]: y.shape, y.strides
Out[40]: ((30, 1117), (4468, 4))

我想知道你从哪里得到的

shape = (30, 818, 300)
strides = (4, 120, 120)

好的,30 是共享的,但 4 只用于 x。随着这些进步 x 看起来它是 F 有序的,甚至可能是 (1117,30) 数组的 t运行spose。您的 y 是用 random 构造的,具有 C 有序数组的典型步幅,内部尾随维度为 4 个字节,前导维度为 4*1117。