> 文章列表 > 【写博客常用】Colab Pytorch神经网络基本构建

【写博客常用】Colab Pytorch神经网络基本构建

【写博客常用】Colab  Pytorch神经网络基本构建

【写博客常用】Colab & Pytorch调用基本模型

  • 1 使用Colab
  • 2 连接GPU
  • 3 tensor
  • 4 计算梯度
  • 5 读取data,使用torch.utils.data里面的Dataset和DataLoader
  • 6 网络构造
    • 6.1 结构
    • 6.2 Linear
    • 6.3 定义一个自己的model
    • 6.4 定义自己的loss
    • 6.5 optimizer
    • 6.6 神经网络构建流程
      • 6.6.1 前期设置
      • 6.6.2 train设置
      • 6.6.3 valid设置
      • 6.6.4 test 设置
      • 6.6.5 存起来
  • 7 参考资料

1 使用Colab

Colab中可以直接打入程序的部分称为code block。直接打入的程序用python来诠释。打上!则以shell script来修饰。cd前要加%

【写博客常用】Colab  Pytorch神经网络基本构建

from google.colab import drive # Import a library named google.colab
drive.mount('/content/drive', force_remount=True) # mount the content to the directory `/content/drive`
from google.colab import drive
drive.mount('/content/drive')

会出现MyDrive的云端存储,加载的照片等不会消失。
【写博客常用】Colab  Pytorch神经网络基本构建

2 连接GPU

change runtime type选择GPU
【写博客常用】Colab  Pytorch神经网络基本构建
右上角代表连接好GPU了
【写博客常用】Colab  Pytorch神经网络基本构建

3 tensor

【写博客常用】Colab  Pytorch神经网络基本构建
1.如何产生tensor:【写博客常用】Colab  Pytorch神经网络基本构建
2.拿掉一个tensor:
【写博客常用】Colab  Pytorch神经网络基本构建
3.加上一个维度:
【写博客常用】Colab  Pytorch神经网络基本构建
4.维度对调
【写博客常用】Colab  Pytorch神经网络基本构建
5.拼接
【写博客常用】Colab  Pytorch神经网络基本构建
6.加减乘除操作
【写博客常用】Colab  Pytorch神经网络基本构建
【写博客常用】Colab  Pytorch神经网络基本构建
7.选择运行的设备,用torch.cuda.is_available()看是否有空闲的显卡。
【写博客常用】Colab  Pytorch神经网络基本构建

4 计算梯度

requires_grad : bool值,若真表示可以进行对该值求导,否则不能;意思差不多是能不能把设置的值当变量来看。
以下面为例:
【写博客常用】Colab  Pytorch神经网络基本构建
存的结果会放在x上面
【写博客常用】Colab  Pytorch神经网络基本构建

5 读取data,使用torch.utils.data里面的Dataset和DataLoader

Dataset:读数据,一次返回一行数据,返回数据的size
【写博客常用】Colab  Pytorch神经网络基本构建
Dataloader:shuffle把每次读data数据是乱的,train的时候要乱,test的时候不要乱,从dataset里一次回传多个data组成一个mini-batch:
【写博客常用】Colab  Pytorch神经网络基本构建
【写博客常用】Colab  Pytorch神经网络基本构建

6 网络构造

6.1 结构

【写博客常用】Colab  Pytorch神经网络基本构建

6.2 Linear

可以通过linear更换神经网络的维度
【写博客常用】Colab  Pytorch神经网络基本构建
【写博客常用】Colab  Pytorch神经网络基本构建
【写博客常用】Colab  Pytorch神经网络基本构建

6.3 定义一个自己的model

sequential依次的放入自己需要的layer
【写博客常用】Colab  Pytorch神经网络基本构建
init定义网络结构
forward是给定x算output的

6.4 定义自己的loss

【写博客常用】Colab  Pytorch神经网络基本构建

6.5 optimizer

算gradient descent
要把model.parameters丢进去才能更新model
【写博客常用】Colab  Pytorch神经网络基本构建

6.6 神经网络构建流程

6.6.1 前期设置

构建:
读数据
把数据放入DataLoader
【写博客常用】Colab  Pytorch神经网络基本构建

6.6.2 train设置

把mode设成train才能更新参数:model.train()
每次迭代要把之前的gradiant设置为0:optimizer.zero_grad()
把数据放到GPU上面去:x,y=x.to(device),y.to(device)
计算输出:pred=model(x)
计算loss:loss=criterion(pred,y)
算出gradient:loss.backward()
算出来之后还没更新model,需要及时更新:optimizer.step()
【写博客常用】Colab  Pytorch神经网络基本构建

6.6.3 valid设置

不希望在valid阶段算gradiant,不需要更新模型了:with torch.no_grad()
【写博客常用】Colab  Pytorch神经网络基本构建

6.6.4 test 设置

【写博客常用】Colab  Pytorch神经网络基本构建

6.6.5 存起来

最后把model给存起来
【写博客常用】Colab  Pytorch神经网络基本构建

7 参考资料

ML2021 Pytorch tutorial part 1