用pytorch的nn.Module構造簡單全鏈接層實例
python版本3.7,用的是虛擬環(huán)境安裝的pytorch,這樣隨便折騰,不怕影響其他的python框架
1、先定義一個類Linear,繼承nn.Module
import torch as t from torch import nn from torch.autograd import Variable as V class Linear(nn.Module): '''因為Variable自動求導,所以不需要實現(xiàn)backward()''' def __init__(self, in_features, out_features): super().__init__() self.w = nn.Parameter( t.randn( in_features, out_features ) ) #權重w 注意Parameter是一個特殊的Variable self.b = nn.Parameter( t.randn( out_features ) ) #偏值b def forward( self, x ): #參數(shù) x 是一個Variable對象 x = x.mm( self.w ) return x + self.b.expand_as( x ) #讓b的形狀符合 輸出的x的形狀
2、驗證一下
layer = Linear( 4,3 ) input = V ( t.randn( 2 ,4 ) )#包裝一個Variable作為輸入 out = layer( input ) out
#成功運行,結果如下:
tensor([[-2.1934, 2.5590, 4.0233], [ 1.1098, -3.8182, 0.1848]], grad_fn=<AddBackward0>)
下面利用Linear構造一個多層網(wǎng)絡
class Perceptron( nn.Module ): def __init__( self,in_features, hidden_features, out_features ): super().__init__() self.layer1 = Linear( in_features , hidden_features ) self.layer2 = Linear( hidden_features, out_features ) def forward ( self ,x ): x = self.layer1( x ) x = t.sigmoid( x ) #用sigmoid()激活函數(shù) return self.layer2( x )
測試一下
perceptron = Perceptron ( 5,3 ,1 ) for name,param in perceptron.named_parameters(): print( name, param.size() )
輸出如預期:
layer1.w torch.Size([5, 3]) layer1.b torch.Size([3]) layer2.w torch.Size([3, 1]) layer2.b torch.Size([1])
以上這篇用pytorch的nn.Module構造簡單全鏈接層實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
python 字符串轉列表 list 出現(xiàn)\ufeff的解決方法
下面小編就為大家?guī)硪黄猵ython 字符串轉列表 list 出現(xiàn)\ufeff的解決方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06selenium + python 獲取table數(shù)據(jù)的示例講解
今天小編就為大家分享一篇selenium + python 獲取table數(shù)據(jù)的示例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10Python3實現(xiàn)將文件歸檔到zip文件及從zip文件中讀取數(shù)據(jù)的方法
這篇文章主要介紹了Python3實現(xiàn)將文件歸檔到zip文件及從zip文件中讀取數(shù)據(jù)的方法,涉及Python針對zip文件操作的相關技巧,需要的朋友可以參考下2015-05-05Python高級特性——詳解多維數(shù)組切片(Slice)
今天小編就為大家分享一篇Python高級特性——詳解多維數(shù)組切片(Slice),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11python+matplotlib實現(xiàn)禮盒柱狀圖實例代碼
這篇文章主要介紹了python+matplotlib實現(xiàn)禮盒柱狀圖實例代碼,具有一定借鑒價值,需要的朋友可以參考下2018-01-01