Pytorch之认识Variable

参考  Pytorch之认识Variable - 云+社区 - 腾讯云

Tensor是Pytorch的一个完美组件,但是要构建神经网络还是远远不够的,我们需要能够计算图的Tensor,那就是Variable。Variable是对Tensor的一个封装,操作和Tensor是一样的,但是每个Variable都有三个属性,Varibale的Tensor本身的.data,对应Tensor的梯度.grad,以及这个Variable是通过什么方式得到的.grad_fn。

# 通过一下方式导入Variable
from torch.autograd import Variable
import torch
x_tensor = torch.randn(10,5)
y_tensor = torch.randn(10,5)

#将tensor转换成Variable
x = Variable(x_tensor,requires_grad=True) #Varibale 默认时不要求梯度的,如果要求梯度,需要说明
y = Variable(y_tensor,requires_grad=True)
z = torch.sum(x + y)
print(z.data)
print(z.grad_fn)

z.backward()
print(x.grad)
print(y.grad)

tensor(7.0406)
<SumBackward0 object at 0x000002A557C47908>

tensor([[1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.]])
tensor([[1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.]])

上面打印出了z的Tensor数值,以及通过.grad_fn得到其是通过sum这种方式得到的,通过.grad得到了x和y的梯度

#构建一个y = x^2 函数 求x = 2 的导数
import numpy as np
import torch
from torch.autograd import Variable
# 1、画出函数图像
import matplotlib.pyplot as plt
x = np.arange(-3,3.01,0.1)
y = x**2
plt.plot(x,y)
plt.plot(2,4,'ro')
plt.show()

#定义点variable类型的x = 2

x = Variable(torch.FloatTensor([2]),requires_grad=True)
y = x ** 2
y.backward()
print(x.grad)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wanderer001

ROIAlign原理

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值