【问题标题】:Encode categorical features with multiple categories per example - sklearn每个示例使用多个类别编码分类特征 - sklearn
【发布时间】:2023-03-13 03:14:02
【问题描述】:

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

数据看起来像这样-

    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 类的方法。

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

【问题讨论】:

    标签: pandas machine-learning scikit-learn feature-extraction categorical-data


    【解决方案1】:

    This 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
    

    【讨论】:

      猜你喜欢
      • 2020-01-05
      • 1970-01-01
      • 2019-10-21
      • 2022-01-20
      • 2015-04-23
      • 2019-06-13
      • 2018-08-08
      • 2021-03-07
      • 2016-05-23
      相关资源
      最近更新 更多