[Numpy-discussion] Bug in as_strided/reshape

Dave Hirschfeld dave.hirschfeld at gmail.com
Thu Aug 9 09:06:53 EDT 2012


Dave Hirschfeld <dave.hirschfeld <at> gmail.com> writes:

> 
> It seems that reshape doesn't work correctly on an array which has been
> resized using the 0-stride trick e.g.
> 
> In [73]: x = array([5])
> 
> In [74]: y = as_strided(x, shape=(10,), strides=(0,))
> 
> In [75]: y
> Out[75]: array([5, 5, 5, 5, 5, 5, 5, 5, 5, 5])
> 
> In [76]: y.reshape([10,1])
> Out[76]: 
> array([[          5],
>        [          8],
>        [  762933412],
>        [-2013265919],
>        [         26],
>        [         64],
>        [  762933414],
>        [-2013244356],
>        [         26],
>        [         64]]) <================ Should all be 5????????
> 
> In [77]: y.copy().reshape([10,1])
> Out[77]: 
> array([[5],
>        [5],
>        [5],
>        [5],
>        [5],
>        [5],
>        [5],
>        [5],
>        [5],
>        [5]])
> 
> In [78]: np.__version__
> Out[78]: '1.6.2'
> 
> Perhaps a clause such as below is required in reshape?
> 
> if any(stride == 0 for stride in y.strides):
>     return y.copy().reshape(shape)
> else:
>     return y.reshape(shape)
> 
> Regards,
> Dave
> 

Though it would be good to avoid the copy which you should be able to do in this 
case. Investigating further:

In [15]: y.strides
Out[15]: (0,)

In [16]: z = y.reshape([10,1])

In [17]: z.strides
Out[17]: (4, 4)

In [18]: z.strides = (0, 4)

In [19]: z
Out[19]: 
array([[5],
       [5],
       [5],
       [5],
       [5],
       [5],
       [5],
       [5],
       [5],
       [5]])

In [32]: y.reshape([5, 2])
Out[32]: 
array([[5, 5],
       [5, 5],
       [5, 5],
       [5, 5],
       [5, 5]])

In [33]: y.reshape([5, 2]).strides
Out[33]: (0, 0)

So it seems that reshape is incorrectly setting the stride of axis0 to 4, but 
only when the appended axis is of size 1.

-Dave







More information about the NumPy-Discussion mailing list