PyTorch 解决Dataset和Dataloader遇到的问题

yipeiwu_com7年前Python基础

今天在使用PyTorch中Dataset遇到了一个问题。先看代码

class psDataset(Dataset):
  def __init__(self, x, y, transforms = None):
    super(Dataset, self).__init__()
    self.x = x
    self.y = y
    if transforms == None:
      self.transforms = Compose([Resize((224, 224)), ToTensor()])
    else:
      self.transforms = transforms
    
  def __len__(self):
    return len(self.x)
  
  def __getitem__(self, idx):
    img = Image.open(self.x[idx])
    img = self.transforms(img)    
    return img, torch.tensor([[self.y[idx]]])

结果运行时报错:RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 0. Got 3 and 1 in dimension 1 at /opt/conda/conda-bld/pytorch_1522182087074/work/torch/lib/TH/generic/THTensorMath.c:2897

Google了一下发现是这样的:读入的图片有些是灰度图(1个通道),绝大多数是RGB图片(3通道),也有些是带透明度的(4通道)

。这导致在读入后最后一个维度(通道数)不一致(可能是1、3或者4)。

Dataloader在制作batch data时,tensor的shape必须一样,就报了这个错误。解决的方法是:img = img.convert(“RGB”)。完

整代码如下:

class psDataset(Dataset):
  def __init__(self, x, y, transforms = None):
    super(Dataset, self).__init__()
    self.x = x
    self.y = y
    if transforms == None:
      self.transforms = Compose([Resize((224, 224)), ToTensor()])
    else:
      self.transforms = transforms
    
  def __len__(self):
    return len(self.x)
  
  def __getitem__(self, idx):
    img = Image.open(self.x[idx])
    img = img.convert("RGB")
    img = self.transforms(img)    
    return img, torch.tensor([[self.y[idx]]])

以上这篇PyTorch 解决Dataset和Dataloader遇到的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现扫描局域网活动ip(扫描在线电脑)

内网的主机都是自动分配ip地址,有时候需要查看下有那些ip在使用,就写了个简单的脚本。 linux和windows下都可以用,用多线程来ping1-255所有的地址,效率不高,2分钟左右...

Windows下为Python安装Matplotlib模块

Windows下为Python安装Matplotlib模块

  这玩意反反复复弄了一晚上,这里详细叙述下如何安装,肯定会对大家有所帮助。首先默认大家都装了Python,这个从官网下基本不会有任何难度。   (1)Setuptools的安装   为...

django中forms组件的使用与注意

forms组件 django框架提供了一个Form类,来进行web开发中的表单提交数据的处理工作。 导入相关模块 from django import forms from dja...

python中的单引号双引号区别知识点总结

python中的单引号双引号有什么区别呢?下面给大家详细的介绍一下: 先说双引号与三引号的区别,双引号所表示的字符串通常要写成一行。 如: s1 = "hello,world" 如...

使用Python读写及压缩和解压缩文件的示例

读写文件 首先看一个例子: f = open('thefile.txt','w') #以写方式打开, try: f.write('wokao') finally: f.c...