By default, Dataloader use collate_fn method to pack a series of images and target as tensors (first dimension of tensor is batch size). The default collate_fn expects all the images in a batch to have the same size because it uses torch.stack() to pack the images. If the images provided by Dataset have variable size, you have to provide your custom collate_fn. A simple example is shown below:

 # a simple custom collate function, just to show the idea

 # `batch` is a list of tuple where first element is image tensor and

 # second element is corresponding label

 def my_collate(batch):
data = [item[0] for item in batch] # just form a list of tensor target = [item[1] for item in batch]
target = torch.LongTensor(target)
return [data, target]

Reference:   Writing Your Own Custom Dataset for Classification in PyTorch

By default, torch stacks the input image to from a tensor of size N*C*H*W, so every image in the batch must have the same height and width. In order to load a batch with variable size input image, we have to use our own collate_fn which is used to pack a batch of images.

For image classification, the input to collate_fn is a list of with size batch_size. Each element is a tuple where the first element is the input image(a torch.FloatTensor) and the second element is the image label which is simply an int. Because the samples in a batch have different size, we can store these samples in a list ans store the corresponding labels in torch.LongTensor. Then we put the image list and the label tensor into a list and return the result.

here is a very simple snippet to demonstrate how to write a custom collate_fn:

 import torch
from torch.utils.data import DataLoader
from torchvision import transforms
import torchvision.datasets as datasets
import matplotlib.pyplot as plt # a simple custom collate function, just to show the idea
def my_collate(batch):
data = [item[0] for item in batch]
target = [item[1] for item in batch]
target = torch.LongTensor(target)
return [data, target] def show_image_batch(img_list, title=None):
num = len(img_list)
fig = plt.figure()
for i in range(num):
ax = fig.add_subplot(1, num, i+1)
ax.imshow(img_list[i].numpy().transpose([1,2,0]))
ax.set_title(title[i]) plt.show() # do not do randomCrop to show that the custom collate_fn can handle images of different size
train_transforms = transforms.Compose([transforms.Scale(size = 224),
transforms.ToTensor(),
]) # change root to valid dir in your system, see ImageFolder documentation for more info
train_dataset = datasets.ImageFolder(root="/hd1/jdhao/toyset",
transform=train_transforms) trainset = DataLoader(dataset=train_dataset,
batch_size=4,
shuffle=True,
collate_fn=my_collate, # use custom collate function here
pin_memory=True) trainiter = iter(trainset)
imgs, labels = trainiter.next() # print(type(imgs), type(labels))
show_image_batch(imgs, title=[train_dataset.classes[x] for x in labels])

Reference:    How to create a dataloader with variable-size input

Dataloader的测试用例:

 import torch
import torch.utils.data as Data
import numpy as np test = np.array([0,1,2,3,4,5,6,7,8,9,10,11]) inputing = torch.tensor(np.array([test[i:i + 3] for i in range(10)]))
target = torch.tensor(np.array([test[i:i + 1] for i in range(10)])) torch_dataset = Data.TensorDataset(inputing,target)
batch = 3 loader = Data.DataLoader(
dataset=torch_dataset,
batch_size=batch, # 批大小
# 若dataset中的样本数不能被batch_size整除的话,最后剩余多少就使用多少
collate_fn=lambda x:(
torch.cat(
[x[i][j].unsqueeze(0) for i in range(len(x))], 0
).unsqueeze(0) for j in range(len(x[0]))
)
) for (i,j) in loader:
print(i)
print(j)

Reference: DataLoader的collate_fn参数

pytorch 读取变长数据

https://zhuanlan.zhihu.com/p/60129684

Pytorch collate_fn用法的更多相关文章

  1. pytorch faster_rcnn

    代码地址:https://github.com/jwyang/faster-rcnn.pytorch 1.fasterRCNN.train():这个不是让网络进行训练,而是让module in tra ...

  2. Transformers 简介(下)

    作者|huggingface 编译|VK 来源|Github Transformers是TensorFlow 2.0和PyTorch的最新自然语言处理库 Transformers(以前称为pytorc ...

  3. 深度学习与CV教程(8) | 常见深度学习框架介绍

    作者:韩信子@ShowMeAI 教程地址:http://www.showmeai.tech/tutorials/37 本文地址:http://www.showmeai.tech/article-det ...

  4. Pytorch 一些函数用法

    PyTorch中view的用法:https://blog.csdn.net/york1996/article/details/81949843 max用法 import torch d=torch.T ...

  5. 关于Pytorch的二维tensor的gather和scatter_操作用法分析

    看得不明不白(我在下一篇中写了如何理解gather的用法) gather是一个比较复杂的操作,对一个2维tensor,输出的每个元素如下: out[i][j] = input[index[i][j]] ...

  6. [转载]PyTorch中permute的用法

    [转载]PyTorch中permute的用法 来源:https://blog.csdn.net/york1996/article/details/81876886 permute(dims) 将ten ...

  7. Pytorch中randn和rand函数的用法

    Pytorch中randn和rand函数的用法 randn torch.randn(*sizes, out=None) → Tensor 返回一个包含了从标准正态分布中抽取的一组随机数的张量 size ...

  8. Pytorch中nn.Conv2d的用法

    Pytorch中nn.Conv2d的用法 nn.Conv2d是二维卷积方法,相对应的还有一维卷积方法nn.Conv1d,常用于文本数据的处理,而nn.Conv2d一般用于二维图像. 先看一下接口定义: ...

  9. PyTorch中view的用法

    相当于numpy中resize()的功能,但是用法可能不太一样. 我的理解是: 把原先tensor中的数据按照行优先的顺序排成一个一维的数据(这里应该是因为要求地址是连续存储的),然后按照参数组合成其 ...

随机推荐

  1. ZJNU 2136 - 会长的正方形

    对于n*m网格 取min(n,m)作为最大的正方形边长 则答案可以表示成 s=1~min(n,m) 对于一个s*s的正方形 用oblq数组储存有多少四个角都在这个正方形边上的正方形 以4*4为例 除了 ...

  2. linux(centos 7)安装及使用yum

    yum介绍: Yum(全称为 Yellow dog Updater, Modified)是一个在Fedora和RedHat以及CentOS中的Shell前端软件包管理器.基于RPM包管理,能够从指定的 ...

  3. Android开发学习3

    学习内容: 1.复选框CheckBox 2.ImageView & 使用第三方库加载网络图片 3.列表视图ListView 4.网格视图GridView 5.ScrollView & ...

  4. python学习笔记(26)-request模块

    python学习笔记 #requests import requests #from class_005.http_resuest import HttpRequest login_url = &qu ...

  5. VUEJS文件扩展名esm.js和common.js是什么意思

    vue.js : vue.js则是直接用在<script>标签中的,完整版本,直接就可以通过script引用. vue.common.js :预编译调试时,CommonJS规范的格式,可以 ...

  6. MySQL_语句

    一.基础 1.说明:创建数据库CREATE DATABASE database-name 2.说明:删除数据库drop database dbname 3.说明:备份sql server--- 创建 ...

  7. VScode中Python的交互式命令环境使用笔记

    前言 时间比较久了,忘记了具体配置了,不讲搭建了,提供参https://www.zhihu.com/question/49799276,或自行谷歌,常用的插件Python和Code Runner. 本 ...

  8. MRP自动运算设置

    1.执行计划-删除老的调度计划: 2.运算日志-清除冲突: 3.MRP计划运算向导,清除预留: 4.创建MRP凌晨调度任务,名称自己修改: 5.创建完成: 6.设置消息通知:

  9. certutil

    计算摘要 certutil -hashfile inst.ini MD2 certutil -hashfile inst.ini MD5 certutil -hashfile inst.ini SHA ...

  10. 吴裕雄--天生自然python学习笔记:python 用pygame模块检测键盘事件和鼠标事件

    用户可通过键盘输入来操控游戏中角色的运动,取得键盘事件的方法有以下两种 : 常用的按键与键盘常数对应表 : 按下右箭头键,蓝色小球会 向 右移动:按住右箭头键不放 , 球体会快速 向 右移 动, 若到 ...