用pytorch的nn.Module構(gòu)造簡單全鏈接層實(shí)例
python版本3.7,用的是虛擬環(huán)境安裝的pytorch,這樣隨便折騰,不怕影響其他的python框架
1、先定義一個(gè)類Linear,繼承nn.Module
import torch as t
from torch import nn
from torch.autograd import Variable as V
class Linear(nn.Module):
'''因?yàn)閂ariable自動(dòng)求導(dǎo),所以不需要實(shí)現(xiàn)backward()'''
def __init__(self, in_features, out_features):
super().__init__()
self.w = nn.Parameter( t.randn( in_features, out_features ) ) #權(quán)重w 注意Parameter是一個(gè)特殊的Variable
self.b = nn.Parameter( t.randn( out_features ) ) #偏值b
def forward( self, x ): #參數(shù) x 是一個(gè)Variable對象
x = x.mm( self.w )
return x + self.b.expand_as( x ) #讓b的形狀符合 輸出的x的形狀
2、驗(yàn)證一下
layer = Linear( 4,3 ) input = V ( t.randn( 2 ,4 ) )#包裝一個(gè)Variable作為輸入 out = layer( input ) out
#成功運(yùn)行,結(jié)果如下:
tensor([[-2.1934, 2.5590, 4.0233], [ 1.1098, -3.8182, 0.1848]], grad_fn=<AddBackward0>)
下面利用Linear構(gòu)造一個(gè)多層網(wǎng)絡(luò)
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() )
輸出如預(yù)期:
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構(gòu)造簡單全鏈接層實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python Social Auth構(gòu)建靈活而強(qiáng)大的社交登錄系統(tǒng)實(shí)例探究
這篇文章主要為大家介紹了Python Social Auth構(gòu)建靈活而強(qiáng)大的社交登錄系統(tǒng)實(shí)例探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01
Python機(jī)器學(xué)習(xí)應(yīng)用之決策樹分類實(shí)例詳解
決策樹(Decision?Tree)是在已知各種情況發(fā)生概率的基礎(chǔ)上,通過構(gòu)成決策樹來求取凈現(xiàn)值的期望值大于等于零的概率,評價(jià)項(xiàng)目風(fēng)險(xiǎn),判斷其可行性的決策分析方法,是直觀運(yùn)用概率分析的一種圖解法2022-01-01
Python進(jìn)程multiprocessing.Process()的使用解讀
這篇文章主要介紹了Python進(jìn)程multiprocessing.Process()的使用,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02
python數(shù)據(jù)預(yù)處理方式 :數(shù)據(jù)降維
今天小編就為大家分享一篇python數(shù)據(jù)預(yù)處理方式 :數(shù)據(jù)降維,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
使用Python獲取當(dāng)前工作目錄和執(zhí)行命令的位置
這篇文章主要介紹了使用Python獲取當(dāng)前工作目錄和執(zhí)行命令的位置,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
如何對Python編譯PyInstaller打包生成的exe文件進(jìn)行反編譯生成pyc、py源代碼文件
很多開發(fā)者沒有發(fā)布源程序代碼,而是將代碼封裝為exe可執(zhí)行文件,這樣不僅更有利于程序傳播,下面這篇文章主要介紹了如何對Python編譯PyInstaller打包生成的exe文件進(jìn)行反編譯生成pyc、py源代碼文件的相關(guān)資料,需要的朋友可以參考下2023-01-01
Python 讀寫 Matlab Mat 格式數(shù)據(jù)的操作
這篇文章主要介紹了Python 讀寫 Matlab Mat 格式數(shù)據(jù)的操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-05-05

