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. Aras Innovator时间验证

    //方法名:bcs_Nexteer_CheckTime //功能描述:开始和结束日期对比 //原作者:joe //创建时间:20141226 //版权所有(C)JOE.FAN //debugger; ...

  2. Xcode中SVN不能提交.a及其他文件

    Xcode默认忽略的.a 文件.所以无法提交到svn服务器,但是很多第三方的库都有.a文件.所以还是必须提交到服务器. 搜索了一下解决方案: http://wpt205.blog.163.com/bl ...

  3. PAT Advanced 1097 Deduplication on a Linked List (25) [链表]

    题目 Given a singly linked list L with integer keys, you are supposed to remove the nodes with duplica ...

  4. 洛谷 P3371 【模板】单源最短路径(弱化版)(dijkstra邻接链表)

    题目传送门 解题思路: 传送门 AC代码: #include<iostream> #include<cstdio> #include<cstring> using ...

  5. 吴裕雄--天生自然 JAVA开发学习:多态

    Parent p = new Child(); public class Test { public static void main(String[] args) { show(new Cat()) ...

  6. D - Daydreaming Stockbroker Gym - 101550D

    题目链接:http://codeforces.com/gym/101550/attachments 总的来说就是要: 极大值卖出,极小值买入, 再加上端点时的特判. 还有就是会有连续几天股票价格相同的 ...

  7. TPO5-1 Minerals and plants

    Only recently have investigators considered using these plants to clean up soil and waste sites that ...

  8. Java字符串替换函数replace、replaceFirst、replaceAll

    一.replace(String old,String new) 功能:将字符串中的所有old子字符串替换成new字符串 示例 String s="Hollow world!"; ...

  9. 【转】Linux服务器命令行模式安装Matlab2014a

    转自http://www.aichengxu.com/diannao/39100.htm 0.下载安装包  下载Matlab2014a for Linux安装包的ISO镜像文件 将下载好的iso文件挂 ...

  10. linux版本neo4j安装配置教程

    https://blog.csdn.net/weixin_44293236/article/details/89467489