【问题标题】:Bad input shape while training a prediction model训练预测模型时输入形状错误
【发布时间】:2019-10-20 01:42:44
【问题描述】:

我用下面的代码用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)

我需要做什么来修复这个错误?

【问题讨论】:

    标签: python-3.x numpy valueerror


    【解决方案1】:

    没有必要对您正在执行的y 执行reshape()。以下就足够了。

    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']
    

    【讨论】:

    • 如果我不重新整形,它会引发以下错误:ValueError: Expected 2D array, got 1D array instead: array=[ 4 3 7 0 8 6 5 1 11 10 9 2]。如果您的数据具有单个特征,则使用 array.reshape(-1, 1) 重塑您的数据,如果它包含单个样本,则使用 array.reshape(1, -1)。
    • 我已经分享了上面运行良好的代码。你能分享你的完整代码吗?
    猜你喜欢
    • 2017-05-29
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多