pytorch,梯度参数
Autograd:自动求导
首先我们学习到了pytorch中的对Tensor所有操作的自动求导机制。
一个简单的例子
from torch.autograd import Variable
x = Variable(torch.ones(2, 2), requires_grad = True)
y = x + 2
z = y * y * 3
out = z.mean()
# 现在我们来使用反向传播
out.backward()
# out.backward()和操作out.backward(torch.Tensor([1.0]))是等价的
# 在此处输出 d(out)/dx
x.grad
又一个例子:
x = torch.randn(3)
x = Variable(x, requires_grad = True)
y = x * 2
while y.data.norm() < 1000:
y = y * 2
gradients = torch.FloatTensor([0.1, 1.0, 0.0001])
y.backward(gradients)
x.grad
但是在这个例子中我不懂y.backward(gradients)中的梯度参数是什么。通过继续学习操作,看下一个例子
from torch.autograd import Variable
import torch
x = Variable(torch.FloatTensor([[1, 2, 3, 4]]), requires_grad=True)
z = 2*x
loss = z.sum(dim=1)
# do backward for first element of z
z.backward(torch.FloatTensor([[1, 0, 0, 0]]), retain_graph=True)
print(x.grad.data)
通过改变梯度参数不断观察,暂时我粗浅的理解是:里面的参数相当于作用于各个部分求导后的权值,这么做可以用来为不同的损失增加权重或重要性。
参考链接:https://qastack.cn/programming/43451125/pytorch-what-are-the-gradient-arguments
(用markdown编辑出来的风格确实好看了许多,之前一直待在舒适区,以后要多写博客,多熟悉markdown的使用。还有,终于搭建了自己的博客了,慢慢扩充起来)