Pytorch

332 阅读4分钟

时间:2023.01.4 14:03

线索

  1. Pytorch基本语法
  2. tensor张量
  3. 使用pytorch构建一个神经网络

笔记内容

pytorch

  • 定义:基于numpy的科学计算库 两大功能

    提供GPU服务

    灵活性和速度

  • pytorch的基本元素操作

    pythorch之所以能使用GPU加速:tensor张量 numpy核心:ndarray

    api函数 1. 函数的参数有哪些 2. 函数的返回值是什么

    创建矩阵

from __future__ import print_function
import torch
# 创建矩阵
x = torch.empty(5,3)# 未初始化,只保证形状,值是不确定的
print(x)
x = torch.rand(5,3)# 初始化
print(x)

x = torch.zeros(5,3,dtype = torch.long)
x = torch.tensor(2.3,3.4)
#利用已有张量创建相同大小的
x = x.new_ones(5,3,dtype = torch.double)
y = torch.randn_like(X,dtype = torch.float)
#获取张量大小
print(x.size) # [5,3]
  • pytorch 的基本运算

    • 加法:

    1. x+y

    2. torch.add(x,y)

    3. torch.add(x,y,result)

    4. y.add_(x)—>y = y+x

    • 张量切片

    • 改变形状 torch.view()

    • 只有一个元素时, .item() 获取该元素,常用于获取loss

    • 如果有一个列表的元素 .tolist()

    • tensor 和array之间转化 - tensor 和 array是共享底层空间 - tensor → array:tensor.numpy() - array → tensor:torch.from_numpy()

y = torch.rand(5,3)
print(y)
b = y.numpy()
print(b)
print("--------------")
y.add_(1)
print(y)
print(b)

  • GPU
import torch
x = torch.rand(2,2)
if torch.cuda.is_available():
    device = torch.device("cuda")
    y = torch.ones_like(x,device = device)
    x = x.to(device)
    z = x+y
    print(z)
    print("*********")
    print(z.to("cpu",torch.double))

方法后加_构成新的方法,该方法原地改变属性值,例如:y.add_(x) —>y = y+x , y值改变

torch.Tensor

在整个Pytorch框架中,所有的神经网络本质上都是一个autograd package(自动求导工具包);autograd package提供了一个对Tensors上所有的操作进行自动微分的功能

  • torch.Tensor是整个package中的核心类,如果将属性 .require_grad 设置为True,它将追踪在这个类上定义的所有操作。当代码要进行反向传播的时候,直接调用 .backward() 就可以自动计算所有的梯度,在这个Tensor上的所有梯度将被累加进属性**.grad**中;
import torch
x1 = torch.ones(3,3)
print(x1)
x2 = torch.ones(2,2,requires_grad=True)
print(x2)
y = x2+1
print(y)

print(x2.grad_fn)
print(y.grad_fn)

  • 如果想终止一个Tensor在计算图中的追踪回溯,只需要执行 .detach() 就可以将该Tensor从计算图中撤下,在未来的回溯计算中也不会再计算该Tensor;
  • 除了 .detach() ,如果想终止对计算图的回溯,也就是不再进行传播求导数的过程,也可以采用代码块的方式 with torch.no_grad(): ,这种方式非常适用于对模型进行预测的时候,因为预测阶段不再需要对梯度进行计算。
out.backward()
print(x2.grad)

print(x2.requires_grad)
print((x2 ** 2).requires_grad)

# 终止自动求导的代码块编写方式
with torch.no_grad():
    print((x2 ** 2).requires_grad)

# 利用detach方法
print(x2.requires_grad)
y = x2.detach()
print(y.requires_grad)
# requires_grad的值不同不代表两者值不相等
print(x2.eq(y).all())


  • 关于torch.Function:

    • Function类是与Tensor类同等重要的一个核心类,它和Tensor共同构建了一个完整的类,每一个Tensor拥有一个 .grad_fn 属性,代表引用了哪个具体的Function创建了该Tensor。
    • 如果某个张量Tensor是用户自定义的,则其对应的grad_fn 为 None。

构建一个神经网络

torch.nn:主要的工具包;依赖autograd来定义模型,并对其自动求导

构建神经网络的典型流程:

  • 定义一个拥有可学习参数的神经网络
  • 遍历训练数据集
  • 处理输入数据使其流经神经网络
  • 计算损失值
criterion = nn.MSEloss()
loss = criterion(output,target)
  • 将网络参数的梯度进行反向传播·
loss.backward()
  • 以一定的规则更新网络的权重
# 导入若干工具包
import torch
import torch.nn as nn
import torch.nn.functional as F

# 定义一个简单的网络类
class Net(nn.Module):

    def __init__(self):
        super(Net,self).__init__()
        # 定义第一层卷积神经网络,输入通道维度=1,输出通道维度=6,卷积核大小为3*3
        self.conv1 = nn.Conv2d(1, 6, 3)
        # 定义第二层卷积神经网络,输入通道维度=6,输出通道维度=16,卷积核大小3*3
        self.conv2 = nn.Conv2d(6, 16, 3)
        # 定义三层全连接网络 32*32
        self.fc1 = nn.Linear(16 * 6 * 6, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)
    # 前向逻辑
    def forward(self,x):
        # 在(2,2)的池化窗口下执行最大池化操作
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)
        x = x.view(-1,self.num_flat_features(x))
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

    def num_flat_features(self,x):
        # 计算size,除了第0个维度上的batch_size
        size = x.size()[1:]
        num_features = 1
        for s in size:
            num_features *= s
        return num_features

net = Net()
print(net)

这段代码里面在卷积层到第一个全连接层的输入参数需要进行计算,其实和num_flat_feature(x)的结果是一样的,计算过程如下:

  • 模型中的可训练参数,都可以通过 net.parameters()来获得:
params = list(net.parameters())
print(len(params))
print(params[0].size())
  • 权重更新
input = torch.randn(1, 1, 32, 32)

target = torch.rand(10)
target = target.view(1, -1)
criterion = nn.MSELoss()
optimer = optim.SGD(net.parameters(), lr=0.01)
# 在反向传播前首先需要对优化器进行梯度清零,以免不同批次之间的梯度累加
optimer.zero_grad()
output = net(input)
loss = criterion(output, target)

# 对损失执行反向传播操作
loss.backward()
# 参数的更新通过一行标准代码来执行
optimer.step()