首页 > 解决方案 > __getitem__ 的 idx 如何在 PyTorch 的 DataLoader 中工作?

问题描述

我目前正在尝试使用 PyTorch 的 DataLoader 处理数据以输入我的深度学习模型,但面临一些困难。

我需要的数据是 shape (minibatch_size=32, rows=100, columns=41)__getitem__我编写的自定义类中的代码Dataset如下所示:

def __getitem__(self, idx):
    x = np.array(self.train.iloc[idx:100, :])
    return x

我这样写的原因是因为我希望 DataLoader(100, 41)一次处理形状的输入实例,我们有 32 个这样的单个实例。

但是,我注意到与我最初的看法相反,idxDataLoader 传递给函数的参数不是连续的(这很重要,因为我的数据是时间序列数据)。例如,打印这些值给了我这样的东西:

idx = 206000
idx = 113814
idx = 80597
idx = 3836
idx = 156187
idx = 54990
idx = 8694
idx = 190555
idx = 84418
idx = 161773
idx = 177725
idx = 178351
idx = 89217
idx = 11048
idx = 135994
idx = 15067

这是正常行为吗?我发布这个问题是因为返回的数据批次不是我最初想要的。

在使用 DataLoader 之前,我用来预处理数据的原始逻辑是:

  1. 从文件中读取txt数据csv
  2. 计算数据中有多少批次并相应地对数据进行切片。例如,由于一个输入实例是有形状(100, 41)的,其中 32 个形成一个 minibatch,我们通常最终得到大约 100 个左右的批次,并相应地重新调整数据。
  3. 一个输入是 shape (32, 100, 41)

我不确定我应该如何处理 DataLoader 挂钩方法。非常感谢任何提示或建议。提前致谢。

标签: pythonpytorchdataloader

解决方案


定义 idx 的是sampleror batch_sampler,正如您在此处看到的(开源项目是您的朋友)。在这段代码sampler(和注释/文档字符串)中,您可以看到和之间的区别batch_sampler。如果你看这里,你会看到索引是如何选择的:

def __next__(self):
    index = self._next_index()

# and _next_index is implemented on the base class (_BaseDataLoaderIter)
def _next_index(self):
    return next(self._sampler_iter)

# self._sampler_iter is defined in the __init__ like this:
self._sampler_iter = iter(self._index_sampler)

# and self._index_sampler is a property implemented like this (modified to one-liner for simplicity):
self._index_sampler = self.batch_sampler if self._auto_collation else self.sampler

注意这是_SingleProcessDataLoaderIter实现;你可以在_MultiProcessingDataLoaderIter 这里找到(ofc,使用哪一个取决于num_workers值,你可以在这里看到)。回到采样器,假设您的数据集不是_DatasetKind.Iterable并且您没有提供自定义采样器,这意味着您正在使用(dataloader.py#L212-L215):

if shuffle:
    sampler = RandomSampler(dataset)
else:
    sampler = SequentialSampler(dataset)

if batch_size is not None and batch_sampler is None:
    # auto_collation without custom batch_sampler
    batch_sampler = BatchSampler(sampler, batch_size, drop_last)

让我们看一下默认的 BatchSampler 是如何构建批次的

def __iter__(self):
    batch = []
    for idx in self.sampler:
        batch.append(idx)
        if len(batch) == self.batch_size:
            yield batch
            batch = []
    if len(batch) > 0 and not self.drop_last:
        yield batch

非常简单:它从采样器获取索引,直到达到所需的 batch_size。

现在的问题是“__getitem__ 的 idx 如何在 PyTorch 的 DataLoader 中工作?” 可以通过查看每个默认采样器的工作方式来回答。

class SequentialSampler(Sampler):
    def __init__(self, data_source):
        self.data_source = data_source

    def __iter__(self):
        return iter(range(len(self.data_source)))

    def __len__(self):
        return len(self.data_source)
def __iter__(self):
    n = len(self.data_source)
    if self.replacement:
        return iter(torch.randint(high=n, size=(self.num_samples,), dtype=torch.int64).tolist())
    return iter(torch.randperm(n).tolist())

因此,由于您没有提供任何代码,我们只能假设:

  1. shuffle=True在 DataLoader中使用
  2. 您正在使用自定义采样器
  3. 您的数据集是_DatasetKind.Iterable

推荐阅读