淺析PyTorch中nn.Module的使用
更新時間:2019年08月18日 10:52:30 作者:Steven·簡談
這篇文章主要介紹了淺析PyTorch中nn.Module的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
torch.nn.Modules 相當于是對網絡某種層的封裝,包括網絡結構以及網絡參數(shù)和一些操作
torch.nn.Module 是所有神經網絡單元的基類
查看源碼
初始化部分:
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:字典,保存用戶直接設置的 Parameter
- _modules:子 module,即子類構造函數(shù)中的內容
- _buffers:緩存
- _backward_hooks與_forward_hooks:鉤子技術,用來提取中間變量
- training:判斷值來決定前向傳播策略
方法定義:
def forward(self, *input): raise NotImplementedError
沒有實際內容,用于被子類的 forward() 方法覆蓋
且 forward 方法在 __call__ 方法中被調用:
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 是輸出層線性輸出
打印出網絡的結構:
>>> 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) )
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Python3將數(shù)據(jù)保存為txt文件的方法
這篇文章主要介紹了Python3將數(shù)據(jù)保存為txt文件的方法,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09Python數(shù)據(jù)類型之Tuple元組實例詳解
這篇文章主要介紹了Python數(shù)據(jù)類型之Tuple元組,結合實例形式分析了Python元組類型的概念、定義、讀取、連接、判斷等常見操作技巧與相關注意事項,需要的朋友可以參考下2019-05-05pytorch 在網絡中添加可訓練參數(shù),修改預訓練權重文件的方法
今天小編就為大家分享一篇pytorch 在網絡中添加可訓練參數(shù),修改預訓練權重文件的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08