Dataloader就是根据Dataset的数据类型生成的一个迭代器,可以按批(batch)的取出我们的数据进行训练,也可打乱(shuffle)数据集。下面只介绍几个常用参数:
torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=False, sampler=None,batch_sampler=None, num_workers=0, collate_fn=None, pin_memory=False,drop_last=False, timeout=0, worker_init_fn=None, multiprocessing_context=None)
dataset:Dataset类型的数据集。batchsize:每个bacth要加载的样本数,默认为1。shuffle:在每个epoch中对整个数据集的顺序进行打乱,默认为False。sample:定义从数据集中加载数据所采用的策略,如果指定的话,shuffle必须为False;torch.utils.data下面有几种采样方法比如RandomSampler,可以传入这些方法的实例。
num_workers:表示开启多少个线程数去加载你的数据,默认为0,代表只使用主进程。collate_fn:可以理解为对batch操作的函数,可以自定义化batch。def collate_fn(batch):"""Custom collate fn for dealing with batches of images that have a differentnumber of associated object annotations (bounding boxes).Arguments:batch: (tuple) A tuple of tensor images and lists of annotationsReturn:A tuple containing:1) (tensor) batch of images stacked on their 0 dim2) (list of tensors) annotations for a given image are stacked on0 dim"""
pin_memory:表示要将load进来的数据是否要拷贝到pin_memory区中,其表示生成的Tensor数据是属于内存中的锁页内存区,这样将Tensor数据转义到GPU中速度就会快一些,默认为False。drop_last:当你的整个数据长度不能够整除你的batchsize,选择是否要丢弃最后一个不完整的batch,默认为False。注:这里简单科普下pin_memory,通常情况下,数据在内存中要么以锁页的方式存在,要么保存在虚拟内存(磁盘)中,设置为True后,数据直接保存在锁页内存中,后续直接传入cuda;否则需要先从虚拟内存中传入锁页内存中,再传入cuda,这样就比较耗时了,但是对于内存的大小要求比较高。
