backward()使用举例
#定义变量
import torch
data_list = [1,2,3,4,5]
data_in = torch.Tensor(data_list)
data_1 = data_in * 2
data_2 = data_1 * 3
data_3 = data_2 * 4
#错误方式
data_3.backward()
报错:
#正确方式1
data_3.backward(torch.ones_like(data_3))
print(data_in.grad)
#方式2
data_3.sum().backward()
print(data_in.grad)
查看non_leaf节点的梯度
在如上的变量中,data_in为leaf节点变量,data_1、data_2、data_3为非non_leaf节点数据。以上方式只能查看leaf节点的梯度,想要查看non_leaf节点变量,需要提前保留。
import torch
data_list = [1,2,3,4,5]
data_in = torch.Tensor(data_list)
data_1 = data_in * 2
data_2 = data_1 * 3
data_3 = data_2 * 4
data_1.retain_grad()
data_2.retain_grad()
data_3.retain_grad()
data_3.backward(torch.ones_like(data_3))
print(data_1.grad)
print(data_2.grad)
print(data_3.grad)