如何预测看不见的数据?

时间:2020-01-31 12:34:03

标签: scikit-learn

嗨,我正在练习ML模型,并在尝试预测看不见的数据时面临问题。 在对分类数据进行onehotencoding时出现错误。

from sklearn.preprocessing import LabelEncoder,OneHotEncoder
labelencoder_x_1 = LabelEncoder() #will encode country
X[:,1] = labelencoder_x_1.fit_transform(X[:,1])

labelencoder_x_2 = LabelEncoder() #will encode Gender
X[:,2] = labelencoder_x_2.fit_transform(X[:,2])
onehotencoder_x = OneHotEncoder(categorical_features=[1])
X= onehotencoder_x.fit_transform(X).toarray()
X = X[:,1:] 

我的X有11列,而第2列和第3列是分类类型(国家和性别)。 模型运行正常,但尝试针对随机输入测试模型时,它无法一次编码。

input = [[619], ['France'], ['Male'],   [42],   [2],    [0.0],  [1],    [1],    [1],[101348.88]]

input[1] = labelencoder_x_1.fit_transform(input[1])
input[2] = labelencoder_x_2.fit_transform(input[2])
input= onehotencoder_x.fit_transform(input).toarray()

错误:

 C:\Anaconda3\lib\site-packages\sklearn\preprocessing\_encoders.py:451: 
  DeprecationWarning: The 'categorical_features' keyword is deprecated in version 0.20 
and will be removed in 0.22. You can use the ColumnTransformer instead.
  "use the ColumnTransformer instead.", DeprecationWarning)
Traceback (most recent call last):

      File "<ipython-input-44-44a43edf17aa>", line 1, in <module>
    input= onehotencoder_x.fit_transform(input).toarray()

  File "C:\Anaconda3\lib\site-packages\sklearn\preprocessing\_encoders.py", line 624, in 
 fit_transform
    self._handle_deprecations(X)

   File "C:\Anaconda3\lib\site-packages\sklearn\preprocessing\_encoders.py", line 453, in 
_handle_deprecations
     n_features = X.shape[1]

 AttributeError: 'list' object has no attribute 'shape'

1 个答案:

答案 0 :(得分:0)

我相信这是因为您有嵌套列表。

您应该拼合输入列表,并将其用于预测。

input[1] = labelencoder_x_1.fit_transform(input[1])
input[2] = labelencoder_x_2.fit_transform(input[2])

intput = [item for sublist in input for item in sublist]

input= onehotencoder_x.fit_transform(input).toarray()

如果您有一个嵌套列表,则列表中的每个元素都将被视为需要通过fit_transform函数的项目,但是由于它是单个元素,因此与fit_transform看起来的形状不匹配为[1,10](1行10列)。