python - 找到平衡的样本数量
问题描述
我有一个由文件夹中的多个文本文件组成的注释数据集。我有超过 100000 个文本样本。文件夹结构如下所示
annotation/
....Sample0.txt
....Sample1.txt
....Sample2.txt
....
....
....Sample100000.txt
每个文本文件如下所示:
cat 0.00 0 0.00 50 33 44 45
dog 0.00 0 0.00 60 10 82 98
beer 0.00 0 0.00 90 50 49 52
每个文件中的第一个单词包含类。
我编写了一个脚本,通过提及文件的百分比来给出每个类的类数。
import glob
from collections import Counter
path = 'annotations/'
files = glob.glob(f'{path}*.txt')
words =[]
filePerc = len(files)*80//100 # get only 80% of data from the folder
for i in range(filePerc):
f = open(files[i],'r')
for line in f:
words.append(line.split()[0])
class_count = Counter(words)
print("Number of samples :",filePerc)
print("Class :",class_count)
这给了我如下输出 - 例如:
Number of samples :100
Class : Counter({'cat': 40, 'dog': 14, 'beer': 5, 'lion':25, 'deer':16})
但是,该类未正确分配。
我想要实现的是,我想从数据集中选择 N% 的样本,而那些N%的部分应该在每个类中具有平衡的样本数。但我不知道该怎么做。