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

 更新时间:2020年01月06日 15:41:29   作者:bob_chen_csdn  
今天小编就为大家分享一篇pytorch动态网络以及权重共享实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

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动态网络以及权重共享实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • pytest利用request fixture实现个性化测试需求详解

    pytest利用request fixture实现个性化测试需求详解

    这篇文章主要为大家详细介绍了pytest如何利用request fixture实现个性化测试需求,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起了解一下
    2023-09-09
  • Python保存dict字典类型数据到Mysql并自动创建表与列

    Python保存dict字典类型数据到Mysql并自动创建表与列

    这篇文章主要介绍了Python保存dict字典类型数据到Mysql并自动创建表与列,字典是另一种可变容器模型,且可存储任意类型对象,想了解更多内容的小伙伴可以和小编一起进入下面文章学习更多内容,希望对你有所帮助
    2022-02-02
  • Pytorch Tensor 输出为txt和mat格式方式

    Pytorch Tensor 输出为txt和mat格式方式

    今天小编就为大家分享一篇Pytorch Tensor 输出为txt和mat格式方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-01-01
  • 使用grappelli为django admin后台添加模板

    使用grappelli为django admin后台添加模板

    本文介绍了一款非常流行的Django模板系统--grappelli,以及如何给Django的admin后台添加模板,非常的实用,这里推荐给大家。
    2014-11-11
  • Python制作进度条的几种方法

    Python制作进度条的几种方法

    如果你之前没用过进度条,八成是觉得它会增加不必要的复杂性或者很难维护,其实不然。要加一个进度条其实只需要几行代码,快跟随小编一起学习学习吧
    2022-12-12
  • pandas groupby + unstack的使用说明

    pandas groupby + unstack的使用说明

    这篇文章主要介绍了pandas groupby + unstack的使用说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-03-03
  • 基于Python实现二维图像双线性插值

    基于Python实现二维图像双线性插值

    双线性插值,又称为双线性内插。在数学上,双线性插值是有两个变量的插值函数的线性插值扩展,其核心思想是在两个方向分别进行一次线性插值。本文将用Python实现二维图像双线性插值,感兴趣的可以了解下
    2022-06-06
  • 详解Python如何实现输出颜色字体到终端界面

    详解Python如何实现输出颜色字体到终端界面

    在终端中,输出的字体总是单一颜色的,黑底白字。但是在一些场景并不能很好的满足输出的需求。本文为大家介绍了Python如何实现输出颜色字体到终端界面中,需要的可以参考一下
    2022-12-12
  • python解析多层json操作示例

    python解析多层json操作示例

    这篇文章主要介绍了python解析多层json操作,结合实例形式分析了Python针对多层json文件的读取、解析、修改、保存等相关操作技巧,需要的朋友可以参考下
    2019-12-12
  • Python制作简易计算器功能

    Python制作简易计算器功能

    这篇文章主要为大家详细介绍了Python制作简易计算器功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-04-04

最新评论