torch.utils.data包详解

参考:1)pytorch实现自由的数据读取-torch.utils.data的学习、2)pytorch源码分析之torch.utils.data.Dataset类和torch.utils.data.DataLoader类、3)PyTorch源码解读之torch.utils.data.DataLoader

目录:
torch.utils.data主要包括以下三个类:

  1. torch.utils.data.Dataset类

  2. torch.utils.data.sampler.Sampler类

  3. torch.utils.data.DataLoader类

torch.utils.data主要包括以下三个类:

  1. torch.utils.data.Dataset类
    class torch.utils.data.Dataset
    源码:
    class Dataset(object):
An abstract class representing a Dataset.
    All other datasets should subclass it. All subclasses should override
    ``__len__``, that provides the size of the dataset, and ``__getitem__``,
    supporting integer indexing in range from 0 to len(self) exclusive.
def __getitem__(self, index):
    raise NotImplementedError
 
def __len__(self):
    raise NotImplementedError
 
def __add__(self, other):
    return ConcatDataset([self, other])

作用: 创建数据集,有__getitem__(self, index)函数来根据索引序号获取图片和标签, 有__len__(self)函数来获取数据集的长度.
其他的数据集类必须是torch.utils.data.Dataset的子类,比如说torchvision.ImageFolder.
一个用来表示数据集的抽象类,其他所有的数据集都应该是这个类的子类,并且需要重写__len__和__getitem__。
2. torch.utils.data.sampler.Sampler类
class torch.utils.data.sampler.Sampler(data_source)
参数: data_source (Dataset) – dataset to sample from
作用: 创建一个采样器, class torch.utils.data.sampler.Sampler是所有的Sampler的基类, 其中,iter(self)函数来获取一个迭代器,对数据集中元素的索引进行迭代,len(self)方法返回迭代器中包含元素的长度.
3. torch.utils.data.DataLoader类
class torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=False, sampler=None, batch_sampler=None, num_workers=0, collate_fn=, pin_memory=False, drop_last=False, timeout=0, worker_init_fn=None)

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

  • dataset (Dataset): 加载数据的数据集
  • batch_size (int, optional): 每批加载多少个样本
  • shuffle (bool, optional): 设置为“真”时,在每个epoch对数据打乱.(默认:False)
  • sampler (Sampler, optional): 定义从数据集中提取样本的策略,返回一个样本
  • batch_sampler (Sampler, optional): like sampler, but returns a batch of indices at a time 返回一批样本. 与atch_size, shuffle, sampler和 drop_last互斥.
  • num_workers (int, optional): 用于加载数据的子进程数。0表示数据将在主进程中加载​​。(默认:0)
  • collate_fn (callable, optional): 合并样本列表以形成一个 mini-batch. # callable可调用对象
  • pin_memory (bool, optional): 如果为 True, 数据加载器会将张量复制到 CUDA 固定内存中,然后再返回它们.
  • drop_last (bool, optional): 设定为 True 如果数据集大小不能被批量大小整除的时候, 将丢掉最后一个不完整的batch,(默认:False).
  • timeout (numeric, optional): 如果为正值,则为从工作人员收集批次的超时值。应始终是非负的。(默认:0)
  • worker_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).
    pytorch读取训练集需要使用到2个类:
    (1)torch.utils.data.Dataset
    (2)torch.utils.data.DataLoader

你可能感兴趣的:(python,pytorch,深度学习,python)