Pytorch 實(shí)現(xiàn)自定義參數(shù)層的例子
注意,一般官方接口都帶有可導(dǎo)功能,如果你實(shí)現(xiàn)的層不具有可導(dǎo)功能,就需要自己實(shí)現(xiàn)梯度的反向傳遞。
官方Linear層:
class Linear(Module):
def __init__(self, in_features, out_features, bias=True):
super(Linear, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.weight = Parameter(torch.Tensor(out_features, in_features))
if bias:
self.bias = Parameter(torch.Tensor(out_features))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
stdv = 1. / math.sqrt(self.weight.size(1))
self.weight.data.uniform_(-stdv, stdv)
if self.bias is not None:
self.bias.data.uniform_(-stdv, stdv)
def forward(self, input):
return F.linear(input, self.weight, self.bias)
def extra_repr(self):
return 'in_features={}, out_features={}, bias={}'.format(
self.in_features, self.out_features, self.bias is not None
)
實(shí)現(xiàn)view層
class Reshape(nn.Module):
def __init__(self, *args):
super(Reshape, self).__init__()
self.shape = args
def forward(self, x):
return x.view((x.size(0),)+self.shape)
實(shí)現(xiàn)LinearWise層
class LinearWise(nn.Module):
def __init__(self, in_features, bias=True):
super(LinearWise, self).__init__()
self.in_features = in_features
self.weight = nn.Parameter(torch.Tensor(self.in_features))
if bias:
self.bias = nn.Parameter(torch.Tensor(self.in_features))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
stdv = 1. / math.sqrt(self.weight.size(0))
self.weight.data.uniform_(-stdv, stdv)
if self.bias is not None:
self.bias.data.uniform_(-stdv, stdv)
def forward(self, input):
x = input * self.weight
if self.bias is not None:
x = x + self.bias
return x
以上這篇Pytorch 實(shí)現(xiàn)自定義參數(shù)層的例子就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
利用python將?Matplotlib?可視化插入到?Excel表格中
這篇文章主要介紹了利用python將?Matplotlib?可視化?插入到?Excel?表格中,通過(guò)使用xlwings模塊來(lái)控制Excel插入圖表,具體詳細(xì)需要的朋友可以參考下面文章內(nèi)容2022-06-06
如何利用pygame實(shí)現(xiàn)打飛機(jī)小游戲
pygame是python的一個(gè)做游戲的庫(kù),非常適合做游戲開(kāi)發(fā),這篇文章主要給大家介紹了關(guān)于如何利用pygame實(shí)現(xiàn)打飛機(jī)小游戲的相關(guān)資料,需要的朋友可以參考下2021-05-05
Python設(shè)計(jì)模式之建造者模式實(shí)例詳解
這篇文章主要介紹了Python設(shè)計(jì)模式之建造者模式,簡(jiǎn)單說(shuō)明了建造者模式的概念、原理,并結(jié)合實(shí)例形式分析了Python定義及使用建造者模式相關(guān)操作技巧,需要的朋友可以參考下2019-01-01
Qt調(diào)用Python詳細(xì)圖文過(guò)程記錄
Qt調(diào)用python實(shí)際上就是c++調(diào)python,網(wǎng)上搜會(huì)出來(lái)很多,介紹得也比較全,這里做個(gè)記錄,下面這篇文章主要給大家介紹了關(guān)于Qt調(diào)用Python詳細(xì)圖文過(guò)程,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-05-05
python淘寶準(zhǔn)點(diǎn)秒殺搶單的實(shí)現(xiàn)示例
為了想要搶到想要的商品,想了個(gè)用Python實(shí)現(xiàn)python淘寶準(zhǔn)點(diǎn)秒殺搶單方案,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05
Anaconda安裝opencv庫(kù)詳細(xì)圖文教程
這篇文章主要給大家介紹了關(guān)于Anaconda安裝opencv庫(kù)詳細(xì)圖文教程的相關(guān)資料,安裝Anaconda后,你可以使用conda命令在Anaconda環(huán)境中安裝OpenCV,文中有詳細(xì)步驟,需要的朋友可以參考下2023-07-07

