针对多标签分类问题的标签数量计数错误

时间:2020-08-05 20:45:59

标签: python pandas dataframe computer-vision

我正在为一个多标签分类问题计算标签的分布。请从CSV文件中找到包含的示例数据。

filenames   labels
tt3302594.jpg   ['deer']
tt2377194.jpg   ['deer']
tt2309762.jpg   ['dog', 'deer']
tt2870808.jpg   ['cat', 'deer']
tt2551396.jpg   ['cat', 'dog', 'deer']
tt4008652.jpg   ['dog']
tt2926810.jpg   ['deer']
tt3531604.jpg   ['dog', 'deer']
tt2290739.jpg   ['cat', 'deer']

我希望绘制一个海洋图,在X轴上使用单个标签,在Y轴上使用它们的计数值。

以下是代码:

import numpy as np
import pandas as pd
import seaborn as sns
from collections import Counter

train = pd.read_csv('example.csv')    # reading the csv file
meta = pd.DataFrame(train, columns=['filenames', 'labels'])
print(f'Found {len(meta)} images')
meta.sample(9)
all_labels = [label for lbs in meta['labels'] for label in lbs]
labels_count = Counter(all_labels)
ax = sns.countplot(all_labels, order=[k for k, _ in labels_count.most_common()], log=True)
ax.set_title('Number of images with a class label')
ax.set_ylim(1E2, 1E4)
ax.set_xticklabels(ax.get_xticklabels(), rotation=90);

上面的代码,不是在计算标签中的每个字符(如“'',“ d”,“ e”,“ r”等)时,不使用类标签来计算图像的数量。

1 个答案:

答案 0 :(得分:1)

您需要使用literal_eval将列表中形成的字符串解析为真实列表(此外,对于发布的示例,y lims将使条消失,因此添加注释),

import numpy as np
import pandas as pd
import seaborn as sns
from collections import Counter
import ast

train = pd.read_csv('example.csv')    # reading the csv file
meta = pd.DataFrame(train, columns=['filenames', 'labels'])
print(f'Found {len(meta)} images')
meta.sample(9)
meta['labels'] = [ast.literal_eval(x) for x in meta['labels'].values] 
all_labels = [label for lbs in meta['labels'] for label in lbs]
labels_count = Counter(all_labels)
ax = sns.countplot(all_labels, order=[k for k, _ in labels_count.most_common()], log=True)
ax.set_title('Number of images with a class label')
# ax.set_ylim(1E2, 1E4)
ax.set_xticklabels(ax.get_xticklabels(), rotation=90);

enter image description here