pytorch 变量

import torch
from torch.autograd import Variable
tensor =torch.FloatTensor([[1,2],[3,4]])
Variable =Variable(tensor,requires_grad=True)
t_out=torch.mean(tensortensor) #(1+9+4+16)/4=7.5
v_out=torch.mean(Variable
Variable)
print(t_out)#tensor(7.5000)
print(v_out)#tensor(7.5000, grad_fn=)
v_out.backward()#反向传递
#v_out=1/4sum(varvar)
#d(v_out)/d(var)=1/2
variable
print(Variable.grad)#打印梯度

tensor([[0.5000, 1.0000],

[1.5000, 2.0000]])

print(Variable.data)# 从变量转换成tensor的形式

输出 tensor([[1., 2.],

[3., 4.]])

print(Variable.data.numpy())#tensor 转换成numpy array

输出 [[1. 2.]

输出 [3. 4.]]

你可能感兴趣的:(pytorch)