【深度学习】PyTorch使用手册

Last updated on February 22, 2024 am

本文主要介绍pytorch中的基本使用,包括如何导入数据集,如何搭建并训练网络以及可视化的内容,基本涵盖了深度学习中经典算法的使用以及相关的例子

Basics

计算梯度例子

引入基本需要用到的包,深度学习中torch处理大部分张量的运算,而torch.nn则是对torch的网络中的一些运算,这些都是必须用到的包。

1
2
3
4
5
import torch 
import torchvision
import torch.nn as nn
import numpy as np
import torchvision.transforms as transforms

在深度学习中,一般使用张量进行运算,此时会涉及到计算张量的梯度等问题,我们这里给出一个例子来展示如何使用张量来进行梯度计算:

初始化定义张量

1
2
3
x = torch.tensor(1., requires_grad=True)
w = torch.tensor(2., requires_grad=True)
b = torch.tensor(3., requires_grad=True)

建立计算图 computational graph

1
y = w * x + b    # y = 2 * x + 3

计算梯度

1
2
3
4
y.backward()
print(x.grad) # x.grad = 2
print(w.grad) # w.grad = 1
print(b.grad) # b.grad = 1

【深度学习】PyTorch使用手册
https://lihaibineric.github.io/2023/10/22/dl_pytorch/
Author
Haibin Li
Posted on
October 22, 2023
Updated on
February 22, 2024
Licensed under