Manipulations des strides et shape avec numpy

的 Joseph Razik, last modified 在 2019-10-18
numpy_stride

Manipulation des strides d'array de numpy

In [1]:
import numpy as np
In [2]:
a = np.arange(20)
In [3]:
a
Out[3]:
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19])
In [4]:
a = a.reshape((5,4), order='F')
In [5]:
a
Out[5]:
array([[ 0,  5, 10, 15],
       [ 1,  6, 11, 16],
       [ 2,  7, 12, 17],
       [ 3,  8, 13, 18],
       [ 4,  9, 14, 19]])
In [6]:
from numpy.lib.stride_tricks import as_strided
In [7]:
a.strides
Out[7]:
(8, 40)
In [8]:
a.shape
Out[8]:
(5, 4)
In [9]:
b = as_strided(a, strides=(8, 16), shape=(2, 10))
In [10]:
b
Out[10]:
array([[ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18],
       [ 1,  3,  5,  7,  9, 11, 13, 15, 17, 19]])
In [11]:
c = as_strided(a, strides=(8, 16), shape=(4, 9))
In [12]:
c
Out[12]:
array([[ 0,  2,  4,  6,  8, 10, 12, 14, 16],
       [ 1,  3,  5,  7,  9, 11, 13, 15, 17],
       [ 2,  4,  6,  8, 10, 12, 14, 16, 18],
       [ 3,  5,  7,  9, 11, 13, 15, 17, 19]])
In [13]:
id(a), id(b), id(c)
Out[13]:
(139898340931264, 139898340930064, 139898340932944)
In [14]:
d = as_strided(a, strides=(8, 16), shape=(5, (20-5)//2+1))
In [15]:
d
Out[15]:
array([[ 0,  2,  4,  6,  8, 10, 12, 14],
       [ 1,  3,  5,  7,  9, 11, 13, 15],
       [ 2,  4,  6,  8, 10, 12, 14, 16],
       [ 3,  5,  7,  9, 11, 13, 15, 17],
       [ 4,  6,  8, 10, 12, 14, 16, 18]])
In [33]:
b = as_strided(a, strides=(16, 8, 80), shape=(10, 2, 2))
In [34]:
b
Out[34]:
array([[[                  0,                  10],
        [                  1,                  11]],

       [[                  2,                  12],
        [                  3,                  13]],

       [[                  4,                  14],
        [                  5,                  15]],

       [[                  6,                  16],
        [                  7,                  17]],

       [[                  8,                  18],
        [                  9,                  19]],

       [[                 10,                 176],
        [                 11,                3201]],

       [[                 12,                   1],
        [                 13,     139899149145856]],

       [[                 14,                3140],
        [                 15,                  -1]],

       [[                 16,                 228],
        [                 17,                   0]],

       [[                 18, 4398461372421459466],
        [                 19, 8237094757554011453]]])
In [18]:
a.__array_interface__['data'][0]
Out[18]:
94307559584256