1. 程式人生 > >pytorch 梯度計算

pytorch 梯度計算

梯度計算

import torch
from torch.autograd import Variable

x = Variable(torch.ones(2), requires_grad=True)
# y = (4 * x * x).norm()
y = (4 * x * x + 10 * x).mean()
y.backward()
print('x的值:',x)
print('x的梯度',x.grad)
print('y的值:',y)
print('y的梯度',y.grad)

# a = torch.ones(1,2)
# a = torch.Tensor((3,4))
# print(a)
# print(torch.norm(a,p=2))
# print(torch.norm(a))

輸出

x的值: tensor([1., 1.], requires_grad=True)
x的梯度 tensor([9., 9.])
y的值: tensor(14., grad_fn=<MeanBackward1>)
y的梯度 None