nn.Module接口怎么在pytorch中使用?相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。
torch.nn 是專門為神經(jīng)網(wǎng)絡(luò)設(shè)計(jì)的模塊化接口,nn構(gòu)建于autgrad之上,可以用來(lái)定義和運(yùn)行神經(jīng)網(wǎng)絡(luò)
nn.Module 是nn中重要的類,包含網(wǎng)絡(luò)各層的定義,以及forward方法
查看源碼
初始化部分:
def __init__(self): self._backend = thnn_backend self._parameters = OrderedDict() self._buffers = OrderedDict() self._backward_hooks = OrderedDict() self._forward_hooks = OrderedDict() self._forward_pre_hooks = OrderedDict() self._state_dict_hooks = OrderedDict() self._load_state_dict_pre_hooks = OrderedDict() self._modules = OrderedDict() self.training = True
屬性解釋:
_parameters:字典,保存用戶直接設(shè)置的 Parameter
_modules:子 module,即子類構(gòu)造函數(shù)中的內(nèi)容
_buffers:緩存
_backward_hooks與_forward_hooks:鉤子技術(shù),用來(lái)提取中間變量
training:判斷值來(lái)決定前向傳播策略
方法定義:
def forward(self, *input): raise NotImplementedError
沒(méi)有實(shí)際內(nèi)容,用于被子類的 forward() 方法覆蓋
且 forward 方法在 __call__ 方法中被調(diào)用:
def __call__(self, *input, **kwargs): for hook in self._forward_pre_hooks.values(): hook(self, input) if torch._C._get_tracing_state(): result = self._slow_forward(*input, **kwargs) else: result = self.forward(*input, **kwargs) ... ...
對(duì)于自己定義的網(wǎng)絡(luò),需要注意以下幾點(diǎn):
1)需要繼承nn.Module類,并實(shí)現(xiàn)forward方法,只要在nn.Module的子類中定義forward方法,backward函數(shù)就會(huì)被自動(dòng)實(shí)現(xiàn)(利用autograd機(jī)制)
2)一般把網(wǎng)絡(luò)中可學(xué)習(xí)參數(shù)的層放在構(gòu)造函數(shù)中__init__(),沒(méi)有可學(xué)習(xí)參數(shù)的層如Relu層可以放在構(gòu)造函數(shù)中,也可以不放在構(gòu)造函數(shù)中(在forward函數(shù)中使用nn.Functional)
3)在forward中可以使用任何Variable支持的函數(shù),在整個(gè)pytorch構(gòu)建的圖中,是Variable在流動(dòng),也可以使用for,print,log等
4)基于nn.Module構(gòu)建的模型中,只支持mini-batch的Variable的輸入方式,如,N*C*H*W
代碼示例:
class LeNet(nn.Module): def __init__(self): # nn.Module的子類函數(shù)必須在構(gòu)造函數(shù)中執(zhí)行父類的構(gòu)造函數(shù) super(LeNet, self).__init__() # 等價(jià)與nn.Module.__init__() # nn.Conv2d返回的是一個(gè)Conv2d class的一個(gè)對(duì)象,該類中包含forward函數(shù)的實(shí)現(xiàn) # 當(dāng)調(diào)用self.conv1(input)的時(shí)候,就會(huì)調(diào)用該類的forward函數(shù) self.conv1 = nn.Conv2d(1, 6, (5, 5)) # output (N, C_{out}, H_{out}, W_{out})` self.conv2 = nn.Conv2d(6, 16, (5, 5)) self.fc1 = nn.Linear(256, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): # F.max_pool2d的返回值是一個(gè)Variable, input:(10,1,28,28) ouput:(10, 6, 12, 12) x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) # input:(10, 6, 12, 12) output:(10,6,4,4) x = F.max_pool2d(F.relu(self.conv2(x)), (2, 2)) # 固定樣本個(gè)數(shù),將其他維度的數(shù)據(jù)平鋪,無(wú)論你是幾通道,最終都會(huì)變成參數(shù), output:(10, 256) x = x.view(x.size()[0], -1) # 全連接 x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = F.relu(self.fc3(x)) # 返回值也是一個(gè)Variable對(duì)象 return x def output_name_and_params(net): for name, parameters in net.named_parameters(): print('name: {}, param: {}'.format(name, parameters)) if __name__ == '__main__': net = LeNet() print('net: {}'.format(net)) params = net.parameters() # generator object print('params: {}'.format(params)) output_name_and_params(net) input_image = torch.FloatTensor(10, 1, 28, 28) # 和tensorflow不一樣,pytorch中模型的輸入是一個(gè)Variable,而且是Variable在圖中流動(dòng),不是Tensor。 # 這可以從forward中每一步的執(zhí)行結(jié)果可以看出 input_image = Variable(input_image) output = net(input_image) print('output: {}'.format(output)) print('output.size: {}'.format(output.size()))
看完上述內(nèi)容,你們掌握nn.Module接口怎么在pytorch中使用的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)成都網(wǎng)站設(shè)計(jì)公司行業(yè)資訊頻道,感謝各位的閱讀!
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。
分享名稱:nn.Module接口怎么在pytorch中使用-創(chuàng)新互聯(lián)
瀏覽路徑:http://www.ekvhdxd.cn/article16/djoegg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供自適應(yīng)網(wǎng)站、Google、用戶體驗(yàn)、面包屑導(dǎo)航、定制網(wǎng)站、外貿(mào)建站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容