当前位置:   article > 正文

pytorch能做什么?_pytorch可以解决什么

pytorch可以解决什么

GPU加速

在处理大数据时在cpu和gpu上分别进行矩阵运算

    import torch
    import time
    print(torch.__version__)
    print(torch.cuda.is_available())
    
    #俩矩阵
    a=torch.rand(10000,1000)
    b=torch.rand(1000,2000)
    
    #cpu测试时间
    t0=time.time()
    c=torch.matmul(a,b)
    t1=time.time()
    print(a.device,t1-t0,c.norm(2))
    
    #gpu测试时间
    device=torch.device('cuda')
    a=a.to(device)
    b=b.to(device)
    t0=time.time()
    c=torch.matmul(a,b)
    t1=time.time()
    print(a.device,t1-t0,c.norm(2))
    
    #再次测试
    t0=time.time()
    c=torch.matmul(a,b)
    t1=time.time()
    print(a.device,t1-t0,c.norm(2))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

可以发现第一次用cuda运行居然比cpu的要慢,但是第二次却快非常多。原因是第一遍需要进行gpu环境的初始化,是需要占用一些时间的。第二次就非常的真实。

在这里插入图片描述

自动求导

torch.tensor张量可看这篇:https://www.jianshu.com/p/5ae644748f21/

在机器学习中就是神经网络反向传播的时候要更新参数,这时需要对其求偏导,也就是“梯度”

    import torch
    from torch import autograd
    #对abcx分别初始化赋值
    x=torch.tensor(1.)
    a=torch.tensor(1.,requires_grad=True)
    b=torch.tensor(2.,requires_grad=True)
    c=torch.tensor(3.,requires_grad=True)
    
    y=a**2*x+b*x+c
    # 对a,b,c分别求偏导
    print('before:',a.grad,b.grad,c.grad)
    grads=autograd.grad(y,[a,b,c])
    print('after: ',grads[0],grads[1],grads[2])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

运行结果可以发现在调用autograd之前并没有求导。
grands结果展示

常用网络层

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/862051
推荐阅读
相关标签
  

闽ICP备14008679号