Anjith
Anjith

Reputation: 2308

Numpy reshape seems to output value error

I tried to use reshape

import numpy as np
d = np.arange(30).reshape(1,3)

It is not working cannot reshape array of size 30 into shape (1,3)

but when I tried to use

d = np.arange(30).reshape(-1,3) # This works

Why do we have to use -1?.

It's really confusing and I'm can't seem to figure out how reshape works. I would really appreciate if someone can help me figure out how this works. I tried docs and other posts in SO but it wasn't much helpful.

I am new to ML and Python.

Upvotes: 0

Views: 956

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476614

A reshape means that you order your elements of the array, according to other dimensions. For example arange(27) will produce a vector containing 27 elements. But with .reshape(9, 3) you specify here that you want to transform it into a two dimensional array, where the first dimension contains 9 elements, and the second three elements. So the result will look like:

>>> np.arange(27).reshape(9, 3)
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [12, 13, 14],
       [15, 16, 17],
       [18, 19, 20],
       [21, 22, 23],
       [24, 25, 26]]) 

But we can also make it a 3×3×3 array:

>>> np.arange(27).reshape(3, 3, 3)
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],

       [[18, 19, 20],
        [21, 22, 23],
        [24, 25, 26]]])

-1 is used as a value that will numpy derive the dimension.

So if you have an array containing 30 elements, and you reshape these to m×3, then m is 10. -1 is thus not the real value, it is used for programmer convenience if for example you do not know the number of elements, but know that it is divisable by three.

The following two are (under the assumption that m contains 30 elements equivalent:

m.reshape(10, 3)
m.reshape(-1, 3)

Note that you can specify at most one -1, since otherwise there are multiple possibilities, and it becomes also harder to find a valid configuration.

Upvotes: 3

Related Questions