1.tensor转变为Variable变量
首先需要解释一个库from torch.autograd import Variable
,提到这个库就必须要提到Variable,简而言之,Variable就是一个tensor的外衣,里面有三个属性.data
, .grad
和.grad_fn
(老版的是.creator
),其中data属性存储着tensor数据,grad属性存储关于该变量的导数(当然只有BP才会有),grad_fn是代表该变量的创造者。这个库呢就是给我提供了Variable。
import torch
from torch.autograd import Variable
tensor=torch.FloatTensor([[1,2],[3,4]])
variable=Variable(tensor,requires_grad=True)
print(tensor) # [torch.FloatTensor of size 2x2]
print(variable.data)#存放了tensor的数据
print(variable) # [torch.FloatTensor of size 2x2]
print(variable.grad_fn)
这个里的required_grad指的是参加BP,如果是False就是不参加BP
2.mean的操作
t_out=torch.mean(tensor*tensor)
v_out=torch.mean(variable*variable)
print(t_out)
print(v_out) # 7.5
3.进行BP,打印梯度
t_out=torch.mean(tensor*tensor)
v_out=torch.mean(variable*variable)
v_out.backward()#进行BP
print(variable.grad)
print(variable)
print(variable.data)
print(variable.data.numpy())#变成numpy形式
————————————————————————————————————————————————
我是一名机器学习的初学者,是万千小白中努力学习中的一员