【问题标题】:Encoding with OneHotEncoder使用 OneHotEncoder 编码
【发布时间】:2020-04-27 11:20:48
【问题描述】:

我正在尝试使用 scikitlearn 的 OneHotEncoder 对数据进行预处理。显然,我做错了什么。这是我的示例程序:

from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.compose import ColumnTransformer


cat = ['ok', 'ko', 'maybe', 'maybe']


label_encoder = LabelEncoder()
label_encoder.fit(cat)


cat = label_encoder.transform(cat)

# returns [2 0 1 1], which seams good.
print(cat)

ct = ColumnTransformer(transformers=[('encoder', OneHotEncoder(), [0])], remainder='passthrough')

res = ct.fit_transform([cat])

print(res)

最终结果:[[1.0 0 1 1]]

预期结果:类似于:

[
 [ 1 0 0 ]
 [ 0 0 1 ]
 [ 0 1 0 ]
 [ 0 1 0 ]
]

有人能指出我缺少什么吗?

【问题讨论】:

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


    【解决方案1】:

    您可以考虑使用 numpy 和 MultiLabelBinarizer。

    import numpy as np
    from sklearn.preprocessing import MultiLabelBinarizer
    
    cat = np.array([['ok', 'ko', 'maybe', 'maybe']])
    
    m = MultiLabelBinarizer()
    print(m.fit_transform(cat.T))
    

    如果您仍想坚持自己的解决方案。你只需要更新如下:

    # because of it still a row, not a column
    # res = ct.fit_transform([cat])  => remove this
    
    # it should works
    res = ct.fit_transform(np.array([cat]).T)
    
    Out[2]:
    array([[0., 0., 1.],
           [1., 0., 0.],
           [0., 1., 0.],
           [0., 1., 0.]])
    

    【讨论】:

    • OneHotEncoder(dtype=int) 获取正确的返回数据类型
    猜你喜欢
    • 2019-02-25
    • 2016-02-24
    • 2023-03-09
    • 2017-08-01
    • 1970-01-01
    • 2020-12-23
    • 2020-03-16
    • 2020-04-08
    • 1970-01-01
    相关资源
    最近更新 更多