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中针对函数处理的特殊方法
Mar 06 Python
在Python的Django框架中编写编译函数
Jul 20 Python
Python实现string字符串连接的方法总结【8种方式】
Jul 06 Python
浅谈python3.x pool.map()方法的实质
Jan 16 Python
python简单验证码识别的实现方法
May 10 Python
Python实现钉钉订阅消息功能
Jan 14 Python
python实现可下载音乐的音乐播放器
Feb 25 Python
OpenCV Python实现拼图小游戏
Mar 23 Python
Python读入mnist二进制图像文件并显示实例
Apr 24 Python
解决python中import文件夹下面py文件报错问题
Jun 01 Python
使用TensorBoard进行超参数优化的实现
Jul 06 Python
python 实现简单的计算器(gui界面)
Nov 11 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
php之curl实现http与https请求的方法
2014/10/21 PHP
Session 失效的原因汇总及解决丢失办法
2015/09/30 PHP
详解在PHP的Yii框架中使用行为Behaviors的方法
2016/03/18 PHP
浅谈php中urlencode与rawurlencode的区别
2016/09/05 PHP
thinkphp5 migrate数据库迁移工具
2018/02/20 PHP
动态创建的表格单元格中的事件实现代码
2008/12/30 Javascript
Google Map API更新实现用户自定义标注坐标
2009/07/29 Javascript
JS解析json数据并将json字符串转化为数组的实现方法
2012/12/25 Javascript
javascript通过class来获取元素实现代码
2013/02/20 Javascript
jQuery中ajax的load()与post()方法实例详解
2016/01/05 Javascript
jQuery Timelinr实现垂直水平时间轴插件(附源码下载)
2016/02/16 Javascript
JS使用正则表达式实现关键字替换加粗功能示例
2016/08/03 Javascript
对js eval()函数的一些见解
2016/08/15 Javascript
JS实现访问DOM对象指定节点的方法示例
2018/04/04 Javascript
JS/HTML5游戏常用算法之碰撞检测 地图格子算法实例详解
2018/12/12 Javascript
[18:32]DOTA2 HEROS教学视频教你分分钟做大人-谜团
2014/06/12 DOTA
[04:03]2014DOTA2西雅图国际邀请赛 LGD战队巡礼
2014/07/07 DOTA
在Python的Django框架中用流响应生成CSV文件的教程
2015/05/02 Python
python实现类的静态变量用法实例
2015/05/08 Python
Python爬虫实现网页信息抓取功能示例【URL与正则模块】
2017/05/18 Python
解析Python的缩进规则的使用
2019/01/16 Python
Python函数中参数是传递值还是引用详解
2019/07/02 Python
python中使用while循环的实例
2019/08/05 Python
Python通过2种方法输出带颜色字体
2020/03/02 Python
python网络爬虫实现发送短信验证码的方法
2021/02/25 Python
英国乐购杂货:Tesco Groceries
2018/11/29 全球购物
Elemental Herbology官网:英国美容品牌
2019/04/27 全球购物
Footshop罗马尼亚:最好的运动鞋选择
2019/09/10 全球购物
企划经理的岗位职责
2013/11/17 职场文书
环境工程专业自荐信
2014/03/03 职场文书
成品库仓管员岗位职责
2014/04/06 职场文书
本科生求职信
2014/06/17 职场文书
2019大学生预备党员转正思想汇报
2019/06/21 职场文书
导游词之云南-元阳梯田
2019/10/08 职场文书
如何利用JavaScript实现二叉搜索树
2021/04/02 Javascript
详解Python描述符的工作原理
2021/06/11 Python