#和numpy之间转换
np_b = b.numpy()print('convert to numpy is \n {}'.format(np_b))
e = np.array([[2,3],[4,5]])
torch_e = torch.from_numpy(e)print('from numpy to torch.Tensor is {}'.format(torch_e))
convert to numpy is
[[2 3]
[4 8]
[7 9]]
from numpy to torch.Tensor is tensor([[2, 3],
[4, 5]])
二、Variable (变量)
#variable变量#标量求导
x = Variable(torch.Tensor([1]),requires_grad=True)
w = Variable(torch.Tensor([2]),requires_grad=True)
b = Variable(torch.Tensor([3]),requires_grad=True)
y = w*x+b
#这一步即自动求导
y.backward()print(x.grad)print(w.grad)print(b.grad)
tensor([2.])
tensor([1.])
tensor([1.])
#矩阵求导
x = torch.randn(3)
x = Variable(x,requires_grad =True)
y = x*2print(y)
y.backward(torch.FloatTensor([1,0.1,0.01]))print(x.grad)