按比例增加数据



我面临两个类之间的分类问题。目前我使用以下代码扩充数据集:

aug_train_data_gen = ImageDataGenerator(rotation_range=0,
height_shift_range=40,
width_shift_range=40,
zoom_range=0,
horizontal_flip=True,
vertical_flip=True, 
fill_mode='reflect',
rescale=1/255.)
aug_train_gen = aug_train_data_gen.flow_from_directory(directory=training_dir,
target_size=(96,96),
color_mode='rgb',
classes=None, # can be set to labels
class_mode='categorical',
batch_size=64,
shuffle= False #set to false if need to compare images
)

但是我认为使用增强来增加class1的数据会提高我的性能,因为目前class2的图像是class1的6倍,导致CNN倾向于将图像分类到class2。我该怎么做呢?

为了获得一个平衡的批处理,您可以使用附带的类。

在init上,你提供了一个包含多个数据集的列表。每个类一个数据集。多个数据集的数量等于类的数量。

在运行时,__ get_item __()在类中随机选择一个样本,并在类中随机选择一个样本。

最好

from torch.utils.data import Dataset
class MultipleDataset(Dataset):
"""
Choose randomly from which dataset return an item on each call to __get_item__()
"""
def __init__(self, datasets: Iterable[Dataset]) -> None:
super(MultipleDataset, self).__init__()
self.datasets = list(datasets)
assert len(self.datasets) > 0, 'datasets should not be an empty iterable'  # type: ignore[arg-type]
for d in self.datasets:
assert not isinstance(d, IterableDataset), "ConcatDataset does not support IterableDataset"
self.dataset_sizes = [len(d) for d in self.datasets]
self.num_datasets = len(self.datasets)
def __len__(self):
return max(self.dataset_sizes)
def __getitem__(self, idx):
if idx < 0:
if -idx > len(self):
raise ValueError("absolute value of index should not exceed dataset length")
idx = len(self) + idx
dataset_idx = randint(self.num_datasets)
sample_idx = idx % self.dataset_sizes[dataset_idx]
return self.datasets[dataset_idx][sample_idx]

最新更新