栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

《Pytorch学习指南》- 基础API(4)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

《Pytorch学习指南》- 基础API(4)

1. Pytorch编程技巧 1.1 Pytorch模型的使用
  • torch.saves(state, dir)
    1. 保存/序列化
  • torch.load(dir)
    1. 加载模型
1.2 Pytorch并行化操作
  • torch.get num threads():
    1. 获得用于并行化CPU操作的OpenMP线程数
  • torch.set_ num threads(int):
    1. 设定用于并行化CPU操作的OpenMP线程数
1.3 Tensor的相关配置
  • torch.is_ tensor()
    1. 如果是pytorch的tensor类型返回true
  • torch.is_ storage()
    1. 如果是pytorch的storage类型返回ture
  • torch.set flush_ denormal(mode)
    1. 防止- -些不正常的元素产生
  • torch.set_default_ dtype(d)
    1. 对torch.tensor() 设置默认的浮点类型
  • torch.set_printoptions(precision= None, threshold=None, edgeitems = None, linewidth=None, profile=None)
    1. 设置printing的打印参数
1.4 Tensor与numpy的相互转换
  • torch.from_ numpy(ndarry)
  • a.numpy()
import torch
import numpy as np

a = np.zeros([2, 2])
out = torch.from_numpy(a)

# out = out.to(torch.device("cuda"))
out = out.to(torch.device("cpu"))
2. AutoGrad的概念
  • torch.autograd.grad(outputs, inputs, grad_ outputs=None, retain graph= None,create_ graph=False, only_ inputs =True, allow_ unused= False)
    计算和返回output关 于inputs的梯度的和。

    1. outputs :函数的因变量,即需要求导的那个函数
    2. inputs :函数的自变量,
    3. grad_ _outputs :同backward
    4. only_ inputs:只计算input的梯度
    5. allow_ unused( bool,可选) :如果为False,当计算输出出错时(因此他们的梯度永远是0)指明不使用的inputs。
  • torch.autograd 包中的其他函数

    1. torch.autograd.enable_grad:启动梯度计算的上下文管理器
    2. torch.autograd.no_grad :禁止梯度计算的上下文管理器
    3. torch.autograd.set_ grad. enabled(mode):设置是否进行梯度计算的上下文管
      理器。
  • torch.autograd.Function

    1. 每一个原始的自动求导运算实际上是两个在Tensor上运行的函数
    2. forward函数计算从输入Tensors获得的输出Tensors
    3. backward函数接收输出Tensors对于某个标量值的梯度,并且计算输入Tensors相对于该相同标量值的梯度
    4. 最后,利用apply方法执行相应的运算定义在Function类的父类Functionbase中定义的一 个方法
import torch

class line(torch.autograd.Function):

    @staticmethod
    def forward(ctx, w, x, b):
        """
            前向传播
        :param ctx:
        :param w:
        :param x:
        :param b:
        :return:
        """
        #y = w*x +b
        # 将变量存储
        ctx.save_for_backward(w, x, b)
        return w * x + b


    @staticmethod
    def backward(ctx, grad_out):
        """
            反向传播
        :param ctx:
        :param grad_out:
        :return:
        """
        # 获取在forward中存储的变量
        w, x, b = ctx.saved_tensors

        grad_w = grad_out * x
        grad_x = grad_out * w
        grad_b = grad_out

        return grad_w, grad_x, grad_b


w = torch.rand(2, 2, requires_grad=True)
x = torch.rand(2, 2, requires_grad=True)
b = torch.rand(2, 2, requires_grad=True)

out = line.apply(w, x, b)
out.backward(torch.ones(2, 2))

print(w, x, b)
print(w.grad, x.grad, b.grad)
3. torch.nn 库
  • torch.nn是专门为神经网络设计的模块化接口。

  • nn构建于autograd之上,可以用来定义和运行神经网络。

    1. nn.Parameter
    2. nn.Linear&nn.conv2d等等
    3. nn.functional
    4. nn.Module
    5. nn.Sequential
  • nn.Parameter

    1. 定义可训练参数
    2. self.my_ param = nn.Parameter(torch.randn(1))
    3. self.register_ parameter
    4. nn.ParameterList & nn.ParameterDict
  • nn.Linear&nn.conv2d&nn.ReLU&nn.MaxPool2d(2))&nn.MSELoss等等

    • 各种神经网络层的定义,继承于nn.Module的子类
      1. self.conv1 = nn.Conv2d(1,6, (5,5))
      2. 调用时: self.conv1(x)
    • 参数为parameter类型
      1. layer = nn.Linear(1,1)
      2. layer.weight = nn.Parameter(torch.FloatTensor([[0]]))
      3. layer.bias = nn.Parameter(torch.FloatTensor([0]))
  • nn.functional

    • 包含torch.nn库中所有函数,包含大量loss和activation function
      1. torch.nn.functional.conv2d(input, weight, bias=None,stride=1, padding=0, dilation=1, groups=1)
      2. torch.nn.conv2d 是一个类
    • nn.functional.xxx是函数接口
    • nn.functional.xxx无法与nn.Sequential结合使用
    • 没有学习参数的(eg. maxpool, loss_func, activation func)等根据个人选择使用nn.functional.xxx或nn.Xxx 需要特别注意dropout层
  • nn 与nn.functional有什么区别?.nn.functional.xxx是函数接口

    1. nn.Xxx是.nn.functional.xxx的类封装,并且nn.Xx×都继承于一个共同祖先 nn.Module
    2. nn.Xxx除了具有nn.functional.xxx功能之外,内部附带nn.Module相关的属性和方法,eg. train(), eval(),load_state_dict, state_dict
  • nn.Module

    1. 它是一个抽象概念,既可以表示神经网络中的某个层(layer),也可以表示一个包含很多层的神经网络
    2. model.parameters()
    3. model.buffers()
    4. model.state_dict()
    5. model.modules()
    6. forward(), to()
    7. https://pytorch.org/docs/stable/nn.html#torch.nn.Module
  • Parameters VS buffers

    1. 一种是反向传播需要被optimizer更新的,称之为parameter
      • self.register_parameter(“param”, param)
      • self.param = nn.Parameter(torch.randn(1))
    2. —种是反向传播不需要被optimizer更新,称之为buffer
      • self.register_buffer(‘my_buffer’, torch.randn(1))
  • state_dict() & load_state_dict

    1. 保存模型和加载模型
    2. torch.save(obj=model.state_dict(), f= “models/net.pth”)
    3. model.load_state_dict(torch.load(“models/net.pth”))
  • visdom : Facebook专门为Pytorch开发的一款可视化工具,开源于2017年3月,提供了大多数的科学运算可视化API:

    1. https://github.com/facebookresearch/visdom
    2. 支持数值(折线图,直方图等)、图像、文本以及视频等·支持Pytorch、Torch和Numpy
    3. 用户可以通过编程的方式组织可视化空间或者通过用户接口为数据打造仪表板,检查实验结果和调试代码。
      • env:环境& pane:窗格
    4. 安装
      • pip install visdom
    5. 启动服务
      • python -m visdom.server
  • tensorboardX介绍

    1. scalar, image, figure, histogram, audio, text, graph,onnx_graph, embedding, pr_curve and videosummaries等不同的可视化展示方式
    2. pip3 install tensorboardX
4. TensorboardX
  • tensorboardX介绍
    1. scalar, image, figure, histogram, audio, text, graph,onnx_graph, embedding, pr_curve and videosummaries等不同的可视化展示方式
    2. pip3 install tensorboardX
  • 使用方式
    1. 生成日志到指定的目录
    2. tensorboard --logdir 日志路径
from tensorboardX import SummaryWriter

# 定义文件路径
writer = SummaryWriter("log")
for i in range(100):
    writer.add_scalar("a", i, global_step=i)
    writer.add_scalar("b", i ** 2, global_step=i)
writer.close()

11488@DESKTOP-4KT7IH4 MINGW64 /g/SpellWorkSpace/PytorchSpace/pytorch-code-edu/base_api/log (master)
$ tensorboard --logdir ./
2021-10-15 10:24:01.331265: W tensorflow/stream_executor/platform/default/dso_loader.cc:59] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
2021-10-15 10:24:01.331798: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
Serving TensorBoard on localhost; to expose to the network, use a proxy or pass --bind_all
TensorBoard 2.6.0 at http://localhost:6006/ (Press CTRL+C to quit)
5. Torchvision介绍
  • torchvision是独立于pytorch的关于图像操作的一些方便工具库。
    1. https://github.com/pytorch/vision
    2. https://pytorch.org/docs/master/torchvision/
  • torchvision主要包括一下几个包:
    1. vision.datasets:几个常用视觉数据集,可以下载和加载
    2. vision.models:已经训练好的模型,例如: AlexNet, VGG,ResNet
    3. vision.transforms:常用的图像操作, 例如:随机切割, 旋转, 数据类型转换, 图像到tensor, numpy 数组到tensor, tensor到图像等
    4. vision.utils、vision.io、vision.ops
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/326135.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号