【问题标题】:One hot encoding of multi label images in keraskeras中多标签图像的一种热编码
【发布时间】:2020-01-16 22:33:23
【问题描述】:

我正在使用 PASCAL VOC 2012 数据集进行图像分类。一些图像具有多个标签,其中一些具有单个标签,如下所示。

    0  2007_000027.jpg               {'person'}
    1  2007_000032.jpg  {'aeroplane', 'person'}
    2  2007_000033.jpg            {'aeroplane'}
    3  2007_000039.jpg            {'tvmonitor'}
    4  2007_000042.jpg                {'train'}

我想对这些标签进行 one-hot 编码来训练模型。但是,我不能使用 keras.utils.to_categorical,因为这些标签不是整数,而且 pandas.get_dummies 没有给我预期的结果。 get_dummies 给出了如下不同的类别,即将每个唯一的标签组合作为一个类别。

 {'aeroplane', 'bus', 'car'}  {'aeroplane', 'bus'}  {'tvmonitor', 'sofa'}  {'tvmonitor'} ...

对这些标签进行一次热编码的最佳方法是什么,因为我们没有为每张图像指定特定数量的标签。

【问题讨论】:

    标签: python pandas keras one-hot-encoding multilabel-classification


    【解决方案1】:

    如果第二列中有sets,则可以使用MultiLabelBinarizer

    print (df)
                     a                        b
    0  2007_000027.jpg               {'person'}
    1  2007_000032.jpg  {'aeroplane', 'person'}
    2  2007_000033.jpg            {'aeroplane'}
    3  2007_000039.jpg            {'tvmonitor'}
    4  2007_000042.jpg                {'train'}
    

    from sklearn.preprocessing import MultiLabelBinarizer
    
    mlb = MultiLabelBinarizer()
    df = pd.DataFrame(mlb.fit_transform(df['b']),columns=mlb.classes_)
    print (df)
       aeroplane  person  train  tvmonitor
    0          0       1      0          0
    1          1       1      0          0
    2          1       0      0          0
    3          0       0      0          1
    4          0       0      1          0
    

    Series.str.joinSeries.str.get_dummies,但在大型DataFrame 中应该更慢:

    df = df['b'].str.join('|').str.get_dummies()
    print (df)
    
       aeroplane  person  train  tvmonitor
    0          0       1      0          0
    1          1       1      0          0
    2          1       0      0          0
    3          0       0      0          1
    4          0       0      1          0
    

    【讨论】:

    • 我不知道我哪里出错了,我使用了你提到的 MultiLabelBinarizer,但是我得到了这样的类 ' , a b c d e f g h i k l m n o p r s t u v w y { }
    • @Sree - 我知道有什么问题,没有集合,只有字符串,所以在解决方案之前使用import ast df['b'] = df['b'].apply(ast.literal_eval)
    • @Sree - 或使用df = df['b'].str.strip("{}").str.get_dummies(', ').rename(columns=lambda x: x.strip("'"))
    • 节省了我很多时间。
    猜你喜欢
    • 1970-01-01
    • 2018-11-04
    • 2018-12-25
    • 1970-01-01
    • 2022-06-21
    • 1970-01-01
    • 2016-10-15
    相关资源
    最近更新 更多