我正在阅读 PyTorch 的文档,并找到了他们编写的示例

gradients = torch.FloatTensor([0.1, 1.0, 0.0001])
y.backward(gradients)
print(x.grad)

其中 x 是一个初始变量,从中构造 y (一个 3 向量)。问题是,梯度张量的 0.1、1.0 和 0.0001 参数是什么?文档对此不是很清楚。

最佳答案

gradients = torch.FloatTensor([0.1, 1.0, 0.0001])
y.backward(gradients)
print(x.grad)
上面代码的问题是没有基于计算梯度的函数。这意味着我们不知道有多少参数(函数采用的参数)和参数的维度。
为了完全理解这一点,我创建了一个接近原始示例的示例:
a = torch.tensor([1.0, 2.0, 3.0], requires_grad = True)
b = torch.tensor([3.0, 4.0, 5.0], requires_grad = True)
c = torch.tensor([6.0, 7.0, 8.0], requires_grad = True)

y=3*a + 2*b*b + torch.log(c)
gradients = torch.FloatTensor([0.1, 1.0, 0.0001])
y.backward(gradients,retain_graph=True)

print(a.grad) # tensor([3.0000e-01, 3.0000e+00, 3.0000e-04])
print(b.grad) # tensor([1.2000e+00, 1.6000e+01, 2.0000e-03])
print(c.grad) # tensor([1.6667e-02, 1.4286e-01, 1.2500e-05])
我假设我们的函数是 y=3*a + 2*b*b + torch.log(c) 并且参数是里面有三个元素的张量。
你可以把 gradients = torch.FloatTensor([0.1, 1.0, 0.0001]) 想象成这样就是累加器。
您可能听说过 PyTorch autograd 系统计算等效于雅可比积。
neural-network - Pytorch,梯度参数是什么-LMLPHP
如果你有一个函数,就像我们所做的那样:
y=3*a + 2*b*b + torch.log(c)
Jacobian 将是 [3, 4*b, 1/c] 。然而,这个 Jacobian 并不是 PyTorch 计算特定点梯度的方式。
PyTorch 使用前向传递和 backward mode automatic differentiation (AD) 串联。
不涉及符号数学,也没有数值微分。

如果您不在 y.backward() 中使用渐变:
a = torch.tensor(0.1, requires_grad = True)
b = torch.tensor(1.0, requires_grad = True)
c = torch.tensor(0.1, requires_grad = True)
y=3*a + 2*b*b + torch.log(c)

y.backward()

print(a.grad) # tensor(3.)
print(b.grad) # tensor(4.)
print(c.grad) # tensor(10.)
根据您最初如何设置 abc 张量,您将简单地在某一点获得结果。
请注意如何初始化 abc :
a = torch.empty(1, requires_grad = True, pin_memory=True)
b = torch.empty(1, requires_grad = True, pin_memory=True)
c = torch.empty(1, requires_grad = True, pin_memory=True)

y=3*a + 2*b*b + torch.log(c)

gradients = torch.FloatTensor([0.1, 1.0, 0.0001])
y.backward(gradients)

print(a.grad) # tensor([3.3003])
print(b.grad) # tensor([0.])
print(c.grad) # tensor([inf])
如果您使用 torch.empty() 而不使用 pin_memory=True,您每次可能会得到不同的结果。
另外,注意梯度就像累加器,所以在需要时将它们归零。
a = torch.tensor(1.0, requires_grad = True)
b = torch.tensor(1.0, requires_grad = True)
c = torch.tensor(1.0, requires_grad = True)
y=3*a + 2*b*b + torch.log(c)

y.backward(retain_graph=True)
y.backward()

print(a.grad) # tensor(6.)
print(b.grad) # tensor(8.)
print(c.grad) # tensor(2.)
关于 PyTorch 使用的术语的最后一些提示:
PyTorch 在计算正向传递中的梯度时创建了一个 动态计算图 。这看起来很像一棵树。
所以你经常会听到这棵树的叶子是 输入张量 根是 输出张量
通过跟踪从根到叶的图形并使用 链式法则 的方式乘以每个梯度来计算梯度。这种乘法发生在反向传播中。

关于neural-network - Pytorch,梯度参数是什么,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43451125/

10-12 22:52