PyTorch-Tutorials【pytorch官方教程中英文详解】- 3 Datasets&DataLoaders

165 篇文章 57 订阅
订阅专栏
72 篇文章 28 订阅
订阅专栏
28 篇文章 17 订阅
订阅专栏

【2022真的开始了,第一条博客。】

在文章PyTorch-Tutorials【pytorch官方教程中英文详解】- 2 Tensors中介绍了张量,接下来看看pytorch中读取数据集的Datasets&DataLoaders类。

原文链接: Datasets & DataLoaders — PyTorch Tutorials 1.10.1+cu102 documentation

Code for processing data samples can get messy and hard to maintain; we ideally want our dataset code to be decoupled from our model training code for better readability and modularity. PyTorch provides two data primitives: torch.utils.data.DataLoader and torch.utils.data.Dataset that allow you to use pre-loaded datasets as well as your own data. Dataset stores the samples and their corresponding labels, and DataLoader wraps an iterable around the Dataset to enable easy access to the samples.

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

PyTorch domain libraries provide a number of pre-loaded datasets (such as FashionMNIST) that subclass torch.utils.data.Dataset and implement functions specific to the particular data. They can be used to prototype and benchmark your model. You can find them here: Image Datasets, Text Datasets, and Audio Datasets

【PyTorch域库提供了许多预加载的数据集(如FashionMNIST),它们是torch.util .data. dataset的子类,并实现特定于特定数据的函数。它们可以用于原型和基准测试你的模型。你可以在这里找到它们:Image Datasets、Text Datasets和Audio Datasets】

1 Loading a Dataset

Here is an example of how to load the Fashion-MNIST dataset from TorchVision. Fashion-MNIST is a dataset of Zalando’s article images consisting of 60,000 training examples and 10,000 test examples. Each example comprises a 28×28 grayscale image and an associated label from one of 10 classes.

【下面是一个如何从TorchVision加载Fashion-MNIST数据集的例子。fashionmnist是Zalando文章图像的数据集,包含6万个训练示例和1万个测试示例。每个示例包含28×28灰度图像和来自10个类之一的相关标签。】

We load the FashionMNIST Dataset with the following parameters:

  • root is the path where the train/test data is stored,
  • train specifies training or test dataset,
  • download=True downloads the data from the internet if it’s not available at root.
  • transform and target_transform specify the feature and label transformations

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

  • root是训练/测试数据存储的路径,
  • train指定训练或测试数据集,
  • download=True表示如果无法从根目录获取数据,则从Internet下载数据。
  • 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()
)

输出:

2 Iterating and Visualizing the Dataset

We can index Datasets manually like a list: training_data[index]. We use matplotlib to visualize some samples in our training data.

【我们可以像列表一样手动索引数据集: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()

输出:

3 Creating a Custom Dataset for your files

A custom Dataset class must implement three functions: __init__, __len__, and __getitem__. Take a look at this implementation; the FashionMNIST images are stored in a directory img_dir, and their labels are stored separately in a CSV file annotations_file.

【自定义Dataset类必须实现三个函数:__init__、__len__和__getitem__。看看这个实现;FashionMNIST图像存储在目录img_dir中,它们的标签分别存储在CSV文件annotations_file中。】

In the next sections, we’ll break down what’s happening in each of these functions.

【在下一节中,我们将详细分析每个函数中发生的事情。】

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

__init__

The __init__ function is run once when instantiating the Dataset object. We initialize the directory containing the images, the annotations file, and both transforms (covered in more detail in the next section).

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

The labels.csv file looks like:

【labels.csv文件如下所示:】

tshirt1.jpg, 0
tshirt2.jpg, 0
......
ankleboot999.jpg, 9
def __init__(self, annotations_file, img_dir, transform=None, target_transform=None):
    self.img_labels = pd.read_csv(annotations_file, names=['file_name', 'label'])
    self.img_dir = img_dir
    self.transform = transform
    self.target_transform = target_transform

__len__

The __len__ function returns the number of samples in our dataset.

【__len__函数返回数据集中的样本数量。】

Example:

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

__getitem__

The __getitem__ function loads and returns a sample from the dataset at the given index idx. Based on the index, it identifies the image’s location on disk, converts that to a tensor using read_image, retrieves the corresponding label from the csv data in self.img_labels, calls the transform functions on them (if applicable), and returns the tensor image and corresponding label in a tuple.

【__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

4 Preparing your data for training with DataLoaders

The Dataset retrieves our dataset’s features and labels one sample at a time. While training a model, we typically want to pass samples in “minibatches”, reshuffle the data at every epoch to reduce model overfitting, and use Python’s multiprocessing to speed up data retrieval.

【数据集每次检索一个样本的数据集的特征和标签。在训练模型时,我们通常希望以“小批量”传递样本,在每个epoch重新打乱数据以减少模型过拟合,并使用Python的多进程处理来加速数据检索。】

DataLoader is an iterable that abstracts this complexity for us in an easy API.

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

5 Iterate through the DataLoader

We have loaded that dataset into the DataLoader and can iterate through the dataset as needed. Each iteration below returns a batch of train_features and train_labels (containing batch_size=64 features and labels respectively). Because we specified shuffle=True, after we iterate over all batches the data is shuffled (for finer-grained control over the data loading order, take a look at Samplers).

【我们已经将该数据集加载到DataLoader中,并可以根据需要遍历该数据集。下面的每次迭代都返回一批train_features和train_labels(分别包含batch_size=64个特性和标签)。因为我们指定了shuffle=True,所以在我们遍历所有批次之后,数据就会被打乱(对于更细粒度的数据加载顺序的控制,请查看Sampler)。】

# 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}")

输出结果:

Feature batch shape: torch.Size([64, 1, 28, 28])
Labels batch shape: torch.Size([64])
Label: 7

 6 Further Reading

  • torch.utils.data API

说明:记录学习笔记,如果错误欢迎指正!写文章不易,转载请联系我。

Pytorch框架-Datasets&DataLoaders
程序员,他们想的是什么?他们想的永远都是技术,他们崇尚的也永远都是技术。
10-27 305
Pytorch教程参考链接:https://github.com/yunjey/pytorch-tutorial。
PYG(Pytorch Geometric)中文说明书——第3章TUTORIALS
qq_37415491的博客
08-02 1586
本文为pyg官网的中文翻译(官方原版链接 https://pytorch-geometric.readthedocs.io/en/latest/),并加入了一些其他网上大佬和自己的理解。如有翻译理解不当之处还请各位多多指出,非常感谢! 3.1Creating Message Passing Networks 将卷积算子推广到不规则域通常表示为邻域聚合或消息传递方案。用表示第(k-1)层中节点 i 的特征,表示节点 j 到节点 i 的(可选)边缘特征,消息传递图神经网络可以描述为 其中表示一个可微的,排列
pytorch tutorials v1.0.0.dev20181002 官方文档PDF版
10-10
pytorch tutorials 保存于网页,完美pdf版,完整公式、图片、表格,有页码,有目录,有书签导航,适用电脑、pad、手机上浏览。 === Printed v1.0.0.dev20181002 from [ https://pytorch.org/tutorials/ ] at 2018-10-10 21:03:44. Visit [ https://download.csdn.net/user/ldengjie/uploads ] to get the latest version pdf or mail to ldengjie@163.com to ask for printing and updating the latest version pdf. === 《pytorch docs v0.4.1 官方文档PDF版》 在 https://download.csdn.net/download/ldengjie/10712472 ,保存时间 2018-10-10 15:17:41 ===
Pytorch tutorial pytorch 入门
TYtrack的博客
10-15 2044
今天看了pytorch官方tutorial,好美的教程哦,按规定是60min分钟的闪电战,结果运行完代码,花了一整天,是我不配,网站官方地址是:https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html 这篇tutorial主要分为四个部分: 1、什么是Tensor,和Tensorflow介绍差不多 2、自动求梯度(微分) 3、神经网络架构 4、以一个图像分类作为example实战 1、WHAT IS PYT.
PyTorch Tutorial
摩登都市天空---专栏
01-18 742
目录 图像、视觉、CNN相关实现 对抗生成网络、生成模型、GAN相关实现 机器翻译、问答系统、NLP相关实现 先进视觉推理系统 深度强化学习相关实现 通用神经网络高级应用 图像、视觉、CNN相关实现 PyTorch-FCNhttps://github.com/wkentaro/pytorch-fcn.git FCN(Fully Convolutional Networks...
PyTorch tutorials:快速学会使用PyTorch
最新发布
jiayoushijie的博客
06-10 1090
PyTorch是由Facebook人工智能研究实验室(FAIR)开发的开源深度学习框架。它建立在Torch库之上,Torch是一个使用Lua编程语言的机器学习库。Torch主要用于研究和学术领域,而PyTorch则旨在为研究人员和实践者提供一个Python友好的接口。PyTorch是为灵活性和速度而设计的。它提供了一个名为Tensor的主要数据结构,用于存储和操作多维数组。Tensor类似于NumPy的ndarray,但可以利用GPU来加速计算。
pytorch tutorials运行
坩埚上校的博客
08-30 651
Error1 from PyQt5 import QtCore, QtGui, QtWidgets ImportError: libGL.so.1: cannot open shared object file: No such file or directory sovle: 安装: yum install mesa-libGL-devel Error2: in _create_qA
Deep-Learning-with-PyTorch-Tutorials-master(1).zip
02-26
PyTorch深度学习教程全解析》 PyTorch,作为一款开源的机器学习库,以其易用性和灵活性深受广大开发者喜爱,尤其在深度学习领域,PyTorch扮演着重要的角色。本教程集合了丰富的资源,旨在帮助初学者快速入门,并...
卷积神经网络-pytorch-lenet5&&resnet
tjjyqing的博客
05-05 293
卷积神经网络pytorch实现一、模型建立1 Lenet5卷积神经网络模型2 Resnet卷积神经网络模型二、模型调用 一、模型建立 本代码基于pytorch以及cuda的GPU模式,如果没有GPU的话,把to.devide()这种代码删去就好。 下面仅仅是代码的实现,不对模型建立做解释,相关的代码解释有注释,希望对大家有帮助。 1 Lenet5卷积神经网络模型 需要先运行模型,然后下面调用才能成功。其次,模型代码文件需与运行的代码文件在同一级同一目录下。 from torch import nn cl
Manjaro 20.04安装Nvidia驱动,并安装pytorch-gpu
ph2537089的博客
10-30 1906
安装闭源Nvidia驱动: 删去自带nvidia驱动 方式一:面板删除全删干净。 方式二: mhwd -li #查看已安装的显卡驱动 sudo mhwd -r video-nvidia#卸载对应驱动 mhwd -l #查看可安装显卡驱动 切换低版本内核 #删除不需要的内核版本 mhwd-kernel -li#查看已安装内核 sudo mhwd-kernel -r xxx#删除不需要的内核 安装nvidia驱动 #选择与内核相对应的版本,不要带390xx的旧显卡驱动,不带尾缀的会自动安装
pytorch tutorials v0.4.0 官方文档PDF版
05-26
pytorch tutorials 保存于网页,完美pdf版,完整公式、图片、表格,有页码,有目录,有书签导航,适用电脑、pad、手机上浏览。 Printed v0.4.0 from [ https://pytorch.org/tutorials/ ] at 2018-05-26 02:02:47. Visit [ https://download.csdn.net/user/ldengjie/uploads ] to get the latest version pdf or mail to ldengjie@163.com to ask for printing and updating the latest version pdf.
PytorchTutorials1.5.pdf
05-10
pytorch最新版本1.5的英文官方教程,因为工作需要学习Pytorch,而官方教程是最权威的教程,而pytorch的官网速度比较慢,所以自己下载下来了所有的教程文档,并制作成了pdf,方便查看,同时也制作好了书签,方便阅读
PyTorch_tutorial_0.0.4_余霆嵩
12-20
教程以实际应用、工程开发为目的,着重介绍模型训练过程中遇到的实 际问题和方法。如上图所示,在机器学习模型开发中,主要涉及三大部分,分别是数据、模型和损失函数及优化器。本文也按顺序的依次介绍数据、模型和损失函数及优化器,从而给大家带来清晰的机器学习结构。
PyTorch-Tutorialspytorch官方教程中英文详解】- 8 Save and Load Model
csdn_xmj的博客
01-12 778
原文链接:Save and Load the Model — PyTorch Tutorials 1.10.1+cu102 documentation SAVE AND LOAD THE MODEL In this section we will look at how to persist model state with saving, loading and running model predictions. 【在本节中,我们将看看如何通过保存、加载和运行模型预测来持久化模型状态。】 imp
PyTorch-Tutorialspytorch官方教程中英文详解】- 5 Build Model
csdn_xmj的博客
01-06 1313
原文链接:Build the Neural Network — PyTorch Tutorials 1.10.1+cu102 documentation BUILD THE NEURAL NETWORK Neural networks comprise of layers/modules that perform operations on data. The torch.nn namespace provides all the building blocks you need to build you
PyTorch-Tutorialspytorch官方教程中英文详解】- 2 Tensors
csdn_xmj的博客
12-31 1435
原文链接:Tensors — PyTorch Tutorials 1.10.1+cu102 documentation
Pytorch tutorials学习笔记
o707191418的博客
10-22 258
每一段代码后都有跑出来的结果 参考网址 https://pytorch.org/tutorials/beginner/blitz/neural_networks_tutorial.html 文章目录1. Neural Networks1.1 Define the network1.2 Loss Function1.3 Backprop1.4 Update the weights 1. Neu...
PyTorch-Tutorialspytorch官方教程中英文详解】- 1 Quickstart
csdn_xmj的博客
12-30 1633
原文链接:Learn the Basics — PyTorch Tutorials 1.10.1+cu102 documentation
写文章

热门文章

  • 残差网络(ResNets)的残差块(Residual block) 49842
  • Coursera吴恩达《深度学习》课程总结(全) 30909
  • 三元组损失(Triplet loss) 20710
  • 负采样(Negative Sampling) 15701
  • 交并比(Intersection over union) 14921

分类专栏

  • 吴恩达深度学习笔记 91篇
  • DETR专栏 4篇
  • 大模型专栏 43篇
  • 多模态模型专栏 14篇
  • NLP专栏 2篇
  • Transformer专栏 47篇
  • Diffusion Model专栏 12篇
  • CV-目标跟踪专栏 4篇
  • OCR专栏 2篇
  • AIGC专栏 3篇
  • CV-目标检测专栏 52篇
  • CV-分割专栏 11篇
  • python库 98篇
  • python常见书籍 12篇
  • 运维知识 2篇
  • 深度学习拓展阅读 286篇
  • python拓展学习 149篇
  • 统计学 13篇
  • 论文阅读one 7篇
  • 动手学习-项目类 11篇
  • 日常操作 5篇
  • docker知识 4篇
  • Git 5篇
  • 李宏毅机器学习笔记 14篇
  • DL框架 28篇
  • AI 72篇
  • DL tips 7篇
  • 深度学习知识点储备 68篇
  • 笔记 165篇
  • 《尚硅谷》MySQL笔记 6篇
  • 日常唠嗑 9篇
  • 数据收集 18篇

最新评论

  • 天才程序员周弈帆 | Stable Diffusion 解读(一):回顾早期工作

    ccc_do: 可以询问一下为什么说transformer只能处理离散向量吗,按照我的个人理解,文本词嵌入之后不也是连续向量吗

  • OpenCV与AI深度学习 | 高效开源的OCR工具:Surya-OCR介绍与使用

    抓娃男孩: 为什么只有坐标,没办法提取到文本吗

  • Coggle数据科学 | 科大讯飞AI大赛:人岗匹配挑战赛 赛季3

    双木的木: https://challenge.xfyun.cn/topic/info?type=match-challenge-s3&ch=dw24_AtTCK9点击这个链接

  • Coggle数据科学 | 科大讯飞AI大赛:人岗匹配挑战赛 赛季3

    2301_80186124: 数据集可以分享吗,想练习练习表情包

  • 极市平台|100+深度学习各方向数据集资源大盘点

    qq_40408025: 您好这个数据还能下载吗

最新文章

  • 周报 | 24.10.14-24.10.20文章汇总
  • OpenCV学堂 | YOLOv8实战 | 荧光显微镜细胞图像检测
  • 机器学习算法那些事 | 有位大佬逐模块解析了detr结构
2024
10月 42篇
09月 60篇
08月 62篇
07月 62篇
06月 57篇
05月 59篇
04月 58篇
03月 61篇
02月 23篇
01月 7篇
2023年6篇
2022年41篇
2021年132篇

目录

目录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值

玻璃钢生产厂家玻璃钢人物雕塑效果有哪些武汉万圣节商场美陈模型道具浚县玻璃钢雕塑设计辣椒玻璃钢雕塑定制嘉兴玻璃钢仿真水果雕塑厂家河北景观玻璃钢雕塑优势曲阳玻璃钢孔子雕塑陕西仿古玻璃钢景观雕塑厂家上海通道商场美陈生产企业铁岭玻璃钢座雕塑定制云浮玻璃钢景观雕塑定制营口沈阳玻璃钢花盆银川动物玻璃钢雕塑设计邯郸玻璃钢人物雕塑制作岑溪玻璃钢卡通座椅雕塑玻璃钢雕塑厂家电话多少松江区镜面玻璃钢雕塑陶瓦玻璃钢花盆青岛时尚玻璃钢座椅雕塑熊猫卡通玻璃钢雕塑江苏镜面玻璃钢雕塑哪家好辽宁玻璃钢雕塑加工品质玻璃钢雕塑供应商家深圳特色商场美陈怎么样宁夏玻璃钢广场雕塑定制玻璃钢雕塑小品多少钱玻璃钢雕塑公司招聘吉林玻璃钢广场雕塑厂家山东玻璃钢雕塑摆件研发公司二人转人物玻璃钢雕塑香港通过《维护国家安全条例》两大学生合买彩票中奖一人不认账让美丽中国“从细节出发”19岁小伙救下5人后溺亡 多方发声单亲妈妈陷入热恋 14岁儿子报警汪小菲曝离婚始末遭遇山火的松茸之乡雅江山火三名扑火人员牺牲系谣言何赛飞追着代拍打萧美琴窜访捷克 外交部回应卫健委通报少年有偿捐血浆16次猝死手机成瘾是影响睡眠质量重要因素高校汽车撞人致3死16伤 司机系学生315晚会后胖东来又人满为患了小米汽车超级工厂正式揭幕中国拥有亿元资产的家庭达13.3万户周杰伦一审败诉网易男孩8年未见母亲被告知被遗忘许家印被限制高消费饲养员用铁锨驱打大熊猫被辞退男子被猫抓伤后确诊“猫抓病”特朗普无法缴纳4.54亿美元罚金倪萍分享减重40斤方法联合利华开始重组张家界的山上“长”满了韩国人?张立群任西安交通大学校长杨倩无缘巴黎奥运“重生之我在北大当嫡校长”黑马情侣提车了专访95后高颜值猪保姆考生莫言也上北大硕士复试名单了网友洛杉矶偶遇贾玲专家建议不必谈骨泥色变沉迷短剧的人就像掉进了杀猪盘奥巴马现身唐宁街 黑色着装引猜测七年后宇文玥被薅头发捞上岸事业单位女子向同事水杯投不明物质凯特王妃现身!外出购物视频曝光河南驻马店通报西平中学跳楼事件王树国卸任西安交大校长 师生送别恒大被罚41.75亿到底怎么缴男子被流浪猫绊倒 投喂者赔24万房客欠租失踪 房东直发愁西双版纳热带植物园回应蜉蝣大爆发钱人豪晒法院裁定实锤抄袭外国人感慨凌晨的中国很安全胖东来员工每周单休无小长假白宫:哈马斯三号人物被杀测试车高速逃费 小米:已补缴老人退休金被冒领16年 金额超20万

玻璃钢生产厂家 XML地图 TXT地图 虚拟主机 SEO 网站制作 网站优化