【pytorch】 torch.utils.data.DataLoader用法详解

参考:
https://pytorch.org/docs/stable/data.html?highlight=torch%20utils%20data%20dataloader#torch.utils.data.DataLoader
https://blog.csdn.net/u014380165/article/details/79058479

官方函数定义:

class torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=False, sampler=None, batch_sampler=None,
                 num_workers=0, collate_fn=default_collate, pin_memory=False, drop_last=False,
                 timeout=0, worker_init_fn=None):

作用
概括:根据自定义的格式封装成Tensor。
PyTorch中数据读取的一个重要接口是torch.utils.data.DataLoader,该接口定义在dataloader.py脚本中,只要是用PyTorch来训练模型基本都会用到该接口,该接口主要用来将自定义的数据读取接口的输出或者PyTorch已有的数据读取接口的输入按照batch size封装成Tensor,后续只需要再包装成Variable即可作为模型的输入,因此该接口有点承上启下的作用。

函数说明
Data loader. Combines a dataset and a sampler, and provides an iterable over the given dataset.

The DataLoader supports both map-style and iterable-style datasets with single- or multi-process loading, customizing loading order and optional automatic batching (collation) and memory pinning.

Data loader。组合数据集和采样器,并提供给定数据集的可迭代对象。

DataLoader支持映射样式和可迭代样式的数据集,支持单进程或多进程加载、自定义加载顺序、可选的自动批处理(排序)和内存固定。

Parameters 参数

        dataset (Dataset) – dataset from which to load the data.
        要从中加载数据的数据集。

        batch_size (int, optional) – how many samples per batch to load (default: 1).
        每批次要装载多少样品 

        shuffle (bool, optional) – set to True to have the data reshuffled at every epoch (default: False).
        设置为True以使数据在每个时期都重新洗牌 

        sampler (Sampler or Iterable, optional) – defines the strategy to draw samples from the dataset. Can be any Iterable with __len__ implemented. If specified, shuffle must not be specified.
        定义从数据集中抽取样本的策略

        batch_sampler (Sampler or Iterable, optional) – like sampler, but returns a batch of indices at a time. Mutually exclusive with batch_size, shuffle, sampler, and drop_last.
        类似于采样器,但一次返回一批索引。 与batch_size,shuffle,sampler和drop_last互斥。 

        num_workers (int, optional) – how many subprocesses to use for data loading. 0 means that the data will be loaded in the main process. (default: 0)
        多少个子流程用于数据加载。 0表示将在主进程中加载数据。 (默认值:0collate_fn (callable, optional) – merges a list of samples to form a mini-batch of Tensor(s). Used when using batched loading from a map-style dataset.
        合并样本列表以形成张量的小批量。

        pin_memory (bool, optional) – If True, the data loader will copy Tensors into CUDA pinned memory before returning them. If your data elements are a custom type, or your collate_fn returns a batch that is a custom type.
		如果为True,则数据加载器在将张量返回之前将其复制到CUDA固定的内存中。 如果您的数据元素是自定义类型,或者您的collate_fn返回的是一个自定义类型的批处理

        drop_last (bool, optional) – set to True to drop the last incomplete batch, if the dataset size is not divisible by the batch size. If False and the size of dataset is not divisible by the batch size, then the last batch will be smaller. (default: False)
        如果数据集大小不能被批量大小整除,则设置为True以删除最后一个不完整的批量。 如果为False并且数据集的大小不能被批次大小整除,则最后一批将较小。 

        timeout (numeric, optional)if positive, the timeout value for collecting a batch from workers. Should always be non-negative. (default: 0)
		如果为正,则为从工作人员收集批次的超时值。 应始终为非负数。 (默认值:0worker_init_fn (callable, optional) – If not None, this will be called on each worker subprocess with the worker id (an int in [0, num_workers - 1]) as input, after seeding and before data loading. (default: None)

        prefetch_factor (int, optional, keyword-only arg) – Number of samples loaded in advance by each worker. 2 means there will be a total of 2 * num_workers samples prefetched across all workers. (default: 2)
        每个子流程预先加载的样本数。 2表示将在所有子流程中预取总共2 * num_workers个样本。 (默认值:2persistent_workers (bool, optional) – If True, the data loader will not shutdown the worker processes after a dataset has been consumed once. This allows to maintain the workers Dataset instances alive. (default: False)
		如果为True,则一次使用数据集后,数据加载器将不会关闭工作进程。 这样可以使Worker Dataset实例保持活动状态。 (默认值:False) 

使用示例

# 加载数据集,batch_size设为1,每轮epoch不打乱,只在主进程加载,不预先复制到CUDA固定的内存中
data_loader = torch.utils.data.DataLoader(
        dataset,
        batch_size=1,
        shuffle=False,
        num_workers=0,
        pin_memory=False
    )

源码:

class DataLoader(object):
"""
    Data loader. Combines a dataset and a sampler, and provides
    single- or multi-process iterators over the dataset.

    Arguments:
        dataset (Dataset): dataset from which to load the data.
        batch_size (int, optional): how many samples per batch to load
            (default: 1).
        shuffle (bool, optional): set to ``True`` to have the data reshuffled
            at every epoch (default: False).
        sampler (Sampler, optional): defines the strategy to draw samples from
            the dataset. If specified, ``shuffle`` must be False.
        batch_sampler (Sampler, optional): like sampler, but returns a batch of
            indices at a time. Mutually exclusive with batch_size, shuffle,
            sampler, and drop_last.
        num_workers (int, optional): how many subprocesses to use for data
            loading. 0 means that the data will be loaded in the main process.
            (default: 0)
        collate_fn (callable, optional): merges a list of samples to form a mini-batch.
        pin_memory (bool, optional): If ``True``, the data loader will copy tensors
            into CUDA pinned memory before returning them.
        drop_last (bool, optional): set to ``True`` to drop the last incomplete batch,
            if the dataset size is not divisible by the batch size. If ``False`` and
            the size of dataset is not divisible by the batch size, then the last batch
            will be smaller. (default: False)
        timeout (numeric, optional): if positive, the timeout value for collecting a batch
            from workers. Should always be non-negative. (default: 0)
        worker_init_fn (callable, optional): If not None, this will be called on each
            worker subprocess with the worker id as input, after seeding and before data
            loading. (default: None)
"""

    def __init__(self, dataset, batch_size=1, shuffle=False, sampler=None, batch_sampler=None,
                 num_workers=0, collate_fn=default_collate, pin_memory=False, drop_last=False,
                 timeout=0, worker_init_fn=None):
        self.dataset = dataset
        self.batch_size = batch_size
        self.num_workers = num_workers
        self.collate_fn = collate_fn
        self.pin_memory = pin_memory
        self.drop_last = drop_last
        self.timeout = timeout
        self.worker_init_fn = worker_init_fn

        if timeout < 0:
            raise ValueError('timeout option should be non-negative')

        if batch_sampler is not None:
            if batch_size > 1 or shuffle or sampler is not None or drop_last:
                raise ValueError('batch_sampler is mutually exclusive with '
                                 'batch_size, shuffle, sampler, and drop_last')

        if sampler is not None and shuffle:
            raise ValueError('sampler is mutually exclusive with shuffle')

        if self.num_workers < 0:
            raise ValueError('num_workers cannot be negative; '
                             'use num_workers=0 to disable multiprocessing.')

        if batch_sampler is None:
            if sampler is None:
                if shuffle:
                    sampler = RandomSampler(dataset)
                else:
                    sampler = SequentialSampler(dataset)
            batch_sampler = BatchSampler(sampler, batch_size, drop_last)

        self.sampler = sampler
        self.batch_sampler = batch_sampler

    def __iter__(self):
        return DataLoaderIter(self)

    def __len__(self):
        return len(self.batch_sampler)
### 回答1: `torch.utils.data.DataLoader` 是 PyTorch 中用于加载数据的一个重要类。它可以自动地将数据集分成多个批次,并在训练时以迭代器的形式提供数据。 使用方法很简单,只需要将数据集和批次大小传入 `DataLoader` 的构造函数中即可,比如: ``` from torch.utils.data import DataLoader from torchvision import datasets, transforms # 加载 MNIST 数据集 mnist_train = datasets.MNIST('mnist', train=True, download=True, transform=transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)) ])) # 使用 DataLoader 加载数据 train_loader = DataLoader(mnist_train, batch_size=64, shuffle=True) # 迭代训练数据 for data, target in train_loader: # 训练网络 pass ``` 其中 train_loader 为一个迭代器,每次调用 next() 函数即可得到一个批次的数据 你可以使用`num_workers`参数来使用多进程读取数据,可以节省读取数据时间 当然DataLoader也支持并行计算 你可以使用 `torch.utils.data.DataLoader`来创建数据加载器,并可以通过迭代器的形式访问数据 总之,`torch.utils.data.DataLoader` 是 PyTorch 中极其方便的一个类,它可以很好地管理数据的加载和批次的生成。 ### 回答2: torch.utils.data.dataloaderPyTorch中的数据加载器,用于在训练或测试模型时加载数据。它提供了一个高效的数据加载方式,能够有效地减少数据准备的时间,并且能够在训练过程中进行数据增强和预处理。 dataloader的主要功能包括数据加载、数据处理、数据批处理和数据分布式处理。它能够从数据集中逐一读取数据并对其进行处理、组合和转换,同时支持对数据进行分批处理以避免内存溢出和加快计算速度。此外,dataloader还支持在多个进程之间并行加载数据以提高效率,适用于大型数据集和高效计算的场景。 在使用dataloader时,需要指定数据集、批量大小、是否乱序等参数,以及指定数据处理函数和数据转换函数。例如,可以使用transforms模块提供的函数对图像进行裁剪、缩放和旋转,以及转换为PyTorch中的张量。最后,可以使用for循环逐个迭代数据集,利用模型进行训练或测试,同时还可以进行数据增强、数据分布式处理等操作以提高训练效果和计算效率。 总之,torch.utils.data.dataloaderPyTorch中非常重要的数据加载器,在深度学习中的应用非常广泛。它能够高效地加载和处理数据集,并且能够在训练过程中进行数据增强和预处理,是提高深度学习效率和性能的重要工具之一。 ### 回答3: torch.utils.data.dataloaderPyTorch中一个用于将数据加载器实现为Python类的模块。该模块旨在帮助数据科学家和机器学习工程师更轻松地管理和加载数据集。 torch.utils.data.dataloader的主要作用是帮助用户批量读取和处理数据,并在训练模型、评估模型和使用模型进行预测时对其进行优化。在训练神经网络时,通常需要遍历整个数据集多次,并从中随机取出一部分数据进行训练。torch.utils.data.dataloader可以帮助用户在训练过程中自动进行这些操作。 使用torch.utils.data.dataloader有许多优点。首先,该模块提供了一个简单的接口来处理批量数据,减少了繁琐的数据加载过程。其次,它可以自动为数据加载器添加多线程和批量加载机制,从而加速了数据加载过程,提高了模型训练的效率。此外,该模块提供了一些选项来自定义数据加载器的行为,使用户能够根据自己的需求轻松地定制数据加载器。 在使用torch.utils.data.dataloader时,我们需要使用一个数据集类来对数据进行封装,并将其传递给数据加载器。例如,如果我们要加载一个图像分类数据集,我们需要创建一个数据集类来加载数据,并使用这个类来加载数据集。然后,我们可以使用torch.utils.data.dataloader来对数据进行批量处理。 在使用torch.utils.data.dataloader时,我们还需要设置一些参数来配置数据加载器的行为。这些参数包括批量大小、数据并行性、数据加载机制、是否需要打乱数据集等。例如,如果我们想要使用多线程来加载数据,我们可以设置num_workers参数来指定线程数。 总之,torch.utils.data.dataloader是一个非常有用的模块,它可以帮助用户更轻松地管理和加载数据集,并自动进行批量处理和多线程处理,从而提高了模型训练的效率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值