PyTorch DataLoader 如何与 PyTorch 数据集交互以转换批次?

How does PyTorch DataLoader interact with a PyTorch dataset to transform batches?

我正在为 NLP 相关任务创建自定义数据集。

在 PyTorch custom datast tutorial 中,我们看到 __getitem__() 方法在其 returns 示例之前为转换留出了空间:

def __getitem__(self, idx):
        if torch.is_tensor(idx):
            idx = idx.tolist()

        img_name = os.path.join(self.root_dir,
                                self.landmarks_frame.iloc[idx, 0])
        image = io.imread(img_name)
       
        ### SOME DATA MANIPULATION HERE ###

        sample = {'image': image, 'landmarks': landmarks}
        if self.transform:
            sample = self.transform(sample)

        return sample

不过,这里的代码:

        if torch.is_tensor(idx):
            idx = idx.tolist()

暗示应该能够一次检索多个项目,这让我想知道:

  1. 该转换如何作用于多个项目? 以教程中的自定义转换为例。它们看起来不像可以在一次调用中应用于一批样本。

  2. 相关,DataLoader如何并行获取一批多个样本并应用所述变换,如果变换只能应用于单个样本?

来自 transforms from torchvision 的文档:

All transformations accept PIL Image, Tensor Image or batch of Tensor Images as input. Tensor Image is a tensor with (C, H, W) shape, where C is a number of channels, H and W are image height and width. Batch of Tensor Images is a tensor of (B, C, H, W) shape, where B is a number of images in the batch. Deterministic or random transformations applied on the batch of Tensor Images identically transform all the images of the batch.

这意味着您可以传递一批图像,只要符合形状,变换就会应用于整批图像。列表索引作用于数据框的 iloc,它选择单个索引或它们的列表,返回请求的子集。

  1. 该转换如何处理多个项目? 他们通过使用数据加载器处理多个项目。通过使用转换,您指定了单次数据发射应该发生什么(例如,batch_size=1)。数据加载器采用 您的 指定的 batch_size 并对火炬数据集中的 __getitem__ 方法进行 n 调用,将转换应用于发送的每个样本进入 training/validation。然后它将 n 个样本整理成从数据加载器发出的批量大小。

  2. 相关,DataLoader如何并行获取一批多个样本并应用所述变换,如果变换只能应用于单个样本?希望以上内容对您有意义。并行化由火炬数据集 class 和数据加载器完成,您在其中指定 num_workers。 Torch 将对数据集进行腌制并将其传播到所有工作人员中。