1. 程式人生 > >【pytorch】variable 和 tensor

【pytorch】variable 和 tensor

import torch
from torch.autograd import Variable

tensor = torch.FloatTensor([[1,2],[3,4]])
variable = Variable(tensor,requires_grad=True)

print(tensor)
print(variable)

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

v_out.backward()
print('反向傳播之後',variable) #反向傳播的時候variable 是受影響的,因為反向傳播了

print('變數的data是tensor型別--',variable.data)
print('variable轉為numpy--',variable.data.numpy())# 必須藉助於tensor轉換為numpy