莫烦pytorch学习02:Variable变量

import torch
from torch.autograd import Variable

tensor = torch.FloatTensor([[1, 2], [3, 4]])
variable = Variable(tensor, requires_grad=True)  #numpy张量变为Variable, requires_grad用来指定是否需要计算梯度

t_out = torch.mean(tensor*tensor)
v_out = torch.mean(variable*variable)

print(tensor,t_out)
print(variable,v_out)
print('//////////////////////')
v_out.backward() #反向传播
print(variable.grad) #梯度 v_out = 1/4*sum(var*var)  d(v_out)/d(var) = 1/4*2*variable = variable/2
print(variable.data)
print(variable.data.numpy())
print('//////////////////////')
x = Variable(torch.Tensor([3]), requires_grad=True)
y = x**2
print(y)
y.backward()
print(x.grad) #x为3时,y的导数值

你可能感兴趣的:(pytorch)