首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

pytorch 的一些介绍以及常用工具包展示

  • 25-03-03 00:24
  • 4718
  • 6732
blog.csdn.net

文章目录

    • 一、pytorch 简介
    • 二、pytorch 优势
    • 三、pytorch 常用工具包
    • 四、pytorch 注意点
    • 五、pytorch 理解
    • 六、pytorch-Tensor
        • 1. tensor 数据类型
        • 2. 创建 tensor 相关的 API
        • 3. tensor 对象的 API
    • 七、python 自动求导
    • 八、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 常用工具包

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

四、pytorch 注意点

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

五、pytorch 理解

  1. numpy风格的tensor操作
    • pytorch对tensor提供的API参照了numpy
  2. 变量自动求导
    • 在计算过程形成的计算图中,参与的变量可快速计算出自己对于目标函数的梯度
  3. 神经网络求导及损失函数优化等高层封装
    • 网络层封装在torch.nn
    • 损失函数封装在torch.functional
    • 优化函数封装在torch.optim

六、pytorch-Tensor

1. tensor 数据类型

tensor数据类型:3浮点(float16,float32,float64)5整数(int16,int32,int64,int8+uint8)

Data typedtypeCPU tensorGPU tensor
16-bit floating pointtorch.float16 or torch.halftorch.HalfTensortorch.cuda.HalfTensor
32-bit floating pointtorch.float32 or torch.floattorch.FloatTensortorch.cuda.FloatTensor
64-bit floating pointtorch.float64 or torch.doubletorch.DoubleTensortorch.cuda.DoubleTensor
Data typedtypeCPU tensorGPU tensor
8-bit integer(unsigned)torch.uint8torch.ByteTensortorch.cuda.ByteTensor
8-bit integer(signed)torch.int8torch.CharTensortorch.cuda.CharTensor
16-bit integer(signed)torch.int16 or torch.shorttorch.ShortTensortorch.cuda.ShortTensor
32-bit integer(signed)torch.int32 or torch.inttorch.IntTensortorch.cuda.IntTensor
64-bit integer(signed)torch.int64 or torch.longtorch.LongTensortorch.cuda.LongTensor
2. 创建 tensor 相关的 API

创建tensor的常见api

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

tensor 对象的方法

方法名作用
size()返回张量的shape
numel()计算tensor的元素个数
view(shape)修改tensor的shape,与np.reshape相似,view返回的是对象的共享内存
resize类似于view,但在size超出时会重新分配内存空间
item若为单元素tensor,则返回python的scalar
from_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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

下面表格中列出了比较重要的神经网络层组件。
对应的在nn.functional模块中,提供这些层对应的函数实现。
通常对于可训练参数的层使用module,而对于不需要训练参数的层如softmax这些,可以使用functional中的函数。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dnU00LSM-1649391626450)(photo/图片.png)]

一些容器:

容器类型功能
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([nn.Linear(3,4), nn.ReLU(), nn.Linear(4,2)])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • torch.nn.Module提供了神经网络的基类,当实现神经网络时需要继承自此模块,并在初始化函数中创建网络需要包含的层,并实现forward函数完成前向计算,网络的反向计算会由自动求导机制处理。
  • 通常将需要训练的层写在init函数中,将参数不需要训练的层在forward方法里调用对应的函数来实现相应的层。

编码三步走:

在pytorch中就只需要分三步:

  1. 写好网络;
  2. 编写数据的标签和路径索引;
  3. 把数据送到网络。
文章知识点与官方知识档案匹配,可进一步学习相关知识
OpenCV技能树首页概览26480 人正在系统学习中
注:本文转载自blog.csdn.net的人工智能有点的文章"https://blog.csdn.net/weixin_44417441/article/details/124038308"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2492) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

101
推荐
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2024 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top