pytorch 共享參數(shù)的示例
在很多神經(jīng)網(wǎng)絡(luò)中,往往會出現(xiàn)多個層共享一個權(quán)重的情況,pytorch可以快速地處理權(quán)重共享問題。
例子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
上邊這段程序定義了兩個卷積層,這兩個卷積層共享一個權(quán)重conv_weight,第一個卷積層的權(quán)重是conv_weight本身,第二個卷積層是conv_weight的轉(zhuǎn)置。注意在gpu上運行時,transpose()后邊必須加上.contiguous()使轉(zhuǎn)置操作連續(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)絡(luò)實現(xiàn)了一個雙層感知器,權(quán)重同樣是一個parameter的本身及其轉(zhuǎn)置。
例子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)絡(luò)效果相同。
以上這篇pytorch 共享參數(shù)的示例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python實現(xiàn)新型冠狀病毒傳播模型及預(yù)測代碼實例
在本篇文章里小編給大家整理的是關(guān)于Python實現(xiàn)新型冠狀病毒傳播模型及預(yù)測代碼內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。2020-02-02

