淘先锋技术网

首页 1 2 3 4 5 6 7

对于torch.Tensor,如果设置属性.requires_grad = True。
使用.backward()方法进行自动求取梯度,张量的梯度会保存到.grad属性中。
使用.backward()计算梯度。如果张量是一个标量(只有一个元素),不需要对.backward()指定参数;如果张量不止一个元素,需要设定参数,匹配张量的维度。
例:

a = torch.tensor([1.],requires_grad=True)
b = torch.tensor([2.],requires_grad=True)
c = torch.mul(a,b)
c.backward()
print(a.grad,b.grad)
# tensor([2.]) tensor([1.])

tensor类型需要为float。

a = torch.tensor([1,2,3],dtype=torch.float,requires_grad=True)
b = torch.tensor([2,2,3],dtype=torch.float,requires_grad=True)
c = torch.mul(a,b)
gradient = torch.ones_like(a)
c.backward(gradient)
print(a.grad,b.grad)     
 # tensor([2., 2., 3.]) tensor([1., 2., 3.])