首页 > 解决方案 > 每个示例使用多个类别编码分类特征 - sklearn

问题描述

我正在研究一个包含流派作为特征的电影数据集。数据集中的示例可能同时属于多个流派。因此,它们包含流派标签列表。

数据看起来像这样——

    movieId                                         genres
0        1  [Adventure, Animation, Children, Comedy, Fantasy]
1        2                     [Adventure, Children, Fantasy]
2        3                                  [Comedy, Romance]
3        4                           [Comedy, Drama, Romance]
4        5                                           [Comedy]

我想对这个特征进行矢量化。我已经尝试过LabelEncoderOneHotEncoder,但它们似乎无法直接处理这些列表。

我可以手动对其进行矢量化,但我还有其他包含太多类别的类似功能。对于那些我更喜欢使用FeatureHasher的方式类的方法。

有没有办法让这些编码器类在这样的特性上工作?或者有没有更好的方法来表示这样一个特征,这将使编码更容易?我很乐意欢迎任何建议。

标签: pandasmachine-learningscikit-learnfeature-extractioncategorical-data

解决方案


这个 SO question有一些令人印象深刻的答案。在您的示例数据中,Teoretic 的最后一个答案(使用sklearn.preprocessing.MultiLabelBinarizer)比 Paulo Alves 的解决方案快 14 倍(两者都比接受的答案快!):

from sklearn.preprocessing import MultiLabelBinarizer
mlb = MultiLabelBinarizer()
encoded = pd.DataFrame(mlb.fit_transform(df['genres']), columns=mlb.classes_, index=df.index)
result = pd.concat([df['movieId'], encoded], axis=1)

# Increase max columns to print the entire resulting DataFrame
pd.options.display.max_columns = 50
result
   movieId  Adventure  Animation  Children  Comedy  Drama  Fantasy  Romance
0        1          1          1         1       1      0        1        0
1        2          1          0         1       0      0        1        0
2        3          0          0         0       1      0        0        1
3        4          0          0         0       1      1        0        1
4        5          0          0         0       1      0        0        0

推荐阅读