【问题标题】:OneHotEncoder categories argumentOneHotEncoder 类别参数
【发布时间】:2020-03-10 07:07:31
【问题描述】:

在 sklearn 0.22 中,categorical_features 参数将被删除,因此以下代码不再可执行:

import numpy as np
from sklearn.preprocessing import OneHotEncoder

X = np.array([[1, 1], [2, 2], [1, 3]])
encoder = OneHotEncoder(categorical_features=[1], sparse=False)

print(encoder.fit_transform(X))

问题是,我如何使用类别参数实现与上述代码相同的行为,因为OneHotEncoder(categories=[[1, 2], [1, 2, 3]], sparse=False) 也会对第一列进行编码,而OneHotEncoder(categories=[[1, 2, 3]], sparse=False) 会抛出错误

【问题讨论】:

    标签: python machine-learning scikit-learn preprocessor one-hot-encoding


    【解决方案1】:

    好的,所以基本上你想对第二列 [1,2,3] 进行一次热编码,并保持第一列 [1,2,1] 为通过。在较新的 sklearn 版本中,您可以使用 ColumnTransformer 组合不同的预处理过程,如下所示:

    import numpy as np
    from sklearn.compose import ColumnTransformer
    from sklearn.preprocessing import OneHotEncoder
    
    X = np.array([[1, 1], [2, 2], [1, 3]])
    encoder = ColumnTransformer(
        [('number1', OneHotEncoder(dtype='int'), [1])],
        remainder="passthrough"
    )
    
    print(encoder.fit_transform(X))
    

    那么你就不必用类别来指定取值范围了。有关详细信息,请参阅文档。

    ColumnTransformer

    【讨论】:

      猜你喜欢
      • 2020-05-28
      • 2019-03-25
      • 2017-09-26
      • 2021-06-13
      • 2020-07-28
      • 2021-09-11
      • 1970-01-01
      • 2017-01-22
      • 2011-07-18
      相关资源
      最近更新 更多