pytorch文檔筆記3-神經網絡

import torchc++

import torch.nn as nn網絡

import torch.nn.functional as F #這個是函數形式定義,相對來講更低層一點。ide

 

"""函數

Net(oop

  (conv1): Conv2d(1, 6, kernel_size=(3, 3), stride=(1, 1))優化

  (conv2): Conv2d(6, 16, kernel_size=(3, 3), stride=(1, 1))ci

  (fc1): Linear(in_features=576, out_features=120, bias=True)get

  (fc2): Linear(in_features=120, out_features=84, bias=True)input

  (fc3): Linear(in_features=84, out_features=10, bias=True)it

)

"""

class Net(nn.Module):

 

    def __init__(self):

        super(Net, self).__init__()

        # 1 input image channel, 6 output channels, 3x3 square convolution

        # kernel

        self.conv1 = nn.Conv2d(1, 6, 3)#注意這裏1的大小是1*1*32*32

        self.conv2 = nn.Conv2d(6, 16, 3)

        # an affine operation: y = Wx + b

        self.fc1 = nn.Linear(16 * 6 * 6, 120)  # 6*6 from image dimension

        self.fc2 = nn.Linear(120, 84)

        self.fc3 = nn.Linear(84, 10)

 

#卷經層計算公式:(w-k+2p)/s+1 k表明卷積尺寸,p是填充,s是步幅;

#池化層計算公式:(w-k)/s+1

    def forward(self, x):

        # Max pooling over a (2, 2) window

        # conv1 layer calc:32-3+2*0/1+1 = 30

        # pool1 layer calc:30/2  = 15

      

        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))

        #print(y.size())

        # If the size is a square you can only specify a single number

        #conv2 layer calc:15-3+2*0/1+1=13

        #pool2 layer calc:13/2=6 這裏的問題是剩下的省略了?

        x = F.max_pool2d(F.relu(self.conv2(x)), 2)#x 16*6*6

       

        x = x.view(-1, self.num_flat_features(x))#展開

        x = F.relu(self.fc1(x))#三個全鏈接層

        x = F.relu(self.fc2(x))

        x = self.fc3(x)

        return x

 

#原有尺寸爲1*16*6*6;準確尺寸是16*6*6,第一個維度不要;

    def num_flat_features(self, x):

        size = x.size()[1:]  # all dimensions except the batch dimension 取每個維度尺寸

        num_features = 1

        for s in size:#將每個維度尺寸乘;最終便是總的尺寸。

            num_features *= s

        return num_features


 

net = Net()

print(net)

 

params = list(net.parameters())#存儲其全部參數,依然是張量,打印後格式爲:

"""

torch.Size([6, 1, 3, 3]) torch.Size([6]) torch.Size([16, 6, 3, 3]) torch.Size([16]) torch.Size([120, 576]) torch.Size([120]) 

torch.Size([84, 120]) torch.Size([84])

torch.Size([10, 84]) torch.Size([10]) 

"""

for i in range(len(params)):

    print(params[i].size(),end=' ')

 

input = torch.randn(1, 1, 32, 32)#隨機輸入

out = net(input)

print(out)

 

net.zero_grad( )#將全部梯度歸零

out.backward(torch.randn(1,10))#反向傳播,注意這裏的傳入方式是以前所說的雅各布矩陣

 

#偏差

output = net(input)

target = torch.randn(10)

target = target.view(1,-1)

loss = nn.MSELoss()(output,target)#相似c++函數傳入兩個參數,直觀上不大好看;

print(loss)#會進行相似輸出:tensor(0.4308, grad_fn=<MseLossBackward>)

 

#若是須要查看其調用屬性,可進行以下相似操做

print(loss.grad_fn)  # MSELoss

print(loss.grad_fn.next_functions[0][0])  # Linear

print(loss.grad_fn.next_functions[0][0].next_functions[0][0])  # ReLU

 

#也能夠採起以下方式查看

tmpPrint = loss.grad_fn

for i in range(2):

    print(tmpPrint.next_functions[0][0])

    tmpPrint = tmpPrint.next_functions[0][0]

 

#反向傳播

net.zero_grad()#主要目的是防止微分時出現異常;

print('conv1.bias.grad before backward',net.conv1.bias.grad)

loss.backward()

print('conv1.bias.grad after backward',net.conv1.bias.grad)

 

#更新權重

learning_rate=0.01

for f in net.parameters():

    f.data.sub_(f.grad.data*learning_rate)

 

#根據NN的特色,咱們可能會考慮使用不一樣的更新規則;因此整個流程簡化爲:

import torch.optim as optim

 

# create your optimizer

optimizer = optim.SGD(net.parameters(), lr=0.01)#優化器

 

# in your training loop:

optimizer.zero_grad()   # zero the gradient buffers

output = net(input)

loss = criterion(output, target)

loss.backward()

optimizer.step()    # Does the update

 

"""

因此整個流程變成:

1.定義網絡結構

2.輸入數據正向計算

3.計算損失

4.進行反向傳播

5.更新參數(方法可選)

"""

相關文章
相關標籤/搜索