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

猜你喜欢

转载自blog.csdn.net/luolinll1212/article/details/85225226
今日推荐