keras中多标签图像的一种热编码

One hot encoding of multi label images in keras

我正在使用 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'}

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

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

对这些标签进行单热编码的最佳方法是什么,因为我们没有每个图像的具体标签数量。

如果第二列中有 set 可以使用 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.join with Series.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