将自定义PyTorch数据集拆分为训练加载器和验证加载器:即使拆分了数据集,两者的长度也相同?

时间:2020-07-25 18:44:36

标签: python validation pytorch mnist dataloader

我正在尝试将一个Pytorch自定义数据集(MNIST)分为训练集和验证集,如下所示:

def get_train_valid_splits(data_dir,
                           batch_size,
                           random_seed=1,
                           valid_size=0.2,
                           shuffle=True,
                           num_workers=4,
                           pin_memory=False):

    normalize = transforms.Normalize((0.1307,), (0.3081,))  # MNIST

    # define transforms
    valid_transform = transforms.Compose([
            transforms.ToTensor(),
            normalize
        ])

        train_transform = transforms.Compose([
            transforms.ToTensor(),
            normalize
        ])

    # load the dataset
    train_dataset = datasets.MNIST(root=data_dir, train=True,
                download=True, transform=train_transform)

    valid_dataset = datasets.MNIST(root=data_dir, train=True,
                download=True, transform=valid_transform)

    dataset_size = len(train_dataset)
    indices = list(range(dataset_size))
    split = int(np.floor(valid_size * dataset_size))

    
    if shuffle == True:
        np.random.seed(random_seed)
        np.random.shuffle(indices)
    

    train_idx, valid_idx = indices[split:], indices[:split]

    train_sampler = sampler.SubsetRandomSampler(train_idx)
    valid_sampler = sampler.SubsetRandomSampler(valid_idx)

    print(len(train_sampler))
    print(len(valid_sampler))

    train_loader = torch.utils.data.DataLoader(train_dataset,
                    batch_size=batch_size, sampler=train_sampler,
                    num_workers=num_workers, pin_memory=pin_memory)

    valid_loader = torch.utils.data.DataLoader(valid_dataset,
                    batch_size=batch_size, sampler=valid_sampler,
                    num_workers=num_workers, pin_memory=pin_memory)

    print(len(train_loader.dataset))
    print(len(valid_loader.dataset))

    return (train_loader, valid_loader)

调用该函数后,我注意到样本的索引结果看起来正确,分别为48000和12000:

print(len(train_sampler))
print(len(valid_sampler))

但是,当我查看与train_loader和valid_loader相关联的数据集的长度时:

print(len(train_loader.dataset))
print(len(valid_loader.dataset))

两者的长度相同:60000!知道这里发生了什么吗?为什么即使我按索引清楚地将它赋予两者相同的长度?

1 个答案:

答案 0 :(得分:0)

这是因为数据加载器不会修改传递给它的数据集,而是在您尝试通过迭代访问数据时将诸如批大小,采样器等内容“应用于”数据。问题是您正在使用len(loader.dataset),它确实提供了所提供的数据集的长度而没有修改,而您确实想要len(loader)时,它是“应用”批处理大小之后的数据集长度和采样器。

import torch
import numpy as np

dataset = np.random.rand(100,200)
sampler = torch.utils.data.SubsetRandomSampler(list(range(70)))

loader = torch.utils.data.DataLoader(dataset, sampler=sampler)
print(len(loader)) 
>>> 70
print(len(loader.dataset))
>>> 100

注意: len的结果将受批量大小的影响:

# with batch size
loader = torch.utils.data.DataLoader(dataset, sampler=sampler, batch_size=2)
print(len(loader)) 
>>> 35
print(len(loader.dataset))
>>> 100