淺析PyTorch中nn.Module的使用
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)文章
Python3將數(shù)據(jù)保存為txt文件的方法
這篇文章主要介紹了Python3將數(shù)據(jù)保存為txt文件的方法,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09Python數(shù)據(jù)類型之Tuple元組實例詳解
這篇文章主要介紹了Python數(shù)據(jù)類型之Tuple元組,結(jié)合實例形式分析了Python元組類型的概念、定義、讀取、連接、判斷等常見操作技巧與相關(guān)注意事項,需要的朋友可以參考下2019-05-05pytorch 在網(wǎng)絡(luò)中添加可訓(xùn)練參數(shù),修改預(yù)訓(xùn)練權(quán)重文件的方法
今天小編就為大家分享一篇pytorch 在網(wǎng)絡(luò)中添加可訓(xùn)練參數(shù),修改預(yù)訓(xùn)練權(quán)重文件的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08python 多線程實現(xiàn)檢測服務(wù)器在線情況
本文給大家分享的是Python使用多線程通過ping命令檢測服務(wù)器的在線狀況,給大家了內(nèi)網(wǎng)和外網(wǎng)的2個例子,有需要的小伙伴可以參考下。2015-11-11Python和C語言利用棧分別實現(xiàn)進制轉(zhuǎn)換
這篇文章主要為大家詳細介紹了Python和C語言如何利用棧的數(shù)據(jù)結(jié)構(gòu)分別實現(xiàn)將十進制數(shù)轉(zhuǎn)換成二進制數(shù),文中的示例代碼講解詳細,需要的可以參考一下2022-07-07