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函数返回多个值的示例方法
Dec 04 Python
python缩进区别分析
Feb 15 Python
python执行外部程序的常用方法小结
Mar 21 Python
python根据文章标题内容自动生成摘要的实例
Feb 21 Python
python画双y轴图像的示例代码
Jul 07 Python
Keras load_model 导入错误的解决方式
Jun 09 Python
python3环境搭建过程(利用Anaconda+pycharm)完整版
Aug 19 Python
golang/python实现归并排序实例代码
Aug 30 Python
Python中的None与 NULL(即空字符)的区别详解
Sep 24 Python
pytorch 一行代码查看网络参数总量的实现
May 12 Python
Python 中 Shutil 模块详情
Nov 11 Python
Python使用Web框架Flask开发项目
Jun 01 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实现图片以base64显示的方法
2016/10/13 PHP
jquery tools之tabs 选项卡/页签
2009/07/25 Javascript
node.js中的buffer.Buffer.isBuffer方法使用说明
2014/12/14 Javascript
JavaScript缓冲运动实现方法(2则示例)
2016/01/08 Javascript
Jquery实现select multiple左右添加和删除功能的简单实例
2016/05/26 Javascript
KnockoutJS 3.X API 第四章之表单submit、enable、disable绑定
2016/10/10 Javascript
jQuery.ajax实现根据不同的Content-Type做出不同的响应
2016/11/03 Javascript
微信小程序 视图容器组件的详解及实例代码
2017/01/19 Javascript
微信小程序之蓝牙的链接
2017/09/26 Javascript
JS中通过url动态获取图片大小的方法小结(两种方法)
2018/10/31 Javascript
浅谈Vue服务端渲染框架Nuxt的那些事
2018/12/21 Javascript
layer.msg()去掉默认时间,实现手动关闭的方法
2019/09/12 Javascript
vue如何使用rem适配
2021/02/06 Vue.js
python在多玩图片上下载妹子图的实现代码
2013/08/13 Python
Python pandas实现excel工作表合并功能详解
2019/08/29 Python
基于python及pytorch中乘法的使用详解
2019/12/27 Python
基于Tensorflow批量数据的输入实现方式
2020/02/05 Python
Python使用re模块验证危险字符
2020/05/21 Python
Python爬虫爬取新闻资讯案例详解
2020/07/14 Python
Python模块常用四种安装方式
2020/10/20 Python
python wsgiref源码解析
2021/02/06 Python
html5+css3实现一款注册表单实例
2013/04/17 HTML / CSS
GLAMGLOW香港官网:明星出镜前的秘密武器
2017/03/16 全球购物
美国最大的在线水培用品商店:GrowersHouse.com
2018/08/14 全球购物
蟋蟀的住宅教学反思
2014/04/26 职场文书
关于梦想的演讲稿
2014/05/05 职场文书
护士找工作求职信
2014/07/02 职场文书
学前班幼儿评语大全
2014/12/29 职场文书
首都博物馆观后感
2015/06/05 职场文书
《富饶的西沙群岛》教学反思
2016/02/16 职场文书
Windows下redis下载、redis安装及使用教程
2021/06/02 Redis
《艾尔登法环》Boss腐烂树灵很有可能是《黑暗之魂3》的一个废案
2022/04/11 其他游戏
vue 数字翻牌器动态加载数据
2022/04/20 Vue.js
pt-archiver 主键自增
2022/04/26 MySQL
Golang实现可重入锁的示例代码
2022/05/25 Golang
nginx设置资源请求目录的方式详解
2022/05/30 Servers