【问题标题】:ValueError: Shape mismatch: if categories is an array, it has to be of shape (n_features,)ValueError:形状不匹配:如果类别是一个数组,它必须是形状(n_features,)
【发布时间】:2020-04-18 21:50:46
【问题描述】:

我创建了一个简单的代码来实现OneHotEncoder

from sklearn.preprocessing import OneHotEncoder
X = [[0, 'a'], [0, 'b'], [1, 'a'], [2, 'b']]
onehotencoder = OneHotEncoder(categories=[0])
X = onehotencoder.fit_transform(X).toarray()

我只想将名为fit_transform 的方法用于索引0X,所以它意味着[0, 0, 1, 2],就像您在X 中看到的一样。但它会导致这样的错误:

ValueError: Shape mismatch: if categories is an array, it has to be of shape (n_features,).

谁能解决这个问题?我被卡住了

【问题讨论】:

    标签: python scikit-learn spyder one-hot-encoding


    【解决方案1】:

    您需要使用ColumnTransformer 指定列索引而不是categories 参数。

    构造函数参数categories 是明确告诉不同的类别值。例如。您可以明确提供[0, 1, 2],但auto 将确定它。此外,您可以改用slice() 对象。

    from sklearn.preprocessing import OneHotEncoder
    from sklearn.compose import ColumnTransformer
    
    X = [[0, 'a'], [0, 'b'], [1, 'a'], [2, 'b']]
    
    ct = ColumnTransformer(
        [('one_hot_encoder', OneHotEncoder(categories='auto'), [0])],   # The column numbers to be transformed (here is [0] but can be [0, 1, 3])
        remainder='passthrough'                                         # Leave the rest of the columns untouched
    )
    
    X = ct.fit_transform(X)
    

    【讨论】:

      【解决方案2】:

      pandas.get_dummies() 方法也可以按以下方式进行:

      import numpy as np
      import pandas as pd
      X = np.array([[0, 'a'], [0, 'b'], [1, 'a'], [2, 'b']])
      X = np.array(pd.concat([pd.get_dummies(X[:, 0]), pd.DataFrame(X[:, 1])], axis = 1))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-05
        • 1970-01-01
        • 2021-05-22
        • 1970-01-01
        • 1970-01-01
        • 2013-06-01
        • 1970-01-01
        相关资源
        最近更新 更多