天天看點

pytorch神經網絡之卷積層與全連接配接層參數的設定

        當使用pytorch寫網絡結構的時候,本人發現在卷積層與第一個全連接配接層的全連接配接層的input_features不知道該寫多少?一開始本人的做法是對着pytorch官網的公式推,但是總是算錯。

        後來發現,寫完卷積層後可以根據模拟神經網絡的前向傳播得出這個。

        全連接配接層的input_features是多少。首先來看一下這個簡單的網絡。這個卷積的Sequential本人就不再啰嗦了,現在看

nn.Linear(???, 4096)

這個全連接配接層的第一個參數該為多少呢?請看下文詳解。

class AlexNet(nn.Module):
    def __init__(self):
        super(AlexNet, self).__init__()

        self.conv = nn.Sequential(
            nn.Conv2d(3, 96, kernel_size=11, stride=4),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),

            nn.Conv2d(96, 256, kernel_size=5, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),

            nn.Conv2d(256, 384, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(384, 384, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(384, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2)
        )

        self.fc = nn.Sequential(
            nn.Linear(???, 4096)
            ......
            ......
        )

           

        首先,我們先把forward寫一下:

def forward(self, x):
        x = self.conv(x)
        print x.size()
           

        就寫到這裡就可以了。其次,我們初始化一下網絡,随機一個輸入:

import torch
from Alexnet.AlexNet import *
from torch.autograd import Variable

if __name__ == '__main__':
    net = AlexNet()

    data_input = Variable(torch.randn([1, 3, 96, 96])) # 這裡假設輸入圖檔是96x96
    print data_input.size()
    net(data_input)
           

        結果如下:

(1L, 3L, 96L, 96L)
(1L, 256L, 1L, 1L)
           

        顯而易見,咱們這個全連接配接層的input_features為256。

繼續閱讀