一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

腳本之家,腳本語言編程技術及教程分享平臺!
分類導航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服務器之家 - 腳本之家 - Python - 用pytorch的nn.Module構造簡單全鏈接層實例

用pytorch的nn.Module構造簡單全鏈接層實例

2020-04-22 10:02AItitanic Python

今天小編就為大家分享一篇用pytorch的nn.Module構造簡單全鏈接層實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

python版本3.7,用的是虛擬環(huán)境安裝的pytorch,這樣隨便折騰,不怕影響其他的python框架

1、先定義一個類Linear,繼承nn.Module

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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、驗證一下

?
1
2
3
4
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)絡

?
1
2
3
4
5
6
7
8
9
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 )

測試一下

?
1
2
3
4
perceptron = Perceptron ( 5,3 ,1 )
 
for name,param in perceptron.named_parameters():
  print( name, param.size() )

輸出如預期:

?
1
2
3
4
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構造簡單全鏈接層實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。

原文鏈接:https://blog.csdn.net/AItitanic/article/details/97611356

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 人妖三级 | 国产精品麻豆 | 天堂avav | 奇米视频7777| 久久精品男人影院 | yy6080久久国产伦理 | 欧美伊人影院 | 四虎综合九九色九九综合色 | 黑人巨大vs北条麻妃在线 | 国产情侣露脸自拍 | 国产自在自线午夜精品之la | 果冻传媒mv在线观看入口免费 | 777奇米影视一区二区三区 | 精品久久久久香蕉网 | 日日操日日| 俄罗斯三级在线观看级 | 明星ai人脸替换造梦在线播放 | 古装全套 毛片 | 国产在线欧美精品 | 嗯啊好大好粗 | 色悠久久久久综合欧美99 | 黑人biglackon10十 | 国产高清日韩 | 精品91自产拍在线 | 无码国产成人午夜在线观看不卡 | 日本免费精品 | 国产一区二区免费不卡在线播放 | 国产性片在线观看 | 日本红怡院亚洲红怡院最新 | 欧美日韩国产一区二区三区伦 | 亚洲人成在线播放 | 青青青草国产 | 欧美国产视频 | 女同69式互添在线观看免费 | 亚洲第一男人网站 | 公园暴露娇妻小说 | 爽好大快深点一视频 | 欧美一区二区三区免费观看视频 | 欧美a级在线观看 | 99视频在线看观免费 | 幻女free性zoz0交 |