【PyTorch Tutorial学习笔记】PyTorch官方教学(二)

本文是PyTorch官方教程的第二部分,涵盖了Tensor的使用,数据集与DataLoaders的处理,包括官方数据集与自定义数据集的加载方式,以及Transforms的运用。接着介绍了模型构建、训练模型的步骤,涉及Autograd和Optimization。此外,还阐述了如何保存和加载模型,并详细讲解了如何利用TensorBoard进行模型结构可视化、查看训练日志和底层embedding。最后提供了一些PyTorch学习资源和待探索的问题。
摘要由CSDN通过智能技术生成

Preliminary

Tensor用法

  • tensor初始化及属性
rand_tensor = torch.rand(2,3)
ones_tensor = torch.ones(2,3)
zeros_tensor = torch.zeros(2,3)
print(tensor.shape, tensor.dtype, tensor.device)

p.s.tensor默认是创建在CPU上的,需要显式地移动到GPU。

# We move our tensor to the GPU if available
if torch.cuda.is_available():
  tensor = tensor.to('cuda')
  • tensor操作
    1.索引和切片
tensor = torch.ones(4, 4)
print('First row: ',tensor[0])
print('First column: ', tensor[:, 0])
print('Last column:', tensor[..., -1])

2.拼接

t1 = torch.cat([tensor, tensor, tensor], dim=1)
# 还有torch.stack

3.算术运算

# 矩阵乘法. y1, y2, y3 will have the same value
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)

y3 = torch.rand_like(tensor)
torch.matmul(tensor, tensor.T, out=y3)

# element-wise乘法. z1, z2, z3 will have the same value
z1 = tensor * tensor
z2 = tensor.mul(tensor)

z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)

# in-place operations: 带下划线
tensor.add_(5)
print(tensor)

# 常见操作:sum()和item()!
agg = tensor.sum() # 所有位置上的值求和后aggregate为单值tensor
agg_item = agg.item() # 获取单值tensor的数值
print(agg_item, type(agg_item))

Datasets & DataLoaders

torch.utils.data.DataLoadertorch.utils.data.Dataset两个模块负责数据相关操作, Dataset存储数据和标签,DataLoaderDataset变成可迭代对象。

官方数据集使用方法:

1.使用Dataset类得到data
2.使用DataLoader类创建可迭代对象dataloader
3.使用dataloader遍历数据集:每一轮迭代返回一批也就是batch_size个样本,如果shuffle=True则每当所有数据被迭代一遍,就会shuffle一次

import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor

# Loading a Dataset
training_data = datasets.FashionMNIST(
    root="data", # the path where the train/test data is stored
    train=True, # specifies training or test dataset
    download=True, # downloads the data from the internet if it’s not available at root
    transform=ToTensor() # specify the feature and label transformations
)

# Preparing your data for training with DataLoaders
train_dataloader = DataLoader(training_data, batch_size=64, shuffle=True)

# Iterate through the DataLoader
# iter()函数获取可迭代对象的迭代器,本质是调用__iter__方法
# next()函数获取该对象的下一条数据
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]

自定义数据集使用方法:

定义自己的数据集类(继承Dataset类)并实现三个接口:
(1)__init__, 实例化类的时候运行一次
(2)__len__, 返回数据集大小
(3)__getitem__, 返回一个指定index处的样本

# 前提:图片存在img_dir文件夹下,标签在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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Pytorch是机器学习中的一个重要框架,它与TensorFlow一起被认为是机器学习的两大框架。Pytorch学习可以从以下几个方面入手: 1. Pytorch基本语法:了解Pytorch的基本语法和操作,包括张量(Tensors)的创建、导入torch库、基本运算等\[2\]。 2. Pytorch中的autograd:了解autograd的概念和使用方法,它是Pytorch中用于自动计算梯度的工具,可以方便地进行反向传播\[2\]。 3. 使用Pytorch构建一个神经网络:学习使用torch.nn库构建神经网络的典型流程,包括定义网络结构、损失函数、反向传播和更新网络参数等\[2\]。 4. 使用Pytorch构建一个分类器:了解如何使用Pytorch构建一个分类器,包括任务和数据介绍、训练分类器的步骤以及在GPU上进行训练等\[2\]。 5. Pytorch的安装:可以通过pip命令安装Pytorch,具体命令为"pip install torch torchvision torchaudio",这样就可以在Python环境中使用Pytorch了\[3\]。 以上是一些关于Pytorch学习笔记,希望对你有帮助。如果你需要更详细的学习资料,可以参考引用\[1\]中提到的网上帖子,或者查阅Pytorch官方文档。 #### 引用[.reference_title] - *1* [pytorch自学笔记](https://blog.csdn.net/qq_41597915/article/details/123415393)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [Pytorch学习笔记](https://blog.csdn.net/pizm123/article/details/126748381)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值