Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy reshape confusion with negative shape values

Always confused how numpy reshape handle negative shape parameter, here is an example of code and output, could anyone explain what happens for reshape [-1, 1] here? Thanks.

Related document, using Python 2.7.

http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html

import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder

S = np.array(['box','apple','car'])
le = LabelEncoder()
S = le.fit_transform(S)
print(S)
ohe = OneHotEncoder()
one_hot = ohe.fit_transform(S.reshape(-1,1)).toarray()
print(one_hot)

[1 0 2]
[[ 0.  1.  0.]
 [ 1.  0.  0.]
 [ 0.  0.  1.]]
like image 623
Lin Ma Avatar asked Dec 05 '22 17:12

Lin Ma


2 Answers

-1 is used to infer one missing length from the other. For example reshaping (3,4,5) to (-1,10) is equivalent to reshaping to (6,10) because 6 is the only length that makes sense form the other inputs.

like image 115
Julien Avatar answered Dec 13 '22 09:12

Julien


From reshape docs:

One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

In your case it is used for the common task of transforming the (3,) S into a (3,1) array. I think in this particular case using S[:, None] would have the same effect.

like image 22
Aguy Avatar answered Dec 13 '22 08:12

Aguy