pytorch搭建神經網路是很簡單明瞭的,這裡介紹兩種自己常用的搭建模式:
import torchimport torch.nn as nn
first:
class nn(nn.module):這一種是將整個網路寫在乙個sequential中,網路引數設定可以在網路搭建好後單獨設定:self.model[0].weight.data.uniform_(-3e-3,3e-3),這是設定第乙個linear的權重是(-3e-3,3e-3)之間的均勻分布,bias是-1至1之間的均勻分布。def
__init__(self):
super(nn,
self).__init__()
self.model=nn.sequential(
nn.linear(30
,40),
nn.relu(),
nn.linear(40
,60),
nn.tanh(),
nn.linear(60
,10),
nn.softmax()
)self.model[0].weight.data.uniform_(-3e-3
, 3e-3)
self.model[0].bias.data.uniform(-1,1)
def
forward(self
,states):
return
self.model(states)
second:
class nn1(nn.module):網路引數的設定可以在定義完線性層之後直接設定如這裡對於第乙個線性層是這樣設定:self.linear1.weight.data.fill_(-0.1),self.linear1.bias.data.fill_(-0.1)。def
__init__(self):
super(nn1,
self).__init__()
self.linear1=nn.linear(30
,40)
self.linear1.weight.data.fill_(-0.1)
#self.linear1.weight.data.uniform_(-3e-3,3e-3)
self.linear1.bias.data.fill_(-0.1)
self.layer1=nn.sequential(self.linear1,nn.relu())
self.linear2=nn.linear(40
,60)
self.layer2=nn.sequential(self.linear2,nn.tanh())
self.linear3=nn.linear(60
,10)
self.layer3=nn.sequential(self.linear3,nn.softmax())
def
forward(self
,states):
return
self.model(states)
你可以看一下這樣定義完的引數的效果:
net=nn()print("0:"
,net.model[0])
print("weight:"
,type(net.model[0].weight))
print("weight:"
,type(net.model[0].weight.data))
print("bias"
,net.model[0].bias.data)
print('1:'
,net.model[1])
#print("weight:",net.model[1].weight.data)
print('2:'
,net.model[2])
print('3:'
,net.model[3])
#print(net.model[-1])
net1=nn1()
print(net1.linear1.weight.data)
輸出:
0: linear (30 -> 40)這裡要注意self.linear1.weight的型別是網路的parameter。而self.linear1.weight.data是floattensor。weight: weight: bias
-0.6287
-0.6573
-0.0452
0.9594
-0.7477
0.1363
-0.1594
-0.1586
0.0360
0.7375
0.2501
-0.1371
0.8359
-0.9684
-0.3886
0.7200
-0.3906
0.4911
0.8081
-0.5449
0.9872
0.2004
0.0969
-0.9712
0.0873
0.4562
-0.4857
-0.6013
0.1651
0.3315
-0.7033
-0.7440
0.6487
0.9802
-0.5977
0.3245
0.7563
0.5596
0.2303
-0.3836
[torch.floattensor of size 40]
1: relu ()
2: linear (40 -> 60)
3: tanh ()
-0.1000 -0.1000 -0.1000 ... -0.1000 -0.1000 -0.1000
-0.1000 -0.1000 -0.1000 ... -0.1000 -0.1000 -0.1000
-0.1000 -0.1000 -0.1000 ... -0.1000 -0.1000 -0.1000
... ⋱ ...
-0.1000 -0.1000 -0.1000 ... -0.1000 -0.1000 -0.1000
-0.1000 -0.1000 -0.1000 ... -0.1000 -0.1000 -0.1000
-0.1000 -0.1000 -0.1000 ... -0.1000 -0.1000 -0.1000
[torch.floattensor of size 40x30]
process finished with exit code 0
神經網路 全連線神經網路
全連線神經網路 也稱作多層感知機 mlp 1.1 神經元 神經元接收輸入向量x xx神經元節點有權重向量w和偏置項b 輸出值為f w tx b f w tx b f wtx b 在經過類似線性回歸之後 使用啟用函式對得到值進行操作 1.2 網路結構 個人對於每一層的理解就是 使用 這層維度,上層維度...
什麼是全連線神經網路
對n 1層和n層而言 n 1層的任意乙個節點,都和第n層所有節點有連線。即第n層的每個節點在進行計算的時候,啟用函式的輸入是n 1層所有節點的加權。全連線是一種不錯的模式,但是網路很大的時候,訓練速度回很慢。部分連線就是認為的切斷某兩個節點直接的連線,這樣訓練時計算量大大減小 最簡單的全連線神經網路...
mlp神經網路 MLP(全連線神經網路)的反向傳播
3 梯度消失與 mlp可以說是最簡單的一種ann結構了,輸入通過若干個隱藏層後,進入輸出層得到輸出。下圖展示了只有乙個單隱層的mlp。圖1 單隱層mlp 如果使用交叉熵損失函式 cross entropy error function 需要在輸出層的狀態值 如果使用mse損失函式 mean squa...