Pytorch DataLoader-选择类STL10数据集

时间:2018-07-14 02:56:44

标签: pytorch torch torchvision

是否可以仅在PyTorch torchvision的STL10数据集中的class = 0的地方拉?我可以循环检查它们,但需要接收一批0级图像

# STL10 dataset
train_dataset = torchvision.datasets.STL10(root='./data/',
                                           transform=transforms.Compose([
                                               transforms.Grayscale(),
                                               transforms.ToTensor()
                                           ]),
                                           split='train',
                                           download=True)


# Data loader
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
                                           batch_size=batch_size, 
                                           shuffle=True)

for i, (images, labels) in enumerate(train_loader):
    if labels[0] == 0:...

根据iacolippo的答案进行编辑-现在可以运行:

# Set params
batch_size = 25
label_class = 0   # only airplane images

# Return only images of certain class (eg. airplanes = class 0)
def get_same_index(target, label):
    label_indices = []

    for i in range(len(target)):
        if target[i] == label:
            label_indices.append(i)

    return label_indices

# STL10 dataset
train_dataset = torchvision.datasets.STL10(root='./data/',
                                           transform=transforms.Compose([
                                               transforms.Grayscale(),
                                               transforms.ToTensor()
                                           ]),
                                           split='train',
                                           download=True)

# Get indices of label_class
train_indices = get_same_index(train_dataset.labels, label_class)

# Data loader
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
                                           batch_size=batch_size,
                                           sampler=torch.utils.data.sampler.SubsetRandomSampler(train_indices))

1 个答案:

答案 0 :(得分:1)

如果您只想从一个类中获取样本,则可以从Dataset实例中获取类似类的样本索引,例如

def get_same_index(target, label):
    label_indices = []

    for i in range(len(target)):
        if target[i] == label:
            label_indices.append(i)

    return label_indices

然后您可以使用SubsetRandomSampler仅从一个类别的索引列表中抽取样本

torch.utils.data.sampler.SubsetRandomSampler(indices)