当前位置: 首页 > news >正文

强大的PyTorch:10分钟让你了解深度学习领域新流行的框架

摘要: 今年一月份开源的PyTorch,因为它强大的功能,它现在已经成为深度学习领域新流行框架,它的强大源于它内部有很多内置的库。本文就着重介绍了其中几种有特色的库,它们能够帮你在深度学习领域更上一层楼。

更多深度文章,请关注:https://yq.aliyun.com/cloud


PyTorch由于使用了强大的GPU加速的Tensor计算(类似numpy)和基于tape的autograd系统的深度神经网络。这使得今年一月份被开源的PyTorch成为了深度学习领域新流行框架,许多新的论文在发表过程中都加入了大多数人不理解的PyTorch代码。这篇文章我们就来讲述一下我对PyTorch代码的理解,希望能帮助你阅读PyTorch代码。整个过程是基于贾斯汀·约翰逊的伟大教程。如果你想了解更多或者有超过10分钟的时间,建议你去读下整篇代码。

PyTorch由4个主要包装组成:

  1. Torch:类似于Numpy的通用数组库,可以在将张量类型转换为(torch.cuda.TensorFloat)并在GPU上进行计算。
  2. torch.autograd:用于构建计算图形并自动获取渐变的包
  3. torch.nn:具有共同层和成本函数的神经网络库
  4. torch.optim:具有通用优化算法(如SGD,Adam等)的优化包

1.导入工具

你可以这样导入PyTorch:

 
  
import torch # arrays on GPU
import torch.autograd as autograd #build a computational graph
import torch.nn as nn # neural net library
import torch.nn.functional as F # most non-linearities are here
import torch.optim as optim # optimization package

 

 

2.torch数组取代了numpy ndarray - >在GPU支持下提供线性代数

第一个特色,PyTorch提供了一个像Numpy数组一样的多维数组,当数据类型被转换为(torch.cuda.TensorFloat)时,可以在GPU上进行处理。这个数组和它的关联函数是一般的科学计算工具。

从下面的代码中,我们可以发现,PyTorch提供的这个包的功能可以将我们常用的二维数组变成GPU可以处理的三维数组。这极大的提高了GPU的利用效率,提升了计算速度。

大家可以自己比较 Torch和numpy ,从而发现他们的优缺点。

 

# 2 matrices of size 2x3 into a 3d tensor 2x2x3
d=[[[1., 2.,3.],[4.,5.,6.]],[[7.,8.,9.],[11.,12.,13.]]]
d=torch.Tensor(d) # array from python list
print "shape of the tensor:",d.size()
# the first index is the depth
z=d[0]+d[1]
print "adding up the two matrices of the 3d tensor:",z
shape of the tensor: torch.Size([2, 2, 3])
adding up the two matrices of the 3d tensor: 
  8  10  12
 15  17  19
[torch.FloatTensor of size 2x3]
# a heavily used operation is reshaping of tensors using .view()
print d.view(2,-1) #-1 makes torch infer the second dim
  1   2   3   4   5   6
  7   8   9  11  12  13
[torch.FloatTensor of size 2x6]

 

3.torch.autograd可以生成一个计算图 - >自动计算梯度

第二个特色是autograd包,其提供了定义计算图的能力,以便我们可以自动计算渐变梯度。在计算图中,一个节点是一个数组,边(edge)是on数组的一个操作。要做一个计算图,我们需要在(torch.aurograd.Variable())函数中通过包装数组来创建一个节点。那么我们在这个节点上所做的所有操作都将被定义为边,它们将是计算图中新的节点。图中的每个节点都有一个(node.data)属性,它是一个多维数组和一个(node.grad)属性,这是相对于一些标量值的渐变(node.grad也是一个.Variable()) 。在定义计算图之后,我们可以使用单个命令(loss.backward())来计算图中所有节点的损耗梯度。

  • 使用torch.autograd.Variable()将张量转换为计算图中的节点。
    • 使用x.data访问其值。
    • 使用x.grad访问其渐变。
  • 在.Variable()上执行操作,绘制图形的边缘。

 

# d is a tensor not a node, to create a node based on it:
x= autograd.Variable(d, requires_grad=True)
print "the node's data is the tensor:", x.data.size()
print "the node's gradient is empty at creation:", x.grad # the grad is empty right now
the node's data is the tensor: torch.Size([2, 2, 3])
the node's gradient is empty at creation: None
# do operation on the node to make a computational graph
y= x+1
z=x+y
s=z.sum()
print s.creator
<torch.autograd._functions.reduce.Sum object at 0x7f1e59988790>
# calculate gradients
s.backward()
print "the variable now has gradients:",x.grad
the variable now has gradients: Variable containing:
(0 ,.,.) = 
  2  2  2
  2  2  2
(1 ,.,.) = 
  2  2  2
  2  2  2
[torch.FloatTensor of size 2x2x3]

 

4.torch.nn包含各种NN层(张量行的线性映射)+(非线性)-->

其作用是有助于构建神经网络计算图,而无需手动操纵张量和参数,减少不必要的麻烦。

 

第三个特色是高级神经网络库(torch.nn),其抽象出了神经网络层中的所有参数处理,以便于在通过几个命令(例如torch.nn.conv)就很容易地定义NN。这个包也带有流行的损失函数的功能(例如torch.nn.MSEloss)。我们首先定义一个模型容器,例如使用(torch.nn.Sequential)的层序列的模型,然后在序列中列出我们期望的层。这个高级神经网络库也可以处理其他的事情,我们可以使用(model.parameters())访问参数(Variable())

 

# linear transformation of a 2x5 matrix into a 2x3 matrix
linear_map=nn.Linear(5,3)
print "using randomly initialized params:", linear_map.parameters
using randomly initialized params: <bound method Linear.parameters of Linear (5 -> 3)>
# data has 2 examples with 5 features and 3 target
data=torch.randn(2,5) # training
y=autograd.Variable(torch.randn(2,3)) # target
# make a node
x=autograd.Variable(data, requires_grad=True)
# apply transformation to a node creates a computational graph
a=linear_map(x)
z=F.relu(a)
o=F.softmax(z)
print "output of softmax as a probability distribution:", o.data.view(1,-1)
# loss function
loss_func=nn.MSELoss() #instantiate loss function
L=loss_func(z,y) # calculateMSE loss between output and target
print "Loss:", L
output of softmax as a probability distribution: 
 0.2092  0.1979  0.5929  0.4343  0.3038  0.2619
[torch.FloatTensor of size 1x6]
Loss: Variable containing:
 2.9838
[torch.FloatTensor of size 1]

 

我们还可以通过子类(torch.nn.Module)定义自定义层,并实现接受(Variable())作为输入的(forward())函数,并产生(Variable())作为输出。我们也可以通过定义一个时间变化的层来做一个动态网络。

  • 定义自定义层时,需要实现2个功能:
    • init_函数必须始终被继承,然后层的所有参数必须在这里定义为类变量(self.x)
    • 正向函数是我们通过层传递输入的函数,使用参数对输入进行操作并返回输出。输入需要是一个autograd.Variable(),以便pytorch可以构建图层的计算图。

 

class Log_reg_classifier(nn.Module):
    def __init__(self, in_size,out_size):
        super(Log_reg_classifier,self).__init__() #always call parent's init 
        self.linear=nn.Linear(in_size, out_size) #layer parameters
    def forward(self,vect):
        return F.log_softmax(self.linear(vect)) # 

 

5.torch.optim也可以做优化—>

我们使用torch.nn构建一个nn计算图,使用torch.autograd来计算梯度,然后将它们提供给torch.optim来更新网络参数。

第四个特色是与NN库一起工作的优化软件包(torch.optim)。该库包含复杂的优化器,如Adam,RMSprop等。我们定义一个优化器并传递网络参数和学习率(opt = torch.optim.Adam(model.parameters(),lr = learning_rate)),然后我们调用(opt.step())对我们的参数进行近一步更新。

 

optimizer=optim.SGD(linear_map.parameters(),lr=1e-2) # instantiate optimizer with model params + learning rate
# epoch loop: we run following until convergence
optimizer.zero_grad() # make gradients zero
L.backward(retain_variables=True)
optimizer.step()
print L
Variable containing:
 2.9838
[torch.FloatTensor of size 1]

 

建立神经网络很容易,但是如何协同工作并不容易。这是一个示例显示如何协同工作:

 

# define model
model = Log_reg_classifier(10,2)
# define loss function
loss_func=nn.MSELoss() 
# define optimizer
optimizer=optim.SGD(model.parameters(),lr=1e-1)
# send data through model in minibatches for 10 epochs
for epoch in range(10):
    for minibatch, target in data:
        model.zero_grad() # pytorch accumulates gradients, making them zero for each minibatch
        #forward pass
        out=model(autograd.Variable(minibatch))
        #backward pass 
        L=loss_func(out,target) #calculate loss
        L.backward() # calculate gradients
        optimizer.step() # make an update step

 

希望上述的介绍能够帮你更好的阅读PyTorch代码。  

本文由北邮@爱可可-爱生活老师推荐,阿里云云栖社区组织翻译。

文章原标题《Understand PyTorch code in 10 minutes》,

作者: Hamidreza Saghir,机器学习研究员 - 多伦多大学博士生 译者:袁虎 审阅:阿福

 

文章为简译,更为详细的内容,请查看原文

 

原文链接

转载于:https://www.cnblogs.com/jzy996492849/p/7229083.html

相关文章:

  • 如何修改远程桌面3389端口
  • 17.07.24 Linux 7 文件系统管理
  • python日记----2017.7.25
  • Js实现点击查看全文(类似今日头条、知乎日报效果)
  • 用quicker-worker.js轻松跑一个大数据遍历
  • HttpClient4.2 Fluent API学习
  • 第二天
  • HCNA
  • AR 与 AI 技术是如何让勇士重回王者的?
  • for循环结构break和continue的用法和区别
  • Java中的关键字
  • JSON.parse()在火狐中的BUG
  • IBM:我们不会放弃XIV存储阵列
  • 客户端数据存储----Cookie From 《高程3》
  • Hadoop2.6下安装Hive
  • [分享]iOS开发-关于在xcode中引用文件夹右边出现问号的解决办法
  • 【vuex入门系列02】mutation接收单个参数和多个参数
  • Fundebug计费标准解释:事件数是如何定义的?
  • Intervention/image 图片处理扩展包的安装和使用
  • Laravel核心解读--Facades
  • Vue.js源码(2):初探List Rendering
  • 从零开始的webpack生活-0x009:FilesLoader装载文件
  • 第十八天-企业应用架构模式-基本模式
  • 给github项目添加CI badge
  • 实习面试笔记
  • d²y/dx²; 偏导数问题 请问f1 f2是什么意思
  • ​批处理文件中的errorlevel用法
  • # Panda3d 碰撞检测系统介绍
  • #微信小程序:微信小程序常见的配置传旨
  • (C语言)输入自定义个数的整数,打印出最大值和最小值
  • (react踩过的坑)antd 如何同时获取一个select 的value和 label值
  • (二十三)Flask之高频面试点
  • (附源码)php新闻发布平台 毕业设计 141646
  • (三十五)大数据实战——Superset可视化平台搭建
  • (四) Graphivz 颜色选择
  • ******之网络***——物理***
  • .htaccess配置常用技巧
  • .net 打包工具_pyinstaller打包的exe太大?你需要站在巨人的肩膀上-VC++才是王道
  • .php结尾的域名,【php】php正则截取url中域名后的内容
  • /proc/interrupts 和 /proc/stat 查看中断的情况
  • [100天算法】-实现 strStr()(day 52)
  • [asp.net core]project.json(2)
  • [C++]命名空间等——喵喵要吃C嘎嘎
  • [CareerCup] 2.1 Remove Duplicates from Unsorted List 移除无序链表中的重复项
  • [CareerCup] 6.1 Find Heavy Bottle 寻找重瓶子
  • [CTF]php is_numeric绕过
  • [Hadoop in China 2011] Hadoop之上 中国移动“大云”系统解析
  • [HOW TO]怎么在iPhone程序中实现可多选可搜索按字母排序的联系人选择器
  • [HTML]Web前端开发技术6(HTML5、CSS3、JavaScript )DIV与SPAN,盒模型,Overflow——喵喵画网页
  • [JavaEE系列] Thread类的基本用法
  • [LeetCode] Merge Two Sorted Lists
  • [LeetCode系列]3元素最近和问题的O(n^2)解法
  • [NKCTF 2024]web解析
  • [NOIP2004] 提高组 洛谷P1090 合并果子
  • [Pyhton]weakref 弱引用