小编典典

如何对一个变长特征进行热编码?

python

给出了可变长度特征的列表:

features = [
    ['f1', 'f2', 'f3'],
    ['f2', 'f4', 'f5', 'f6'],
    ['f1', 'f2']
]

每个样本具有不同数量的功能,并且该功能dtype已经str并且很热门。

为了使用sklearn的特征选择实用程序,我必须将转换features为2D数组,如下所示:

    f1  f2  f3  f4  f5  f6
s1   1   1   1   0   0   0
s2   0   1   0   1   1   1
s3   1   1   0   0   0   0

如何通过sklearn或numpy实现它?


阅读 145

收藏
2020-12-20

共1个答案

小编典典

您可以使用scikit中存在的MultiLabelBinarizer专门用于执行此操作。

您的示例代码:

features = [
            ['f1', 'f2', 'f3'],
            ['f2', 'f4', 'f5', 'f6'],
            ['f1', 'f2']
           ]
from sklearn.preprocessing import MultiLabelBinarizer
mlb = MultiLabelBinarizer()
new_features = mlb.fit_transform(features)

输出:

array([[1, 1, 1, 0, 0, 0],
       [0, 1, 0, 1, 1, 1],
       [1, 1, 0, 0, 0, 0]])

它也可以与其他feature_selection实用程序一起在管道中使用。

2020-12-20