Torch学习笔记一

Dataset类

Dataset在torch.utils.data中,util是utility简写,意味应用程序

Dataset用法说明:

 r"""An abstract class representing a :class:`Dataset`.

    All datasets that represent a map from keys to data samples should subclass

    it. All subclasses should overwrite :meth:`__getitem__`, supporting fetching a

    data sample for a given key. Subclasses could also optionally overwrite

    :meth:`__len__`, which is expected to return the size of the dataset by many

    :class:`~torch.utils.data.Sampler` implementations and the default options

    of :class:`~torch.utils.data.DataLoader`.

    .. note::

      :class:`~torch.utils.data.DataLoader` by default constructs a index

      sampler that yields integral indices.  To make it work with a map-style

      dataset with non-integral indices/keys, a custom sampler must be provided.

"""

 关键信息如下:

  1. 创建的数据集的实例应该是Dataset的子类,因此自己创建的数据集类需要继承Dataset。
  2. 所有的子类需要重写__getitem__,get item,获取数据和索引。
  3. 子类可以选择性重写__len__来返回数据集大小

 根据以上信息,可以创建类如下:

from torch.utils.data import Dataset
import os
from PIL import Image

class MyClass(Dataset):
    def __init__(self, rootpath, labelpath):
        self.rootpath = rootpath
        self.labelpath = labelpath
        self.path = os.path.join(self.rootpath, self.labelpath)
        self.imgpath = os.listdir(self.path)

    def __getitem__(self, idx):
        img_name = self.imgpath[idx]
        img_item_path = os.path.join(self.path, img_name)

        img = Image.open(img_item_path)
        label = self.labelpath
        return img, label

    def __len__(self):
        return len(self.imgpath)

初始化方法需要传递根目录和标签路径,可以获得rootpath/labelpath/path/imgpath的属性

定义labelpath是因为使用的ants和bees数据集的标签就为文件夹名字所以需要labelpath。这里使用两个方法:

  1. os.path.join返回连接的两个路径,相比字符串处理好处是自适应linux与windows平台
  2. os.listdir返回文件夹下的图像路径,是一个包含所有图像路径的列表

 

__getitem__方法需要传递图像序号,返回单个图像和其标签。

通过imgpath列表和序号获得图片相对路径,通过os.path.join获得绝对路径,接下来调用pillow中的Image类:

  1. Image.open(img_item_path)返回路径下的图像矩阵,参数可为绝对路径也可为相对路径

label标签即为labelpath

 

__len__方法通过len()函数返回imgpath列表的长度得到

学习视频来源:https://www.bilibili.com/video/BV1hE411t7RN?spm_id_from=333.337.search-card.all.click

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值