pytorch 神經網絡

import torch
import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        # 1 input image channel, 6 output channels, 5x5 square convolution
        # kernel
        self.conv1 = nn.Conv2d(1, 6, 5)
        self.conv2 = nn.Conv2d(6, 16, 5)
        # an affine operation: y = Wx + b
        self.fc1 = nn.Linear(16*5*5,120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)
        
    def forward(self, x):
        # Max pooling over a (2, 2) window
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
        # If the size is a square you can only specify a single number
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)
        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
    
    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)
#剛定義了一個前饋函數,然後反向傳播函數被自動通過 autograd 定義了。你可以使用任何張量操作在前饋函數上。

#一個模型可訓練的參數可以通過調用 net.parameters() 返回
parame = list(net.parameters())
# print(parame)
print(len(parame))
print(parame[0].size()) # conv1's .weight

#讓我們嘗試隨機生成一個 32x32 的輸入。注意:期望的輸入維度是 32x32 。爲了使用這個網絡在 MNIST 數據及上,你需要把數據集中的圖片維度修改爲 32x32
input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)

#把所有參數梯度緩存器置零,用隨機的梯度來反向傳播
net.zero_grad()
out.backward(torch.randn(1, 10))

# 在繼續之前,讓我們複習一下所有見過的類。
# torch.Tensor - A multi-dimensional array with support for autograd operations like backward(). Also holds the gradient w.r.t. the tensor.
# nn.Module - Neural network module. Convenient way of encapsulating parameters, with helpers for moving them to GPU, exporting, loading, etc.
# nn.Parameter - A kind of Tensor, that is automatically registered as a parameter when assigned as an attribute to a Module.
# autograd.Function - Implements forward and backward definitions of an autograd operation. Every Tensor operation, creates at least a single Function node, that connects to functions that created a Tensor and encodes its history.

# 在此,我們完成了:
# 1.定義一個神經網絡
# 2.處理輸入以及調用反向傳播
# 還剩下:
# 1.計算損失值
# 2.更新網絡中的權重

# 損失函數
# 一個損失函數需要一對輸入:模型輸出和目標,然後計算一個值來評估輸出距離目標有多遠。
# 有一些不同的損失函數在 nn 包中。一個簡單的損失函數就是 nn.MSELoss ,這計算了均方誤差。
# 例如:
output = net(input)
target = torch.randn(10) # a dummy target, for example
target = target.view(1, -1) # make it the same shape as output
print('target:',target)
criterion = nn.MSELoss()
loss = criterion(output, target)
print(loss)

#現在,如果你跟隨損失到反向傳播路徑,可以使用它的 .grad_fn 屬性,你將會看到一個這樣的計算圖:
# input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d
#       -> view -> linear -> relu -> linear -> relu -> linear
#       -> MSELoss
#       -> loss

#所以,當我們調用 loss.backward(),整個圖都會微分,而且所有的在圖中的requires_grad=True 的張量將會讓他們的 grad 張量累計梯度。
#爲了演示,我們將跟隨以下步驟來反向傳播。
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
# 反向傳播
# 爲了實現反向傳播損失,我們所有需要做的事情僅僅是使用 loss.backward()。你需要清空現存的梯度,要不然帝都將會和現存的梯度累計到一起。
# 現在我們調用 loss.backward() ,然後看一下 con1 的偏置項在反向傳播之前和之後的變化。
net.zero_grad() # zeroes the gradient buffers of all parameters
print('conv1.bias.grad before backward')
print(net.conv1.bias.grad)
loss.backward()
print('conv1.bias.grad after backward')
print(net.conv1.bias.grad)

# 現在我們看到了,如何使用損失函數。
# 唯一剩下的事情就是更新神經網絡的參數。
# 更新神經網絡參數:
# 最簡單的更新規則就是隨機梯度下降。
# weight = weight - learning_rate*gradient
# 我們可以使用 python 來實現這個規則:
learning_rate = 0.01
for f in net.parameters():
    f.data.sub_(f.grad.data*learning_rate)
# 儘管如此,如果你是用神經網絡,你想使用不同的更新規則,類似於 SGD, Nesterov-SGD, Adam, RMSProp, 等。爲了讓這可行,我們建立了一個小包:torch.optim 實現了所有的方法。使用它非常的簡單。
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


結果:
Net(
  (conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1))
  (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
  (fc1): Linear(in_features=400, out_features=120, bias=True)
  (fc2): Linear(in_features=120, out_features=84, bias=True)
  (fc3): Linear(in_features=84, out_features=10, bias=True)
)
10
torch.Size([6, 1, 5, 5])
tensor([[-0.0220,  0.1704,  0.0581,  0.0586, -0.0196, -0.0184, -0.0314, -0.0540,
          0.0964, -0.1499]], grad_fn=<AddmmBackward>)
target: tensor([[ 1.6351,  1.2183, -0.3568,  0.7986, -0.0817,  0.0549, -1.2019,  0.8935,
          1.2872, -0.1660]])
tensor(0.8259, grad_fn=<MseLossBackward>)
<MseLossBackward object at 0x000001DB3E9D4F88>
<AddmmBackward object at 0x000001DB3E9D4EC8>
<AccumulateGrad object at 0x000001DB3E9D4EC8>
conv1.bias.grad before backward
tensor([0., 0., 0., 0., 0., 0.])
conv1.bias.grad after backward
tensor([-0.0042,  0.0108, -0.0019, -0.0070, -0.0095, -0.0084])

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章