溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

nn.Module接口怎么在pytorch中使用

發(fā)布時間:2021-03-09 16:39:17 來源:億速云 閱讀:166 作者:Leah 欄目:開發(fā)技術(shù)

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)
    # 當(dāng)調(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)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI