详解Pytorch中Dataset的使用

 更新时间:2022年12月29日 14:48:53   作者:LRJ-jonas  
这篇文章主要为大家详细介绍了如何加载并处理TorchVision的FashionMNIST Dataset,文中的示例代码讲解详细,感兴趣的小伙伴可以了解一下

此案例教我们加载并处理TorchVision的FashionMNIST Dataset

root 目录是 train/test data 存储的地方

download=True 如果root目录没有,则从网上下载

transform and target_transform specify the feature and label transformations

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()
)

运行得到的结果是这样的:

遍历并可视化数据集

给数据集手动加上序号sample_idx,并用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()

traning_data

torch.randint(len(training_data), size=(1,)).item()

为我的文件自定义一个Dataset

一个自定义的Dataset必须有三个函数:__init__, __len__, and __getitem__

图片存储在img_dir

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

到此这篇关于详解Pytorch中Dataset的使用的文章就介绍到这了,更多相关Pytorch Dataset使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • python使用selenium模拟浏览器进入好友QQ空间留言功能

    python使用selenium模拟浏览器进入好友QQ空间留言功能

    这篇文章主要介绍了python使用selenium模拟浏览器进入好友QQ空间留言,在本文实现过程中需要注意的是留言框和发表按钮在不同的frame,发表在外面的一层,具体实现过程跟随小编一起看看吧
    2022-04-04
  • Pygame游戏开发之太空射击实战敌人精灵篇

    Pygame游戏开发之太空射击实战敌人精灵篇

    相信大多数8090后都玩过太空射击游戏,在过去游戏不多的年代太空射击自然属于经典好玩的一款了,今天我们来自己动手实现它,在编写学习中回顾过往展望未来,下面开始讲解敌人精灵的使用
    2022-08-08
  • Python标准库之time库的使用教程详解

    Python标准库之time库的使用教程详解

    这篇文章主要介绍了Python的time库的使用教程,文中有非常详细的代码示例,对正在学习python基础的小伙伴们有非常好的帮助,需要的朋友可以参考下
    2022-04-04
  • Python多线程及其基本使用方法实例分析

    Python多线程及其基本使用方法实例分析

    这篇文章主要介绍了Python多线程及其基本使用方法,结合实例形式分析了Python相关概念、原理、使用方法及操作注意事项,需要的朋友可以参考下
    2019-10-10
  • 详解pandas中MultiIndex和对象实际索引不一致问题

    详解pandas中MultiIndex和对象实际索引不一致问题

    这篇文章主要介绍了详解pandas中MultiIndex和对象实际索引不一致问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-07-07
  • 关于pycharm 切换 python3.9 报错 ‘HTMLParser‘ object has no attribute ‘unescape‘ 的问题

    关于pycharm 切换 python3.9 报错 ‘HTMLParser‘ object has no attribu

    这篇文章主要介绍了pycharm 切换 python3.9 报错 ‘HTMLParser‘ object has no attribute ‘unescape‘ 解决,需要的朋友可以参考下
    2020-11-11
  • 详解Python中类方法@classmethod的应用技巧

    详解Python中类方法@classmethod的应用技巧

    在Python中,类方法(class method)是一种特殊的方法,可以在不创建类的实例的情况下调用,本文将详细介绍类方法的概念、用法以及在实际开发中的应用场景,希望对大家有所帮助
    2024-03-03
  • Centos环境部署django项目的全过程(永久复用)

    Centos环境部署django项目的全过程(永久复用)

    Django是一款针对Python环境的WEB开发框架,能够帮助我们构架快捷,下面这篇文章主要给大家介绍了关于Centos环境部署django项目的相关资料,需要的朋友可以参考下
    2022-10-10
  • python使用rabbitmq实现网络爬虫示例

    python使用rabbitmq实现网络爬虫示例

    这篇文章主要介绍了python使用RabbitMQ实现网络爬虫的示例,需要的朋友可以参考下
    2014-02-02
  • python中Scrapy shell的使用

    python中Scrapy shell的使用

    这篇文章主要介绍了python入门之Scrapy shell的使用,scrapy提供了一个shell。用来方便的测试规则,下面我们一起进入文章学习该内容吧,需要的小伙伴可以参考一下,希望对你有所帮助
    2022-02-02

最新评论