亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

淺析PyTorch中nn.Module的使用

 更新時間:2019年08月18日 10:52:30   作者:Steven·簡談  
這篇文章主要介紹了淺析PyTorch中nn.Module的使用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

torch.nn.Modules 相當于是對網(wǎng)絡(luò)某種層的封裝,包括網(wǎng)絡(luò)結(jié)構(gòu)以及網(wǎng)絡(luò)參數(shù)和一些操作

torch.nn.Module 是所有神經(jīng)網(wǎng)絡(luò)單元的基類

查看源碼

初始化部分:

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)
  ...
  ...
 

實例展示

簡單搭建:

import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
  def __init__(self, n_feature, n_hidden, n_output):
    super(Net, self).__init__()
    self.hidden = nn.Linear(n_feature, n_hidden)
    self.out = nn.Linear(n_hidden, n_output)

  def forward(self, x):
    x = F.relu(self.hidden(x))
    x = self.out(x)
    return x

Net 類繼承了 torch 的 Module 和 __init__ 功能

hidden 是隱藏層線性輸出

out 是輸出層線性輸出

打印出網(wǎng)絡(luò)的結(jié)構(gòu):

>>> net = Net(n_feature=10, n_hidden=30, n_output=15)
>>> print(net)
Net(
 (hidden): Linear(in_features=10, out_features=30, bias=True)
 (out): Linear(in_features=30, out_features=15, bias=True)
)

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論