pytorch 中forward 的用法與解釋說明
前言
最近在使用pytorch的時候,模型訓練時,不需要使用forward,只要在實例化一個對象中傳入對應的參數就可以自動調用 forward 函數
即:
forward 的使用
class Module(nn.Module): def __init__(self): super(Module, self).__init__() # ...... def forward(self, x): # ...... return x data = ..... #輸入數據 # 實例化一個對象 module = Module() # 前向傳播 module(data) # 而不是使用下面的 # module.forward(data)
實際上
module(data)
是等價于
module.forward(data)
forward 使用的解釋
等價的原因是因為 python calss 中的__call__和__init__方法.
class A(): def __call__(self): print('i can be called like a function') a = A() a()
out:
i can be called like a function
__call__里調用其他的函數
class A(): def __call__(self, param): print('i can called like a function') print('傳入參數的類型是:{} 值為: {}'.format(type(param), param)) res = self.forward(param) return res def forward(self, input_): print('forward 函數被調用了') print('in forward, 傳入參數類型是:{} 值為: {}'.format( type(input_), input_)) return input_ a = A() input_param = a('i') print("對象a傳入的參數是:", input_param)
out:
i can called like a function
傳入參數的類型是:<class ‘str'> 值為: i
forward 函數被調用了
in forward, 傳入參數類型是:<class ‘str'> 值為: i
對象a傳入的參數是: i
補充:Pytorch 模型中nn.Model 中的forward() 前向傳播不調用 解釋
在pytorch 中沒有調用模型的forward()前向傳播,只實列化后把參數傳入。
定義模型
class Module(nn.Module): def __init__(self): super(Module, self).__init__() # ...... def forward(self, x): # ...... return x data = ..... #輸入數據 # 實例化一個對象 module = Module() # 前向傳播 直接把輸入傳入實列化 module(data) #沒有使用module.forward(data)
實際上module(data) 等價于module.forward(data)
等價的原因是因為 python calss 中的__call__ 可以讓類像函數一樣調用
當執(zhí)行model(x)的時候,底層自動調用forward方法計算結果
class A(): def __call__(self): print('i can be called like a function') a = A() a() >>>i can be called like a function
在__call__ 里可調用其它的函數
class A(): def __call__(self, param): print('我在__call__中,傳入參數',param) res = self.forward(param) return res def forward(self, x): print('我在forward函數中,傳入參數類型是值為: ',x) return x a = A() y = a('i') >>> 我在__call__中,傳入參數 i >>>我在forward函數中,傳入參數類型是值為: i print("傳入的參數是:", y) >>>傳入的參數是: i
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關文章
淺談tensorflow語義分割api的使用(deeplab訓練cityscapes)
這篇文章主要介紹了淺談tensorflow語義分割api的使用(deeplab訓練cityscapes),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05