• pytorch升级打怪(三)


    简介

    处理数据样本的代码可能会变得混乱且难以维护;理想情况下,我们希望我们的数据集代码与模型训练代码解耦,以提高可读性和模块化。PyTorch提供了两个数据原语:torch.utils.data.DataLoader和torch.utils.data.Dataset,允许您使用预加载的数据集以及您自己的数据。Dataset存储样本及其相应的标签,DataLoader在Dataset周围包装一个可以可以方便地访问样本。

    PyTorch域库提供一些预加载的数据集(如FashionMNIST),该子类为torch.utils.data.Dataset,并实现特定于特定数据的功能。它们可用于原型和基准测试您的模型。您可以在这里找到它们:图像数据集文本数据集音频数据集

    加载数据集

    以下是如何从TorchVision加载Fashion-MNIST数据集的示例。Fashion-MNIST是Zalando文章图像的数据集,包括60,000个训练示例和10,000个测试示例。每个示例都包括一个28×28的灰度图像和来自10个班级之一的相关标签。

    我们用以下参数加载FashionMNIST数据集:

    • root是存储火车/测试数据的路径,
    • train指定训练或测试数据集,
    • download=True如果root上没有数据,则从互联网上下载数据。
    • transform和target_transform指定功能和标签转换
    
    import torch
    from torch.utils.data import Dataset
    from torchvision import datasets
    from torchvision.transforms import ToTensor
    import matplotlib.pyplot as plt
    
    
    training_data = datasets.FashionMNIST(
        root="data",
        train=True,
        download=True,
        transform=ToTensor()
    )
    
    test_data = datasets.FashionMNIST(
        root="data",
        train=False,
        download=True,
        transform=ToTensor()
    )
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    
    Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz
    Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz to data/FashionMNIST/raw/train-images-idx3-ubyte.gz
    
      0%|          | 0/26421880 [00:00<?, ?it/s]
      0%|          | 65536/26421880 [00:00<01:12, 363720.69it/s]
      1%|          | 229376/26421880 [00:00<00:38, 682917.83it/s]
      3%|3         | 917504/26421880 [00:00<00:12, 2109774.93it/s]
     12%|#2        | 3211264/26421880 [00:00<00:03, 6286038.17it/s]
     28%|##8       | 7438336/26421880 [00:00<00:01, 14838321.45it/s]
     41%|####      | 10747904/26421880 [00:00<00:00, 16477772.21it/s]
     57%|#####7    | 15138816/26421880 [00:01<00:00, 22904288.96it/s]
     71%|#######   | 18644992/26421880 [00:01<00:00, 21979092.87it/s]
     92%|#########2| 24346624/26421880 [00:01<00:00, 30077676.52it/s]
    100%|##########| 26421880/26421880 [00:01<00:00, 18141478.99it/s]
    Extracting data/FashionMNIST/raw/train-images-idx3-ubyte.gz to data/FashionMNIST/raw
    
    Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-labels-idx1-ubyte.gz
    Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-labels-idx1-ubyte.gz to data/FashionMNIST/raw/train-labels-idx1-ubyte.gz
    
      0%|          | 0/29515 [00:00<?, ?it/s]
    100%|##########| 29515/29515 [00:00<00:00, 327742.46it/s]
    Extracting data/FashionMNIST/raw/train-labels-idx1-ubyte.gz to data/FashionMNIST/raw
    
    Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-images-idx3-ubyte.gz
    Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-images-idx3-ubyte.gz to data/FashionMNIST/raw/t10k-images-idx3-ubyte.gz
    
      0%|          | 0/4422102 [00:00<?, ?it/s]
      1%|1         | 65536/4422102 [00:00<00:11, 363330.31it/s]
      5%|5         | 229376/4422102 [00:00<00:06, 684189.84it/s]
     21%|##1       | 950272/4422102 [00:00<00:01, 2195763.19it/s]
     87%|########6 | 3833856/4422102 [00:00<00:00, 7634326.84it/s]
    100%|##########| 4422102/4422102 [00:00<00:00, 6105857.14it/s]
    Extracting data/FashionMNIST/raw/t10k-images-idx3-ubyte.gz to data/FashionMNIST/raw
    
    Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-labels-idx1-ubyte.gz
    Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-labels-idx1-ubyte.gz to data/FashionMNIST/raw/t10k-labels-idx1-ubyte.gz
    
      0%|          | 0/5148 [00:00<?, ?it/s]
    100%|##########| 5148/5148 [00:00<00:00, 37228063.78it/s]
    Extracting data/FashionMNIST/raw/t10k-labels-idx1-ubyte.gz to data/FashionMNIST/raw
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    迭代和可视化数据集

    我们可以像列表一样手动索引Datasets:training_data[index]。我们使用matplotlib在训练数据中可视化一些样本。

    
    labels_map = {
        0: "T-Shirt",
        1: "Trouser",
        2: "Pullover",
        3: "Dress",
        4: "Coat",
        5: "Sandal",
        6: "Shirt",
        7: "Sneaker",
        8: "Bag",
        9: "Ankle Boot",
    }
    figure = plt.figure(figsize=(8, 8))
    cols, rows = 3, 3
    for i in range(1, cols * rows + 1):
        sample_idx = torch.randint(len(training_data), size=(1,)).item()
        img, label = training_data[sample_idx]
        figure.add_subplot(rows, cols, i)
        plt.title(labels_map[label])
        plt.axis("off")
        plt.imshow(img.squeeze(), cmap="gray")
    plt.show()
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    在这里插入图片描述

    为您的文件创建自定义数据集

    自定义数据集类必须实现三个函数:

    __init__、__len__和__getitem__
    
    • 1

    。看看这个实现;FashionMNIST图像存储在目录img_dir中,其标签单独存储在CSV文件annotations_file。

    在接下来的章节中,我们将分解每个函数中发生的事情。

    
    import os
    import pandas as pd
    from torchvision.io import read_image
    
    class CustomImageDataset(Dataset):
        def __init__(self, annotations_file, img_dir, transform=None, target_transform=None):
            self.img_labels = pd.read_csv(annotations_file)
            self.img_dir = img_dir
            self.transform = transform
            self.target_transform = target_transform
    
        def __len__(self):
            return len(self.img_labels)
    
        def __getitem__(self, idx):
            img_path = os.path.join(self.img_dir, self.img_labels.iloc[idx, 0])
            image = read_image(img_path)
            label = self.img_labels.iloc[idx, 1]
            if self.transform:
                image = self.transform(image)
            if self.target_transform:
                label = self.target_transform(label)
            return image, label
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    __init__

    实例化数据集对象时,__init__函数运行一次。我们初始化包含图像、注释文件和两个转换的目录(下一节将更详细地介绍)。

    
    def __init__(self, annotations_file, img_dir, transform=None, target_transform=None):
        self.img_labels = pd.read_csv(annotations_file)
        self.img_dir = img_dir
        self.transform = transform
        self.target_transform = target_transform
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    __len__

    __len__函数返回我们数据集中的样本数。

    
    def __len__(self):
        return len(self.img_labels)
    
    • 1
    • 2
    • 3

    __getitem__

    __getitem__函数加载并返回给定索引idx的数据集的样本。基于索引,它识别图像在磁盘上的位置,使用read_image将其转换为张量,从self.img_labels中的csv数据中检索相应的标签,调用其上的转换函数(如果适用),并在元组中返回张量图像和相应标签。

    
    def __getitem__(self, idx):
        img_path = os.path.join(self.img_dir, self.img_labels.iloc[idx, 0])
        image = read_image(img_path)
        label = self.img_labels.iloc[idx, 1]
        if self.transform:
            image = self.transform(image)
        if self.target_transform:
            label = self.target_transform(label)
        return image, label
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    准备您的数据以使用DataLoaders进行训练

    Dataset检索我们数据集的功能,并一次标记一个样本。在训练模型时,我们通常希望以“迷你批次”传递样本,在每个时代重新洗牌数据以减少模型过拟合,并使用Pythonmultiprocessing来加快数据检索速度。

    DataLoader是一个可以在一个简单的API中为我们抽象这种复杂性的可以进行的。

    from torch.utils.data import DataLoader
    
    train_dataloader = DataLoader(training_data, batch_size=64, shuffle=True)
    test_dataloader = DataLoader(test_data, batch_size=64, shuffle=True)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5

    通过DataLoader进行遍载

    我们已经将该数据集加载到DataLoader,可以根据需要迭代数据集。下面的每个迭代都会返回一批train_features和train_labels(分别包含batch_size=64特征和标签)。因为我们指定了shuffle=True,在我们遍复所有批次后,数据被洗牌(为了更精细地控制数据加载顺序,请查看采样器)。

    
    # Display image and label.
    train_features, train_labels = next(iter(train_dataloader))
    print(f"Feature batch shape: {train_features.size()}")
    print(f"Labels batch shape: {train_labels.size()}")
    img = train_features[0].squeeze()
    label = train_labels[0]
    plt.imshow(img, cmap="gray")
    plt.show()
    print(f"Label: {label}")
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    在这里插入图片描述

    Feature batch shape: torch.Size([64, 1, 28, 28])
    Labels batch shape: torch.Size([64])
    Label: 5
    
    
    • 1
    • 2
    • 3
    • 4
  • 相关阅读:
    猿创征文|手把手玩转docker,从入门到精通
    Linux 搭建本地镜像源(CentOS 离线 yum)
    redirs非关系型数据库使用
    git报错:Failed to connect to 127.0.0.1 port 1080
    神经网络 深度神经网络,深度神经网络工作原理
    异构数据库
    MySQL varchar详解
    驱动开发:内核封装WFP防火墙入门
    计算机系统漫游
    BERT详解
  • 原文地址:https://blog.csdn.net/qq_43390313/article/details/136590527