首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在PyTorch中定义批量大小为1的手动排序的MNIST数据集

在PyTorch中定义批量大小为1的手动排序的MNIST数据集
EN

Stack Overflow用户
提问于 2021-03-19 00:35:42
回答 2查看 340关注 0票数 1

[]:表示批次。例如,如果批处理大小为5,则批处理将类似于1,4,7,4,2。[]的长度表示批处理大小。

我想让训练集看起来像这样:

1 -> 1 -> 1 -> 1 -> 1 -> 7 -> 7 -> 7 -> 7 -> 7 -> 3 -> 3 -> 3 -> 3 -> 3 -> ...诸若此类

这意味着首先是5个1(批量= 1),其次是5个7(批量= 1),第三个是5个3(批量= 1),依此类推...

有没有人能给我个建议?

如果有人能解释如何用代码实现这一点,那将是非常有帮助的。

谢谢!:)

EN

回答 2

Stack Overflow用户

发布于 2021-03-19 05:21:15

如果您想要一个只为每个样本定义类标签的DataLoader,那么可以使用torch.data.utils.Subset类。不管它的名字是什么,它不一定需要定义数据集的子集。例如

代码语言:javascript
复制
import torch
import torchvision
import torchvision.transforms as T
from itertools import cycle

mnist = torchvision.datasets.MNIST(root='./', train=True, transform=T.ToTensor())

# not sure what "...and so on" implies, but define this list however you like
target_classes = [1, 1, 1, 1, 1, 7, 7, 7, 7, 7, 3, 3, 3, 3, 3]

# create cyclic iterators of indices for each class in MNIST
indices = dict()
for label in torch.unique(mnist.targets).tolist():
    indices[label] = cycle(torch.nonzero(mnist.targets == label).flatten().tolist())

# define the order of indices in the new mnist subset based on target_classes
new_indices = []
for t in target_classes:
    new_indices.append(next(indices[t]))

# create a Subset of MNIST based on new_indices
mnist_modified = torch.utils.data.Subset(mnist, new_indices)
dataloader = torch.utils.data.DataLoader(mnist_modified, batch_size=1, shuffle=False)

for idx, (x, y) in enumerate(dataloader):
    # training loop
    print(f'Batch {idx+1} labels: {y.tolist()}')
票数 1
EN

Stack Overflow用户

发布于 2021-03-19 06:14:10

如果您想要一个在同一个类的一行中返回五个样本的DataLoader,但又不想手动为每个索引定义类,那么您可以创建一个自定义采样器。例如

代码语言:javascript
复制
import torch
import torchvision
import torchvision.transforms as T
from itertools import cycle

class RepeatClassSampler(torch.utils.data.Sampler):
    def __init__(self, targets, repeat_count, length, shuffle=False):
        if not torch.is_tensor(targets):
            targets = torch.tensor(targets)

        self.targets = targets
        self.repeat_count = repeat_count
        self.length = length
        self.shuffle = shuffle

        self.classes = torch.unique(targets).tolist()
        self.class_indices = dict()
        for label in self.classes:
            self.class_indices[label] = torch.nonzero(targets == label).flatten() 

    def __iter__(self):
        class_index_iters = dict()
        for label in self.classes:
            if self.shuffle:
                class_index_iters[label] = cycle(self.class_indices[label][torch.randperm(len(self.class_indices))].tolist())
            else:
                class_index_iters[label] = cycle(self.class_indices[label].tolist())

        if self.shuffle:
            target_iter = cycle(self.targets[torch.randperm(len(self.targets))].tolist())
        else:
            target_iter = cycle(self.targets.tolist())

        def index_generator():
            for i in range(self.length):
                if i % self.repeat_count == 0:
                    current_class = next(target_iter)
                yield next(class_index_iters[current_class])
    
        return index_generator()

    def __len__(self):
        return self.length


mnist = torchvision.datasets.MNIST(root='./', train=True, transform=T.ToTensor())
dataloader = torch.utils.data.DataLoader(
        mnist,
        batch_size=1,
        sampler=RepeatClassSampler(
            targets=mnist.targets,
            repeat_count=5,
            length=15,      # How many total to pick from your dataset
            shuffle=True))

for idx, (x, y) in enumerate(dataloader):
    # training loop
    print(f'Batch {idx+1} labels: {y.tolist()}')
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66695251

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档