1. 介绍Tensor
在PyTorch中主要是通过torch.Tensor
存储和计算数据,Tensor可以表示数值,向量或矩阵。假设x=torch.tensor(3.0)
,当x
的requires_grads
参数为True
时,它跟踪x
参与的运算。并且在计算得到的结果上(结果也是Tensor一个对象)上调用backward()就会自动计算x的梯度,并将梯度累加到x.grad
属性上。下面代码演示在
y
=
x
2
y=x^2
y=x2,求
x
=
3
x=3
x=3时的梯度。
import torch
x = torch.tensor(3., requires_grad=True)
y = x**2
y.backward()
print(x.grad)
tensor(6.)
2. detach()的作用
为了防止x的的计算被跟踪,可以使用detach()
方法获取x的值(x.detach()
和x
共享内存)。例如在
y
=
x
2
+
x
3
y=x^2+x^3
y=x2+x3式子求梯度时,我想忽略
y
=
x
2
y=x^2
y=x2这一项就需要用到x.detach()
了。
import torch
x = torch.tensor(3., requires_grad=True)
y = x.detach()**2 + x**3
y.backward()
print(x.grad)
tensor(27.)
3. torch.no_grad()的作用
torch.no_grad()
的作用和detach()
类似,也是为了防止追踪历史,只是使用方法不同。例如下面式子中不会跟踪
y
=
x
2
y=x^2
y=x2这个运算,所以我们需要把
x
2
x^2
x2看成一个常数,那么计算梯度时就要把
y
=
x
+
x
2
y=x+x^2
y=x+x2看成
y
=
x
+
6
y=x+6
y=x+6,那么x=3时的梯度就是1。
import torch
x = torch.tensor(3., requires_grad=True)
with torch.no_grad():
y = x*2
y = x + y
y.backward()
print(x.grad)
tensor(1.)