pytorch动态网络以及权重共享实例


Posted in Python onJanuary 06, 2020

pytorch 动态网络+权值共享

pytorch以动态图著称,下面以一个栗子来实现动态网络和权值共享技术:

# -*- coding: utf-8 -*-
import random
import torch


class DynamicNet(torch.nn.Module):
  def __init__(self, D_in, H, D_out):
    """
    这里构造了几个向前传播过程中用到的线性函数
    """
    super(DynamicNet, self).__init__()
    self.input_linear = torch.nn.Linear(D_in, H)
    self.middle_linear = torch.nn.Linear(H, H)
    self.output_linear = torch.nn.Linear(H, D_out)

  def forward(self, x):
    """
    For the forward pass of the model, we randomly choose either 0, 1, 2, or 3
    and reuse the middle_linear Module that many times to compute hidden layer
    representations.

    Since each forward pass builds a dynamic computation graph, we can use normal
    Python control-flow operators like loops or conditional statements when
    defining the forward pass of the model.

    Here we also see that it is perfectly safe to reuse the same Module many
    times when defining a computational graph. This is a big improvement from Lua
    Torch, where each Module could be used only once.
    这里中间层每次向前过程中都是随机添加0-3层,而且中间层都是使用的同一个线性层,这样计算时,权值也是用的同一个。
    """
    h_relu = self.input_linear(x).clamp(min=0)
    for _ in range(random.randint(0, 3)):
      h_relu = self.middle_linear(h_relu).clamp(min=0)
    y_pred = self.output_linear(h_relu)
    return y_pred


    # N is batch size; D_in is input dimension;
    # H is hidden dimension; D_out is output dimension.
    N, D_in, H, D_out = 64, 1000, 100, 10

    # Create random Tensors to hold inputs and outputs
    x = torch.randn(N, D_in)
    y = torch.randn(N, D_out)

    # Construct our model by instantiating the class defined above
    model = DynamicNet(D_in, H, D_out)

    # Construct our loss function and an Optimizer. Training this strange model with
    # vanilla stochastic gradient descent is tough, so we use momentum
    criterion = torch.nn.MSELoss(reduction='sum')
    optimizer = torch.optim.SGD(model.parameters(), lr=1e-4, momentum=0.9)
    for t in range(500):
      # Forward pass: Compute predicted y by passing x to the model
      y_pred = model(x)

      # Compute and print loss
      loss = criterion(y_pred, y)
      print(t, loss.item())

      # Zero gradients, perform a backward pass, and update the weights.
      optimizer.zero_grad()
      loss.backward()
      optimizer.step()

这个程序实际上是一种RNN结构,在执行过程中动态的构建计算图

References: Pytorch Documentations.

以上这篇pytorch动态网络以及权重共享实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
由浅入深讲解python中的yield与generator
Apr 05 Python
浅谈python中的数字类型与处理工具
Aug 02 Python
基于Python闭包及其作用域详解
Aug 28 Python
解决Pycharm无法import自己安装的第三方module问题
May 18 Python
Python实现爬虫爬取NBA数据功能示例
May 28 Python
利用Python实现在同一网络中的本地文件共享方法
Jun 04 Python
python 将print输出的内容保存到txt文件中
Jul 17 Python
python django中8000端口被占用的解决
Dec 17 Python
Django REST Swagger实现指定api参数
Jul 07 Python
python中24小时制转换为12小时制的方法
Jun 18 Python
Python语言中的数据类型-序列
Feb 24 Python
详解OpenCV曝光融合
Apr 29 Python
selenium中get_cookies()和add_cookie()的用法详解
Jan 06 #Python
pytorch中的自定义反向传播,求导实例
Jan 06 #Python
PyTorch中 tensor.detach() 和 tensor.data 的区别详解
Jan 06 #Python
6行Python代码实现进度条效果(Progress、tqdm、alive-progress​​​​​​​和PySimpleGUI库)
Jan 06 #Python
基于python+selenium的二次封装的实现
Jan 06 #Python
Python使用Tkinter实现滚动抽奖器效果
Jan 06 #Python
Python使用Tkinter实现转盘抽奖器的步骤详解
Jan 06 #Python
You might like
Thinkphp整合微信支付功能
2016/12/14 PHP
PHP实现mysqli批量执行多条语句的方法示例
2017/07/22 PHP
在Yii2特定页面如何禁用调试工具栏Debug Toolbar详解
2017/08/07 PHP
PHP封装请求类实例分析【基于Yii框架】
2019/10/17 PHP
jQuery Ajax之load()方法
2009/10/12 Javascript
自己做的模拟模态对话框实现代码
2012/05/23 Javascript
jQuery.event兼容各浏览器的event详细解析
2013/12/18 Javascript
Canvas 绘制粒子动画背景
2017/02/15 Javascript
关于vue v-for 循环问题(一行显示四个,每一行的最右边那个计算属性)
2018/09/04 Javascript
vscode配置vue下的es6规范自动格式化详解
2019/03/20 Javascript
[42:24]完美世界DOTA2联赛循环赛 LBZS vs DM BO2第一场 11.01
2020/11/02 DOTA
Python中请使用isinstance()判断变量类型
2014/08/25 Python
python基础知识小结之集合
2015/11/25 Python
python模块简介之有序字典(OrderedDict)
2016/12/01 Python
使用pandas将numpy中的数组数据保存到csv文件的方法
2018/06/14 Python
Python闭包函数定义与用法分析
2018/07/20 Python
对python插入数据库和生成插入sql的示例讲解
2018/11/14 Python
Python SSL证书验证问题解决方案
2020/01/13 Python
python实现图像全景拼接
2020/03/27 Python
python3代码中实现加法重载的实例
2020/12/03 Python
使用CSS3的rem属性制作响应式页面布局的要点解析
2016/05/24 HTML / CSS
CSS3不透明度实例讲解
2016/04/26 HTML / CSS
使用jquery实现HTML5响应式导航菜单教程
2014/04/02 HTML / CSS
英国领先的在线药房:Pharmacy First
2017/09/10 全球购物
美国男士和女士奢侈品折扣手表购物网站:Certified Watch Store
2018/06/13 全球购物
采购文员岗位职责
2013/11/20 职场文书
思想品德课教学反思
2014/02/10 职场文书
设立有限责任公司出资协议书
2014/11/01 职场文书
演讲开场白台词大全
2015/05/29 职场文书
大国崛起观后感
2015/06/02 职场文书
医院病假条怎么写
2015/08/17 职场文书
党员心得体会范文2016
2016/01/23 职场文书
大学生,三分钟即兴演讲稿
2019/07/22 职场文书
PyTorch梯度裁剪避免训练loss nan的操作
2021/05/24 Python
css3中transform属性实现的4种功能
2021/08/07 HTML / CSS
我去timi了,一起去timi是什么意思?
2022/04/13 杂记