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.
"""
关键信息如下:
- 创建的数据集的实例应该是Dataset的子类,因此自己创建的数据集类需要继承Dataset。
- 所有的子类需要重写__getitem__,get item,获取数据和索引。
- 子类可以选择性重写__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。这里使用两个方法:
- os.path.join返回连接的两个路径,相比字符串处理好处是自适应linux与windows平台
- os.listdir返回文件夹下的图像路径,是一个包含所有图像路径的列表
__getitem__方法需要传递图像序号,返回单个图像和其标签。
通过imgpath列表和序号获得图片相对路径,通过os.path.join获得绝对路径,接下来调用pillow中的Image类:
- 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