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中的数据按照行优先的顺序排成一个一维的数据(这里应该是因为要求地址是连续存储的),然后按照参数组合成其 ...
随机推荐
- Python列表中去重的多种方法
怎么快速的对列表进行去重呢,去重之后原来的顺序会不会改变呢? 去重之后顺序会改变 set去重 列表去重改变原列表的顺序了 l1 = [1,4,4,2,3,4,5,6,1] l2 = list(set( ...
- springboot的配置文件说明
1.以servlet的方式启动SpringBoot 正常情况下要复制代码到tomcat去启动,但springboot内置tomcat了,配置好就可以直接run方法直接运行. 2.直接run运行
- 01 语言基础+高级:1-6 集合_day03【List、Set、Collections工具类】
day03 [List.Set.数据结构.Collections] 主要内容 数据结构 List集合 Set集合 Collections 第一章 数据结构 2.1 数据结构有什么用 我们将常见的数据结 ...
- 03 Mybatis:01.Mybatis课程介绍及环境搭建&&02.Mybatis入门案例
mybatis框架共四天第一天:mybatis入门 mybatis的概述 mybatis的环境搭建 mybatis入门案例 -------------------------------------- ...
- php 接口中常用的aes加密
<?php /** * Aes 对称加密 */ class Aes { public $key; public function __construct($key){ $this->key ...
- 4. 监控利器nagios手把手企业级实战第三部
1.nagios图形监控显示和管理服务器 虽然能显示,能报警.但是我们企业工作中需要一个历史趋势图. nagios只开放核心,插件是单独的形式,图像也一样,是插件或者整合的方式.所以可能看起来很多,这 ...
- JdbcRDD连接MySQL
(1)添加依赖 <dependencies> <dependency> <groupId>org.apache.spark</groupId> < ...
- itext实现横向pdf打印内容
Document doc = new Document(PageSize.A4); 这个是用PageSize.A4设置的是纵向A4大小 进入 com.itextpdf.text.PageSize的源码 ...
- oracle_(第二课)监听器配置
一. 1.首先我们得安装好oracle数据库(上一课有讲) 再来看看我们没有监听器之前的文件 文件路径:%ORACLE_HOME%/NETWORK/ADMIN 2.关闭所有防火墙,win10的要特别注 ...
- android课程表控件、悬浮窗、Todo应用、MVP框架、Kotlin完整项目源码
Android精选源码 Android游戏2048 MVP Kotlin项目(RxJava+Rerotfit+OkHttp+Glide) Android基于自定义Span的富文本编辑器 android ...