nn.Module接口怎么在pytorch中使用?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

torch.nn 是專門為神經(jīng)網(wǎng)絡(luò)設(shè)計的模塊化接口,nn構(gòu)建于autgrad之上,可以用來定義和運行神經(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ù),用來提取中間變量
training:判斷值來決定前向傳播策略
方法定義:
def forward(self, *input): raise NotImplementedError
沒有實際內(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) ... ...
對于自己定義的網(wǎng)絡(luò),需要注意以下幾點:
1)需要繼承nn.Module類,并實現(xiàn)forward方法,只要在nn.Module的子類中定義forward方法,backward函數(shù)就會被自動實現(xiàn)(利用autograd機制)
2)一般把網(wǎng)絡(luò)中可學(xué)習(xí)參數(shù)的層放在構(gòu)造函數(shù)中__init__(),沒有可學(xué)習(xí)參數(shù)的層如Relu層可以放在構(gòu)造函數(shù)中,也可以不放在構(gòu)造函數(shù)中(在forward函數(shù)中使用nn.Functional)
3)在forward中可以使用任何Variable支持的函數(shù),在整個pytorch構(gòu)建的圖中,是Variable在流動,也可以使用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__() # 等價與nn.Module.__init__()
# nn.Conv2d返回的是一個Conv2d class的一個對象,該類中包含forward函數(shù)的實現(xiàn)
# 當調(diào)用self.conv1(input)的時候,就會調(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的返回值是一個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))
# 固定樣本個數(shù),將其他維度的數(shù)據(jù)平鋪,無論你是幾通道,最終都會變成參數(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))
# 返回值也是一個Variable對象
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中模型的輸入是一個Variable,而且是Variable在圖中流動,不是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è)計公司行業(yè)資訊頻道,感謝各位的閱讀!
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機、免備案服務(wù)器”等云主機租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。
分享名稱:nn.Module接口怎么在pytorch中使用-創(chuàng)新互聯(lián)
瀏覽路徑:http://www.chinadenli.net/article16/djoegg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供自適應(yīng)網(wǎng)站、Google、用戶體驗、面包屑導(dǎo)航、定制網(wǎng)站、外貿(mào)建站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容