Pytorch学习(二)

Variable变量学习

莫烦python视频学习笔记 视频链接https://www.bilibili.com/video/BV1Vx411j7kT?from=search&seid=3065687802317837578

variable与tensor的不同

import torch
from torch.autograd import Variable

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

# 计算中值
t_out = torch.mean(tensor*tensor)      # x^2
v_out = torch.mean(variable*variable)
print(t_out)
print(v_out)

# 误差的反向传递
# 计算公式
# v_out = 1/4*sum(var*var)
v_out.backward()
# 梯度计算
# d(v_out)/d(var) = 1/4*2*variable = variable/2
print(variable.grad)        # 传递后的结果
print(variable)
print(variable.data)

# variable数据转为numpy数据
print(variable.data.numpy())

输出:

tensor(7.5000)
tensor(7.5000, grad_fn=<MeanBackward0>)
tensor([[0.5000, 1.0000],
        [1.5000, 2.0000]])
tensor([[1., 2.],
        [3., 4.]], requires_grad=True)
tensor([[1., 2.],
        [3., 4.]])
[[1. 2.]
 [3. 4.]]

你可能感兴趣的:(python)