Pytorch學習(6)-神經網絡工具箱nn

nn模塊是構建於autograd之上的神經網絡模塊。(autograd實現了自動微分系統)

1.1、nn.Module

         由於使用autograd可實現深度學習模型,但是其抽象程度較低,用來實現深度學習模型,則需要編寫的代碼量極大。

因此torch.nn產生了,其是專門爲深度學習設計的模塊。torch.nn的核心數據結構是Module,它是一個抽象的概念,既可以表示神經網絡中的某個層(layer),也可以表示一個包含很多層的神經網絡。

          在實際使用中,通常是繼承nn.Module,攥寫自己的網絡/層。

下面先來看看如何用nn.Module實現自己的全連接層。全連接層,又名仿射層,輸出y和輸入x滿足y = Wx + b,W和b是可學習的參數。

全連接層的實現需要注意:

  • 自定義層Linear必須繼承nn.Module,並且在其構造函數中需調用nn.Module的構造函數,即super(Linear, self).__init__()或nn.Module.__init__(self)。
  • 在構造函數__init__中必須自己定義可學習的參數,並封裝成Parameter,如在下面例子裏把w和b封裝成Parameter。Parameter是一種特殊的Variable,但其默認需要求導(requires_grad=True)。
  • forward函數實現前向傳播過程,其輸入可以是一個或多個variable,對x的任何操作也必須是variable支持的操作
  • 無需寫反向傳播函數,因其前向傳播都是對variable進行操作,nn.Module能夠利用autograd自動實現反向傳播,這一點比Function簡單許多。
  • 使用時,直觀上可將layer看成數學概念中的函數,調用layer(input)即可得到input對應的結果。它等價於layers.__call__(input),在__call__函數中,主要調用的是layer.forward(x)。所以在實際使用中應儘量使用layer(x)而不是使用layer.forward(x)。
  • Module中的可學習參數可以通過named_parameters()或者parameter()返回迭代器,前者會給每個parameter附上名字,使其更具有辨識度。
class Linear(nn.Module):  # 繼承nn.Module
    def __init__(self, in_features, out_features):
        super(Linear, self).__init__()  # 等價於nn.Module.__init__(self)
        self.w = nn.Parameter(t.randn(in_features, out_features))
        self.b = nn.Parameter(t.randn(out_features))

    def forward(self, x):
        x = x.mm(self.w)
        return x + self.b.expand_as(x)


layer = Linear(4, 3)
input = V(t.randn(2, 4))
output = layer(input)
print(output)

for name, parameter in layer.named_parameters():
    print(name, parameter)  # w和b
# -----------------------------------------------
tensor([[ 1.1202,  2.3926, -2.0179],
        [ 0.5567,  1.1519,  0.2462]], grad_fn=<AddBackward0>)
w Parameter containing:
tensor([[-0.9790, -0.3613, -0.2963],
        [ 0.7113,  0.0377,  0.4925],
        [-1.0212, -0.6085,  0.3077],
        [ 0.9080, -0.0354,  1.3085]], requires_grad=True)
b Parameter containing:
tensor([ 0.2244,  1.0853, -0.0439], requires_grad=True)
# -------------------------------------------------------------

 

多層感知機的網絡結果如下圖所示,它由兩個全連接層組成,採用sigmoid函數作爲激活函數(圖中沒有畫出)。

                                                  

        實現起來也很簡單,如下代碼,但需要注意兩點:

  • 構造函數__init__中,可利用前面自定義的Linear層(module)作爲當前module對象的一個子module,它的可學習參數,也會成爲當前module的可學習參數。
  • 在前向傳播函數中,將輸入變量都命名成x,是爲了能讓Pytorch回收一些中間層的輸出,從而節省內存。但並不是所有的中間結果都會被回收,有些variable雖然名字被覆蓋,但其在反向傳播時仍需要用到,此時Pytorch的內存回收模塊將通過檢查引用計數,不會回收則不復內存。

module中parameter的全局命名規範如下:

  • Parameter直接命名。例如self.param_name=nn.Parameter(t.randn(3, 4)),命名爲param_name。
  • 子module中的parameter,會在其名字之前加上當前module的名字。例如self.sub_module=SubModel(),SubModel中有個parameter名字也叫做param_name,那麼二者拼接而成的parameter name就是sub_module.param_name。
class Linear(nn.Module):  # 繼承nn.Module
    def __init__(self, in_features, out_features):
        super(Linear, self).__init__()  # 等價於nn.Module.__init__(self)
        self.w = nn.Parameter(t.randn(in_features, out_features))
        self.b = nn.Parameter(t.randn(out_features))

    def forward(self, x):
        x = x.mm(self.w)
        return x + self.b.expand_as(x)


class Perceptron(nn.Module):
    def __init__(self, in_features, hidden_features, out_features):
        nn.Module.__init__(self)
        # 此處的Linear是前面自定義的全連接層
        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)
        return self.layer2(x)


perceptron = Perceptron(3, 4, 1)
for name, param in perceptron.named_parameters():
    print(name, param.size())
# -------------------------------------------------------
layer1.w torch.Size([3, 4])
layer1.b torch.Size([4])
layer2.w torch.Size([4, 1])
layer2.b torch.Size([1])
# ------------------------------------------------------

        爲了方便用戶使用,PyTorch實現了神經網絡中絕大多數的layer,這些layer都繼承於nn.Module,封裝了可學習參數parameter,並實現了forward函數,且專門針對GPU運算進行了CuDNN優化,其速度和性能都十分優異。

  • 構造函數的參數,如nn.Linear(in_features, out_features, bias),需要關注這三個參數的作用
  • 屬性、可學習參數和子module。如nn.Linear中有weight和bias兩個可學習參數,不包含子module。
  • 輸入輸出的形狀,如nn,Linear的輸入形狀是(N, input_features),輸出爲(N, output_features),N是batch_size

這些定義layer對輸入形狀都有假設:輸入的不是單個數據,而是一個batch。若想輸入一個數據,必須調用unsqueeze(0)函數將數據僞裝成batch_size=1的batch。

 

1.2、常用的神經網絡層

   1.2.1、圖像相關層

      圖像相關層主要包括卷積層(Conv)、池化層(Pool)等。

     這些層在實際使用中可分爲一維(1D)、二維(2D)和三維(3D)。

     池化方式又分爲平均池化(AvgPool)、最大值池化(MaxPool)、自適應池化(AdaptiveAvgPool)等

      卷積層有前向卷積、逆卷積(TransposeConv)。

舉例說明,如下:

from PIL import Image
from torchvision.transforms import ToTensor, ToPILImage


to_tensor = ToTensor()  # img -> tensor
to_pil = ToPILImage()
lena = Image.open('D:/Pycharm/Project/BYSJ/test_net/bigimg1.jpg')
lena.show()  # 使用電腦自帶圖片管理器打開圖片
print(lena.mode) # 查看圖片的
print(lena.format)  # 查看圖片的格式

# 輸入是一個batch,batch_size=1,input是一個一通道的圖
input = to_tensor(lena).unsqueeze(0)

# 銳化卷積核
kernel = t.ones(3, 3)/-9.
kernel[1][1] = 1
conv = nn.Conv2d(1, 1, (3, 3), 1, bias=False)
conv.weight.data = kernel.view(1, 1, 3, 3)

out = conv(V(input))
to_pil(out.data.squeeze(0)).show()

# 池化層可以看作是一種特殊的卷積層,用來下采樣,但池化層沒有可學習參數,其weight是固定的
pool = nn.AvgPool2d(2, 2)
print(list(pool.parameters()))
out = pool(V(input))
to_pil(out.data.squeeze(0)).show()
除了卷積層和池化層,深度學習中還將常用到以下幾個層:
  • Linear:全連接層
  • BatchNorm:批規範層,分爲1D、2D和3D。除了標準的BatchNorm之外,還有在風格遷移中常用到的InstanceNorm層
  • Dropout:dropout層,用來防止過擬合,同樣分爲1D、2D和3D。

下面詳細介紹它們的使用方法。

# 輸入batch_size=2,維度3
input = V(t.randn(2, 3))
linear = nn.Linear(3, 4)
h = linear(input)
print(h)

# 4 channel,初始化標準差爲4,均值爲0
bn = nn.BatchNorm1d(4)
bn.weight.data = t.ones(4) * 4
bn.bias.data = t.zeros(4)

bn_out = bn(h)

# 注意輸出的均值和方差
# 方差是標準差的平方,計算無偏差分母會減1
# 使用unbiased=False,分母不減1
print(bn_out.mean(0), bn_out.var(0, unbiased=False))

# 每個元素以0.5的概率捨棄
dropout = nn.Dropout(0.5)
o = dropout(bn_out)
print(o)  # 有一半左右的數變爲0

 

   1.2.2 激活函數

            PyTorch實現了常見的激活函數,這些激活函數可作爲獨立的layer使用。現在將介紹最常用的激活函數ReLU,其數學表達式爲:

                             

relu = nn.ReLU(inplace=True)
input = V(t.randn(2, 3))
print(input)
output = relu(input)  # 小於0的都被截斷爲0,等價於input.clamp(min=0)
print(output) 
# ---------------------------------------
tensor([[ 2.0321,  0.2355,  0.6804],
        [-0.0220,  1.2670, -1.6634]])
tensor([[2.0321, 0.2355, 0.6804],
        [0.0000, 1.2670, 0.0000]])

ReLU函數有個inplace參數,如果設爲True,他會把輸出直接覆蓋到輸入中,這樣節省內存/顯存。之所以可以覆蓋是因爲在計算ReLU的反向傳播時,只需根據輸出就能夠推算出反向傳播的梯度。但是隻有少數的autograd操作支持inplace操作,一般不要使用inplace操作。

在以上例子中,都是將每一層的輸出直接作爲下一層的輸入,這種網絡稱爲前饋傳播網絡(Feedforward Neural Network)。

對於此類網絡,如果每次都寫複雜的forward函數會有些麻煩,在此就有兩種簡化方式,ModuleList和Sequential。其中Sequential是一個特殊的Module,它包含幾個子module,前向傳播時會將輸入一層接一層地傳遞下去。ModuleList也是一個特殊的Module,可以包含幾個子module,可以像用list一樣使用它,但不能直接把輸入傳給ModuleList。

下面舉例說明:

from __future__ import print_function
import torch as t
from torch import nn
from torch.autograd import Variable as V
from collections import OrderedDict

# Sequential的三種寫法
net1 = nn.Sequential()
net1.add_module('conv', nn.Conv2d(3, 3, 3))
net1.add_module('batchnorm', nn.BatchNorm2d(3))
net1.add_module('activation_layer', nn.ReLU())

net2 = nn.Sequential(
        nn.Conv2d(3, 3, 3),
        nn.BatchNorm2d(3),
        nn.ReLU()
        )

net3 = nn.Sequential(OrderedDict([
    ('conv1', nn.Conv2d(3, 3, 3)),
    ('bn1', nn.BatchNorm2d(3)),
    ('relu1', nn.ReLU())
]))

print('net1:', net1)
print('net2:', net2)
print('net3:', net3)

# 可根據名字或序號取出子module
print(net1.conv, net2[0], net3.conv1)

input = V(t.rand(1, 3, 4, 4))
output = net1(input)
output = net2(input)
output = net3(input)
output = net3.relu1(net1.batchnorm(net1.conv(input)))
modellist = nn.ModuleList([nn.Linear(3, 4), nn.ReLU(), nn.Linear(4, 2)])
input = V(t.randn(1, 3))
for model in modellist:
    input = model(input)
# 下面會報錯,因爲modelist沒有實現forward方法
# output = modelist(input)

1.2.3 循環神經網絡(RNN)

PyTorch中實現的最常見的三種RNN:RNN(vanilla RNN)、LSTM和GRU。此外還有對應的三種RNNCell。

RNN和RNNCell層的區別在於前者能夠處理整個序列,而後者一次只處理序列中一個時間點的數據。前者封裝更完備更易於使用,後者更具靈活性。RNN層可以通過組合調用RNNCell來實現。

from __future__ import print_function
import torch as t
from torch import nn
from torch.autograd import Variable as V


t.manual_seed(1000)
# 輸入:batch_size=3,序列長度都爲2,序列中的每個元素佔4維
input = V(t.randn(2, 3, 4))
# lstm輸入向量4維,3個隱藏元,1層
lstm = nn.LSTM(4, 3, 1)
# 初始狀態:1層,batch_size=3,3個隱藏元
h0 = V(t.randn(1, 3, 3))
c0 = V(t.randn(1, 3, 3))
out, hn = lstm(input, (h0, c0))
print(out)
#---------------------------------------------------
tensor([[[-0.3610, -0.1643,  0.1631],
         [-0.0613, -0.4937, -0.1642],
         [ 0.5080, -0.4175,  0.2502]],

        [[-0.0703, -0.0393, -0.0429],
         [ 0.2085, -0.3005, -0.2686],
         [ 0.1482, -0.4728,  0.1425]]], grad_fn=<StackBackward>)
#---------------------------------------------------

 

t.manual_seed(1000)
input = V(t.randn(2, 3, 4))
# 一個LSTMCell對應的層數只能是一層
lstm = nn.LSTMCell(4, 3)
hx = V(t.randn(3, 3))
cx = V(t.randn(3, 3))
out = []
for i_ in input:
    hx, cx = lstm(i_, (hx, cx))
    out.append(hx)
print(t.stack(out))
#-----------------------------------------------------
tensor([[[-0.3610, -0.1643,  0.1631],
         [-0.0613, -0.4937, -0.1642],
         [ 0.5080, -0.4175,  0.2502]],

        [[-0.0703, -0.0393, -0.0429],
         [ 0.2085, -0.3005, -0.2686],
         [ 0.1482, -0.4728,  0.1425]]], grad_fn=<StackBackward>)

 

 

 

 

 

 

 

 

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