浙江好梦来投资 发表于 2023-2-24 23:45:08

pytorch 简介及常用工具包展示

一、pytorch 简介


[*]Pytorch是torch的python版本,是由Facebook开源的神经网络框架,专门针对 GPU 加速的深度神经网络(DNN)编程。Torch 是一个经典的对多维矩阵数据进行操作的张量
(tensor )库,在机器学习和其他数学密集型应用有广泛应用。
[*]Pytorch的计算图是动态的,可以根据计算需要实时改变计算图。
[*]由于Torch语言采用 Lua,导致在国内一直很小众,并逐渐被支持 Python 的 Tensorflow 抢走用户。作为经典机器学习库 Torch 的端口,PyTorch 为 Python 语言使用者提供了舒适的写代码选择。

二、pytorch 优势


[*]1.简洁:
PyTorch的设计追求最少的封装,尽量避免重复造轮子。不像 TensorFlow 中充斥着session、graph、operation、name_scope、variable、tensor、layer等全新的概念,PyTorch 的设计遵循tensor→variable(autograd)→nn.Module 三个由低到高的抽象层次,分别代表高维数组(张量)、自动求导(变量)和神经网络(层/模块),而且这三个抽象之间联系紧密,可以同时进行修改和操作。
[*]2.速度:
PyTorch 的灵活性不以速度为代价,在许多评测中,PyTorch 的速度表现胜过 TensorFlow和Keras 等框架。
[*]3.易用:
PyTorch 是所有的框架中面向对象设计的最优雅的一个。PyTorch的面向对象的接口设计来源于Torch,而Torch的接口设计以灵活易用而著称,Keras作者最初就是受Torch的启发才开发了Keras。
[*]4.活跃的社区:
PyTorch 提供了完整的文档,循序渐进的指南,作者亲自维护的论坛,供用户交流和求教问题。Facebook 人工智能研究院对 PyTorch 提供了强力支持。

三、pytorch 常用工具包


[*]torch :类似 NumPy 的张量库,支持GPU;
[*]torch.autograd :基于 type 的自动区别库,支持 torch 之中的所有可区分张量运行;
[*]torch.nn :为最大化灵活性而设计,与 autograd 深度整合的神经网络库;
[*]torch.optim:与 torch.nn 一起使用的优化包,包含 SGD、RMSProp、LBFGS、Adam 等标准优化方式;
[*]torch.multiprocessing: python 多进程并发,进程之间 torch Tensors 的内存共享;
[*]torch.utils:数据载入器。具有训练器和其他便利功能;
[*]torch.legacy(.nn/.optim) :出于向后兼容性考虑,从 Torch 移植来的 legacy 代码;

四、pytorch 注意点

特别注意一个问题:
通道问题:不同视觉库对于图像读取的方式不一样,图像通道也不一样:
opencv 的 imread 默认顺序时 H * W * C
pytorch的Tensor是 C * H * W
Tensorflow是两者都支持

五、pytorch 理解


[*]numpy风格的tensor操作

[*]pytorch对tensor提供的API参照了numpy

[*]变量自动求导

[*]在计算过程形成的计算图中,参与的变量可快速计算出自己对于目标函数的梯度

[*]神经网络求导及损失函数优化等高层封装

[*]网络层封装在torch.nn
[*]损失函数封装在torch.functional
[*]优化函数封装在torch.optim


六、pytorch-Tensor

1. tensor 数据类型

tensor数据类型:3浮点(float16,float32,float64)5整数(int16,int32,int64,int8+uint8)
Data typedtypeCPU tensorGPU tensor16-bit floating pointtorch.float16 or torch.halftorch.HalfTensortorch.cuda.HalfTensor32-bit floating pointtorch.float32 or torch.floattorch.FloatTensortorch.cuda.FloatTensor64-bit floating pointtorch.float64 or torch.doubletorch.DoubleTensortorch.cuda.DoubleTensorData typedtypeCPU tensorGPU tensor8-bit integer(unsigned)torch.uint8torch.ByteTensortorch.cuda.ByteTensor8-bit integer(signed)torch.int8torch.CharTensortorch.cuda.CharTensor16-bit integer(signed)torch.int16 or torch.shorttorch.ShortTensortorch.cuda.ShortTensor32-bit integer(signed)torch.int32 or torch.inttorch.IntTensortorch.cuda.IntTensor64-bit integer(signed)torch.int64 or torch.longtorch.LongTensortorch.cuda.LongTensor2. 创建 tensor 相关的 API

创建tensor的常见api
方法名说明Tensor()直接从参数构造张量,支持list和numpy数组eye(row,column)创建指定行数&列数的单位tensor(单位阵)linspace(start,end,count)在上创建c个元素的一维tensorlogspace(start,end,count)在上创建c个元素的一维tensorones(size)返回指定shape的tensor,元素初始值为1zeros(size)返回指定shape的tensor,元素初始值为0ones_like(t)返回一个tensor,shape与t相同,且元素初始值为1zeros_like(t)返回一个tensor,shape与t相同,且元素初始值为1arange(s,e,sep)在区间3. tensor 对象的 API

tensor 对象的方法
方法名作用size()返回张量的shapenumel()计算tensor的元素个数view(shape)修改tensor的shape,与np.reshape相似,view返回的是对象的共享内存resize类似于view,但在size超出时会重新分配内存空间item若为单元素tensor,则返回python的scalarfrom_numpy从numpy数据填充numpy返回ndarray类型
七、python 自动求导

tensor对象通过一系列运算组成动态图,每个tensor对象都有以下几个控制求导的属性。
变量作用requird_grad默认为False,表示变量是狗需要计算导数grad_fn变量的梯度函数grad变量对应的梯度
八、pytorch 神经网络

torch.nn提供了创建神经网络的基础构件,这些层都继承自Module类。下面是自己手动实现一个线性层(linear layer)。适当参考,以后直接调用现成的接口,这里稍微了解一下,无实际意义。 ​​​​
import torch

class Linear(torch.nn.Module):
    def __init__(self, in_features, out_features, bias=True):
      super(Linear, self).__init__()
      # torch.randn() 返回一个符合均值为0,方差为1的正态分布
      self.weight = torch.nn.Parameter(torch.randn(out_features, in_features))
      if bias:
            self.bias = torch.nn.Parameter(torch.randn(out_features))

    def forward(self, x):
      # xW+b
      x = x.mm(self.weight)
      if self.bias:
            x = x + self.bias.expand_as(x)
      return x

if __name__ == '__main__':
   
    net = Linear(3,2)
    x = net.forward
    print('11',x)下面表格中列出了比较重要的神经网络层组件。
对应的在nn.functional模块中,提供这些层对应的函数实现。
通常对于可训练参数的层使用module,而对于不需要训练参数的层如softmax这些,可以使用functional中的函数。

一些容器:
容器类型功能Module神经网络模块基类Sequential序贯模型,类似keras,用于构建序列型神经网络ModuleList用于存储层,不接受输入Parameters(t)模块的属性,用于保存其训练参数ParameterList参数列表1容器代码:
# 方法1 像
model1 = nn.Sequential()
model.add_module('fc1', nn.Linear(3,4))
model.add_module('fc2', nn.Linear(4,2))
model.add_module('output', nn.Softmax(2))

# 方法2
model2 = nn.Sequential(
          nn.Conv2d(1,20,5),
          nn.ReLU(),
          nn.Conv2d(20,64,5),
          nn.ReLU()
      )
# 方法3      
model3 = nn.ModuleList()

[*]torch.nn.Module提供了神经网络的基类,当实现神经网络时需要继承自此模块,并在初始化函数中创建网络需要包含的层,并实现forward函数完成前向计算,网络的反向计算会由自动求导机制处理。
[*]通常将需要训练的层写在init函数中,将参数不需要训练的层在forward方法里调用对应的函数来实现相应的层。
编码三步走:
在pytorch中就只需要分三步:

[*]写好网络;
[*]编写数据的标签和路径索引;
[*]把数据送到网络。
到此这篇关于pytorch 简介及常用工具包展示的文章就介绍到这了,更多相关pytorch 常用工具包内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

来源:https://www.jb51.net/article/276379.htm
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: pytorch 简介及常用工具包展示