淺析PyTorch中nn.Module的使用
torch.nn.Modules 相當于是對網(wǎng)絡某種層的封裝,包括網(wǎng)絡結構以及網(wǎng)絡參數(shù)和一些操作
torch.nn.Module 是所有神經(jīng)網(wǎng)絡單元的基類
查看源碼
初始化部分:
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ù)中的內(nèi)容
- _buffers:緩存
- _backward_hooks與_forward_hooks:鉤子技術,用來提取中間變量
- 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)絡的結構:
>>> 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)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
PyCharm+Pipenv虛擬環(huán)境開發(fā)和依賴管理的教程詳解
這篇文章主要介紹了PyCharm+Pipenv虛擬環(huán)境作開發(fā)和依賴管理的教程,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04
Python+Opencv實現(xiàn)計算閉合區(qū)域面積
這篇文章主要介紹了利用Python?Opencv計算閉合區(qū)域的面積的原理以及實現(xiàn)代碼,文中的講解詳細易懂,感興趣的小伙伴快跟隨小編一起學習一下吧2022-03-03
Python實現(xiàn)簡單的文件傳輸與MySQL備份的腳本分享
這篇文章主要介紹了Python實現(xiàn)簡單的文件傳輸與MySQL備份的腳本分享,用到了socket與tarfile模塊,需要的朋友可以參考下2016-01-01
Python win32com 操作Exce的l簡單方法(必看)
下面小編就為大家?guī)硪黄狿ython win32com 操作Exce的l簡單方法(必看)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05
PyTorch搭建雙向LSTM實現(xiàn)時間序列負荷預測
這篇文章主要為大家介紹了PyTorch搭建雙向LSTM實現(xiàn)時間序列負荷預測,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05
python數(shù)據(jù)庫開發(fā)之MongoDB安裝及Python3操作MongoDB數(shù)據(jù)庫詳細方法與實例
這篇文章主要介紹了python數(shù)據(jù)庫開發(fā)之MongoDB安裝及Python3操作MongoDB數(shù)據(jù)庫詳細方法與實例,需要的朋友可以參考下2020-03-03

