pytorch compute graph 计算图 例子

例1

从例1、2中可以发现 使用

y =torch.tensor(x * x, requires_grad=True)

跟使用

y =x*x

效果不一样

x = torch.tensor(0.3, requires_grad=True)
print(x)
y =torch.tensor(x * x, requires_grad=True)
print(y)
z = 2 * y
print(z)

z.backward()

print('x grad: ',x.grad)
print('y grad: ',y.grad)

输出1

tensor(0.3000, requires_grad=True)
tensor(0.0900, requires_grad=True)
tensor(0.1800, grad_fn=<MulBackward0>)
x grad:  None
y grad:  tensor(2.)

例2

x = torch.tensor(0.3, requires_grad=True)
print(x)
y =x * x
print(y)
z = 2 * y
print(z)

z.backward()

print('x grad: ',x.grad)
print('y grad: ',y.grad)

输出2

tensor(0.3000, requires_grad=True)
tensor(0.0900, grad_fn=<MulBackward0>)
tensor(0.1800, grad_fn=<MulBackward0>)
x grad:  tensor(1.2000)
y grad:  None

你可能感兴趣的:(PyTorch,pytorch,深度学习,python)