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

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

我已经创建了一个简单的代码来实现 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] 就像您在 [=13= 中看到的那样].但它会导致这样的错误:

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

谁能解决这个问题?我坚持下去

您需要使用 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)

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