对 numpy 步幅的困惑

Confusion about numpy strides

我正在查看此问题的 ,但无法理解 as_strided 函数如何查看此数组。

这段代码是 :

的一部分
>>> a = np.lib.stride_tricks.as_strided(np.array([1, 512, 0, 3], dtype=np.int16), 
                                        shape=(3,), strides=(3,))
>>> a
array([1, 2, 3], dtype=int16)

>>> a.strides[0]
3

>>> a.itemsize
2 

假设传递的数组的每个元素都是 2 个字节长,我们有以下数组的字节表示:

-------------------------------------------------------------------------------------
         1          |        512          |        0            |          3
-------------------------------------------------------------------------------------
0000 0000 0000 0001 | 0000 0010 0000 0000 | 0000 0000 0000 0000 | 0000 0000 0000 0011

因此,考虑到每个要读取的元素都是 2 个字节,而到达下一个元素的步幅是 3 个字节:

  1. 读取的第一个元素是1(0000 0000 0000 0001),
  2. 要读取的第二个元素是在跳过 3 个字节后得出 00000 0000 | 0000 0000),一半是数字 512 中的字节,并且另一半来自数字0
  3. 再跨步 3 个字节后要读取的最后一个元素是 30000 0000 0000 0011

所以,我哪里错了?跨步输出中的中间元素 2 是如何而不是 0

np.array([1, 512, 0, 3], dtype=np.int16) 的 little-endian 内存布局实际上在内存中看起来像这样(由于是 little-endian,各个条目字节实际上与您编写的顺序相反他们):

(value)
-----------------------------------------------------------------------------------------
         1           |        512           |         0            |          3
-----------------------------------------------------------------------------------------
0000 0001  0000 0000 | 0000 0000  0000 0010 | 0000 0000  0000 0000 | 0000 0011  0000 0000
-----------------------------------------------------------------------------------------
        0          1           2          3           4          5           6          7
(byte number)

stride=3 表示在项目之间移动 3 个字节,因此您将得到字节数 0-13-46-7.

这些是0000 0001 0000 00000000 0010 0000 00000000 0011 0000 0000,再次解释为little-endian。

The strides of an array tell us how many bytes we have to skip in memory to move to the next position along a certain axis.

https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.strides.html