欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

pytorch 共享參數(shù)的示例

 更新時間:2019年08月17日 13:37:45   作者:馬管子  
今天小編就為大家分享一篇pytorch 共享參數(shù)的示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

在很多神經(jīng)網(wǎng)絡中,往往會出現(xiàn)多個層共享一個權重的情況,pytorch可以快速地處理權重共享問題。

例子1:

class ConvNet(nn.Module):
  def __init__(self):
    super(ConvNet, self).__init__()
    self.conv_weight = nn.Parameter(torch.randn(3, 3, 5, 5))
 
  def forward(self, x):
    x = nn.functional.conv2d(x, self.conv_weight, bias=None, stride=1, padding=2, dilation=1, groups=1)
    x = nn.functional.conv2d(x, self.conv_weight.transpose(2, 3).contiguous(), bias=None, stride=1, padding=0, dilation=1,
                 groups=1)
    return x

上邊這段程序定義了兩個卷積層,這兩個卷積層共享一個權重conv_weight,第一個卷積層的權重是conv_weight本身,第二個卷積層是conv_weight的轉置。注意在gpu上運行時,transpose()后邊必須加上.contiguous()使轉置操作連續(xù)化,否則會報錯。

例子2:

class LinearNet(nn.Module):
  def __init__(self):
    super(LinearNet, self).__init__()
    self.linear_weight = nn.Parameter(torch.randn(3, 3))
 
  def forward(self, x):
    x = nn.functional.linear(x, self.linear_weight)
    x = nn.functional.linear(x, self.linear_weight.t())
 
    return x

這個網(wǎng)絡實現(xiàn)了一個雙層感知器,權重同樣是一個parameter的本身及其轉置。

例子3:

class LinearNet2(nn.Module):
  def __init__(self):
    super(LinearNet2, self).__init__()
    self.w = nn.Parameter(torch.FloatTensor([[1.1,0,0], [0,1,0], [0,0,1]]))
 
  def forward(self, x):
    x = x.mm(self.w)
    x = x.mm(self.w.t())
    return x

這個方法直接用mm函數(shù)將x與w相乘,與上邊的網(wǎng)絡效果相同。

以上這篇pytorch 共享參數(shù)的示例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

最新評論