【PyTorch】学习笔记(01):初见PyTorch

【PyTorch】深度学习与Pytorch实战笔记


检查GPU加速是否可用

import torch
print(torch.__version__)
print(torch.cuda.is_available())

对比CPU与GPU方式速度区别

import 	torch
import  time

a = torch.randn(10000, 1000)
b = torch.randn(1000, 2000)

t0 = time.time()
c = torch.matmul(a, b)
t1 = time.time()
print(a.device, t1 - t0, c.norm(2))

device = torch.device('cuda')
a = a.to(device)
b = b.to(device)

t0 = time.time()
c = torch.matmul(a, b)
t2 = time.time()
print(a.device, t2 - t0, c.norm(2))# 第一次要准备环境,速度不准确

t0 = time.time()
c = torch.matmul(a, b)
t2 = time.time()
print(a.device, t2 - t0, c.norm(2))# 测试第二次

在这里插入图片描述

自动求导

y = a 2 x + b x + c y=a^{2} x+b x+c y=a2x+bx+c,求 x = 1 x=1 x=1时的导数
即求导: { ∂ y ∂ a = 2 a ⋅ x = 2 a x ∂ y ∂ b = x ∂ y ∂ c = 1 \left\{\begin{array}{l}\frac{\partial y}{\partial a}=2 a \cdot x=2 a x \\ \frac{\partial y}{\partial b}=x \\ \frac{\partial y}{\partial c}=1\end{array}\right. ay=2ax=2axby=xcy=1
x = 1 x=1 x=1,得到 { ∂ y ∂ a = 2 a ∂ y ∂ b = 1 ∂ y ∂ c = 1 \left\{\begin{array}{l}\frac{\partial y}{\partial a} =2a \\ \frac{\partial y}{\partial b} = 1\\ \frac{\partial y}{\partial c} = 1\end{array}\right. ay=2aby=1cy=1

import  torch
from    torch import autograd


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

print('before:', a.grad, b.grad, c.grad)
grads = autograd.grad(y, [a, b, c])
print('after :', grads[0], grads[1], grads[2])
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值