【问题标题】:How to predict unseen data?如何预测看不见的数据?
【发布时间】:2020-01-31 21:21:29
【问题描述】:

您好,我正在练习 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 列是分类类型(国家和性别)。 模型运行良好,但在尝试针对随机输入测试模型时,它在 onehotencoding 时失败。

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'

【问题讨论】:

    标签: scikit-learn


    【解决方案1】:

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

    您应该展平您的输入列表并将其用于预测。

    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 列)。

    【讨论】:

    • 展平时出现 AttributeError: 'list' object has no attribute 'lower'
    • @ChinmayNayak 我已经编辑了我的答案。有趣的是它没有工作。 编辑: 我检查了我的旧代码,似乎我正在使用 Django 函数。我的错。但是,我的这个版本的你遍历列表的答案应该适合你。
    • 否,获取列表对象错误。 AttributeError:“列表”对象没有属性“形状”
    猜你喜欢
    • 2022-01-22
    • 2018-07-29
    • 1970-01-01
    • 2020-06-21
    • 2021-07-10
    • 2014-12-09
    • 2021-02-21
    • 2016-02-19
    • 1970-01-01
    相关资源
    最近更新 更多