2

在 PyTorch 中对 CIFAR10 进行分类时,通常有 50,000 个训练样本和 10,000 个测试样本。但是,如果我需要创建一个验证集,我可以通过将训练集拆分为 40000 个训练样本和 10000 个验证样本来实现。我使用了以下代码

train_transform = transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5))])
test_transform = transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5))])

cifar_train_L = CIFAR10('./data',download=True, train= True, transform = train_transform)
cifar_test = CIFAR10('./data',download=True, train = False, transform= test_transform) 

train_size = int(0.8*len(cifar_training))
val_size = len(cifar_training) - train_size
cifar_train, cifar_val = torch.utils.data.random_split(cifar_train_L,[train_size,val_size])

train_dataloader = torch.utils.data.DataLoader(cifar_train, batch_size= BATCH_SIZE, shuffle= True, num_workers=2)
test_dataloader = torch.utils.data.DataLoader(cifar_test,batch_size= BATCH_SIZE, shuffle= True, num_workers= 2)
val_dataloader = torch.utils.data.DataLoader(cifar_val,batch_size= BATCH_SIZE, shuffle= True, num_workers= 2)

通常,在 PyTorch 中扩充数据时,在 transforms.Compose函数下会使用不同的扩充过程(即,transforms.RandomHorizo​​ntalFlip())。但是,如果我在拆分训练集和验证集之前使用这些增强过程,则增强数据也将包含在验证集中。有什么办法,我可以解决这个问题吗?

简而言之,我想将训练数据集手动拆分为训练集和验证集,并将数据增强技术用于新的训练集。

4

1 回答 1

2

您可以手动覆盖transforms数据集的:

cifar_train, cifar_val = torch.utils.data.random_split(cifar_train_L,[train_size,val_size])
cifar_val.transforms = test_transform 
于 2019-11-04T07:08:14.390 回答