pytorch学习系列之搭建模型

pytorch学习系列之搭建模型


这里主要是想着左手tensorflow,右手pytorch,玩转算法一二三。主要参考资料是 pytorch中文手册1 2

自动求导

自动求导是pytorch最核心的概念,所谓自动求导和高等数学中的导数的概念。
举个例子,
f ( a , x , b ) = a 2 x + b f(a, x, b) = a^2x+b f(a,x,b)=a2x+b
分别对 a , x , b a,x,b a,x,b求偏导,则有:
∂ f ∂ a = 2 a x ; \frac{\partial {f}}{\partial {a}} = 2ax; af=2ax;
∂ f ∂ x = a 2 \frac{\partial {f}}{\partial {x}} = a^2 xf=a2
∂ f ∂ b = 1 \frac{\partial {f}}{\partial {b}} = 1 bf=1
pytorch实现如下:

    a = torch.tensor(1., requires_grad=True) # 需要求导的话,requires_grad=True,默认False
    b = torch.tensor(1., requires_grad=True)
    x = torch.tensor(1., requires_grad=True)
    f = a*a*x + b
    print("before grad: a.grad is {}, b.grad is {}, x.grad is {}".format(a.grad, b.grad, x.grad))
    grads = autograd.grad(f, [a, b, x])
    print("before grad: a.grad is {}, b.grad is {}, x.grad is {}".format(grads[0], grads[1], grads[2]))

注意⚠️:
上述代码中的1.不能为1,否则会报错:

RuntimeError: Only Tensors of floating point and complex dtype can require gradients

模型架构

在这里插入图片描述
这是一个数字识别的图像,图像经过卷积层,然后进行


  1. http://pytorch.panchuang.net/SecondSection/neural_networks/ ↩︎

  2. https://www.bilibili.com/video/BV14k4y1C7SF/?spm_id_from=333.788.videocard.3 ↩︎

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值