Pytorch collate_fn用法
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用法的更多相关文章
- pytorch faster_rcnn
代码地址:https://github.com/jwyang/faster-rcnn.pytorch 1.fasterRCNN.train():这个不是让网络进行训练,而是让module in tra ...
- Transformers 简介(下)
作者|huggingface 编译|VK 来源|Github Transformers是TensorFlow 2.0和PyTorch的最新自然语言处理库 Transformers(以前称为pytorc ...
- 深度学习与CV教程(8) | 常见深度学习框架介绍
作者:韩信子@ShowMeAI 教程地址:http://www.showmeai.tech/tutorials/37 本文地址:http://www.showmeai.tech/article-det ...
- Pytorch 一些函数用法
PyTorch中view的用法:https://blog.csdn.net/york1996/article/details/81949843 max用法 import torch d=torch.T ...
- 关于Pytorch的二维tensor的gather和scatter_操作用法分析
看得不明不白(我在下一篇中写了如何理解gather的用法) gather是一个比较复杂的操作,对一个2维tensor,输出的每个元素如下: out[i][j] = input[index[i][j]] ...
- [转载]PyTorch中permute的用法
[转载]PyTorch中permute的用法 来源:https://blog.csdn.net/york1996/article/details/81876886 permute(dims) 将ten ...
- Pytorch中randn和rand函数的用法
Pytorch中randn和rand函数的用法 randn torch.randn(*sizes, out=None) → Tensor 返回一个包含了从标准正态分布中抽取的一组随机数的张量 size ...
- Pytorch中nn.Conv2d的用法
Pytorch中nn.Conv2d的用法 nn.Conv2d是二维卷积方法,相对应的还有一维卷积方法nn.Conv1d,常用于文本数据的处理,而nn.Conv2d一般用于二维图像. 先看一下接口定义: ...
- PyTorch中view的用法
相当于numpy中resize()的功能,但是用法可能不太一样. 我的理解是: 把原先tensor中的数据按照行优先的顺序排成一个一维的数据(这里应该是因为要求地址是连续存储的),然后按照参数组合成其 ...
随机推荐
- windows 安装svn 要点(非安装步骤)
http://www.visualsvn.com/files/VisualSVN-Server-2.5.6.msi 下载服务端 windows2008搭建svn 1.360软件管家下载 Visua ...
- Split string every nth character?
https://stackoverflow.com/questions/9475241/split-string-every-nth-character >>> line = '12 ...
- 66)vector基础总结
基本知识: 1)vector 样子 其实就是一个动态数组: 2)vector的基本操作: 3)vector对象的默认构造 对于类 添加到 容器中 要有 拷贝构造函数---> 这个注意 ...
- 【MySQL参数】- query_cache_type
MySQL为什么要关闭查询缓存 https://blog.csdn.net/liqfyiyi/article/details/50178591 Query cache的优化方法 https://blo ...
- 用Python3生成30万条excel数据(xlsx格式)
在B/S架构的系统测试中,有时需要通过导入excel文件来生成一些数据记录,当数据量小的时候,一般不会出现什么问题,而当导入的数据量巨大时,对系统的性能就是一个考验了.为了验证系统的性能,有时需要导入 ...
- 03-string字符串和while循环
目录 03-string字符串和while循环 1. string介绍 2. 字符串的运算 3. 下标及分片 4. 格式化输出 5. f-string格式化输出用法 6. 字符串方法 7. 布尔值,空 ...
- Codeforces620E New Year Tree
挺好的一道题 Description link 给一棵树,每个点有颜色 \(c_i\) 为点权,需要实现以下两种操作: 子树修改颜色(覆盖),查询子树颜色种类 \(n \leq 4 \times 10 ...
- 【hdu6613】Squrirrel 树形DP
题意:给一个带权树,求把一条边的权值变成0,再选一个点做根,最大深度最小是多少. \(\sum n \le 10^6\) key:树形DP 题里有边权小于等于200,然而并没有什么用. 首先做出 \( ...
- Linux Man手册的使用示例
转载自:https://blog.csdn.net/ac_dao_di/article/details/54718710 Linux的命令非常多,很多人在学一个命令时,首先想到的是使用百度或者谷歌,或 ...
- iOS 直接使用16进制颜色
在做iOS开发时,一般我们会吸色,就是产品给的图我们一般会吸色,但是最近吸色时候,老大说有较大的颜色偏差,所以要求我们直接使用UI给出的额16进制颜色,你也可以搜索<RGB颜色值转换成十六进制颜 ...