I'm really new to the numpy and currently confused with negative values in reshape.
import numpy as np
a=np.arange(6)
c=a.reshape(1,3,2)
d=a.reshape(-1,3,2)
e=a.reshape(-1,1,2)
print c
print
print d
print
print e
and it returns
[[[0 1]
[2 3]
[4 5]]]
[[[0 1]
[2 3]
[4 5]]]
[[[0 1]]
[[2 3]]
[[4 5]]]
The question here is that when comparing c and d, there's no difference at all. However in e, additional empty line is formed between each row. So, what exactly does the -1 do in reshape function, and why it causes empty lines between each row in e? Thanks !
When you add -1
to an axis in numpy it will just put everything else in that axis. This is, for an array a
of shape (10, 10)
, the following operations will apply:
>>> a.reshape(-1, 10, 10) # a is (1, 10, 10)
>>> a.reshape( 1, 10, 10) # a is also (1, 10, 10)
>>> a.reshape(-1, 5, 5) # a is (4, 5, 5), since 4 * 5 * 5 = 100
>>> a.reshape(-1, 5, 10) # a is (2, 5, 10) since 2 * 5 * 10 = 100
This is, when reshaping the total number of elements must be the same, so adding -1
to the shape just lets numpy calculate the remaining value for you, so that the product of the axes still matches the previous number of elements.
The difference between c
and e
is not only the additional space, but also the additional bracket around each pair, i.e.
[2 3] vs [[2 3]]
This is because the shape of c
is [1, 3, 2]
, while the shape of e
is [3, 1, 2]
. The shape of d
is also [1, 3, 2]
, and that is why c
and d
are equal.
When you put -1 in the shape, numpy infers it from the other dimensions, that is replaces -1 with product of all dimensions of a / product of all specified shapes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With