训练预测模型时输入形状不良

时间:2019-06-04 13:51:25

标签: python-3.x numpy valueerror

我使用以下代码使用sklearn训练了货币汇率预测模型,但出现了错误:

import numpy as np
x = [[30],[40],[50],[60],[70],[80],[90],[100],[120],[130],[140],[150]] 
y = ['jan','febuary,'march','april','may','june','july','august','september','october','november','december']

y_2 = np.reshape(y, (-1, 2))
#reshaping because it throws in an error to reshape

from sklearn import preprocessing
le = preprocessing.LabelEncoder()
y_3 = le.fit_transform(y_2)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-144-c98a5b8bd15a> in <module>
----> 1 y_3 = le.fit_transform(y_2)

c:\users\user\appdata\local\programs\python\python37-32\lib\site-packages\sklearn\preprocessing\label.py in fit_transform(self, y)
233         y : array-like of shape [n_samples]
234         """
--> 235         y = column_or_1d(y, warn=True)
236         self.classes_, y = _encode(y, encode=True)
237         return y

c:\users\user\appdata\local\programs\python\python37-32\lib\site-packages\sklearn\utils\validation.py in column_or_1d(y, warn)
795         return np.ravel(y)
796 
--> 797     raise ValueError("bad input shape {0}".format(shape))
798 
799 

ValueError: bad input shape (6, 2)

该如何解决此错误?

1 个答案:

答案 0 :(得分:1)

您无需在reshape()上执行y。以下就足够了。

import numpy as np
x = [[30],[40],[50],[60],[70],[80],[90],[100],[120],[130],[140],[150]]
y = ['jan','febuary','march','april','may','june','july','august','september','october','november','december']

#y_2 = np.reshape(y, (-1, 2)) --> This is not needed
#reshaping because it throws in an error to reshape

from sklearn import preprocessing
le = preprocessing.LabelEncoder()
y2 = le.fit_transform(y)
print("LabelEncoder classes =", le.classes_)
# LabelEncoder classes = ['april' 'august' 'december' 'febuary' 'jan' 'july' 'june' 'march' 'may' 'november' 'october' 'september']