Jupyter Snippet CB2nd 06_stride_tricks

Jupyter Snippet CB2nd 06_stride_tricks

4.6. Using stride tricks with NumPy

import numpy as np
def aid(x):
    # This function returns the memory
    # block address of an array.
    return x.__array_interface__['data'][0]
x = np.zeros(10)
x.strides
(8,)
y = np.zeros((10, 10))
y.strides
(80, 8)
n = 1000
a = np.arange(n)
b = np.lib.stride_tricks.as_strided(a, (n, n), (0, 8))
b
array([[  0,   1,   2, ..., 997, 998, 999],
       [  0,   1,   2, ..., 997, 998, 999],
       [  0,   1,   2, ..., 997, 998, 999],
       ...,
       [  0,   1,   2, ..., 997, 998, 999],
       [  0,   1,   2, ..., 997, 998, 999],
       [  0,   1,   2, ..., 997, 998, 999]])
b.size, b.shape, b.nbytes
(1000000, (1000, 1000), 8000000)
%timeit b * b.T
766 µs ± 2.59 µs per loop (mean ± std. dev. of 7 runs,
1000 loops each)
%%timeit
np.tile(a, (n, 1)) * np.tile(a[:, np.newaxis], (1, n))
5.55 ms ± 9.1 µs per loop (mean ± std. dev. of 7 runs,
100 loops each)