当前位置:网站首页>In pytorch function__ call__ And forward functions
In pytorch function__ call__ And forward functions
2022-07-02 19:11:00 【D.ziyu】
Beginners nn.Module, I can't understand all kinds of calls , Later I understood , I guess I'll forget , So write a note
init & call
Code :
class A():
def __init__(self):
print('init function ')
def __call__(self, param):
print('call function ', param)
a = A()
Output 
analysis :A Instantiate the class , Generating objects a, This process Automatically call _init_(), There is no call _call_()
Add a line to the above code
class A():
def __init__(self):
print('init function ')
def __call__(self, param):
print('call function ', param)
a = A()
a(1)
Output 
analysis :a It's the object ,python Let the object have parentheses like a function ( Parameters ) The function of , When using this function , Automatically call _call_()
_ call_() Other functions can be called in , Such as forward function
class A():
def __init__(self):
print('init function ')
def __call__(self, param):
print('call function ', param)
res = self.forward(param)
return res + 2
def forward(self, input_):
print('forward function ', input_)
return input_
a = A()
b = a(1)
print(' result b =',b)

analysis :_call _() Successfully called forward(), And the return value is given to b
Besides, I had a misunderstand , Think that the value of this class can only be used when the parameter is declared , This is wrong
class A():
def __init__(self):
print('init function ')
self.a = 100 # Declare parameters a
def __call__(self, param):
print('call function ', param)
res = self.forward(param)
return res + 2
def forward(self, input_):
print('forward function ', input_, self.a)
return input_
a = A()
b = a(1)
print(' result b =',b)
print(a.a)

nn.Module
Look at the example above , You know the _call _() The role of , Let's see more below CNN Example
from torch import nn
import torch
class Ding(nn.Module):
def __init__(self):
print('init')
super().__init__()
def forward(self, input):
output = input + 1
print("forward")
return output
dzy = Ding()
x = torch.tensor(1.0)
out = dzy(x)
print(out)
result :
analysis :
There is no call here _call_() and forward(), But it still shows forward, as a result of :Ding This subclass inherits the parent class nn.Module Inside call function , Next, go to the source code 
Find out _call_ Called _call_impl This function , It's equivalent to a nickname , Then go to this function to see


There are many parameters here , See reference for details 2. Found here forward_call Or _slow_forward, Or self.forward(), And this _slow_forward() Can also use self.forward()
therefore : _call _() It was used forward, And the parent class forward Override... In subclasses ( Simple code )
Of course , You can also rewrite __call__(), For example, we don't let it use forward()
from torch import nn
import torch
class Ding(nn.Module):
def __init__(self):
print('init')
super().__init__()
def __call__(self, input_):
print(' rewrite call, no need forward')
return 'hhh'
def forward(self, input):
output = input + 1
print("forward")
return output
dzy = Ding()
x = torch.tensor(1.0)
out = dzy(x)
print(out)

summary
Use object dzy(x) when , Parent class used nn.Module Of call function , Called forward, And this forward It was rewritten by us in subclasses .
Reference resources
https://blog.csdn.net/dss_dssssd/article/details/83750838
https://zhuanlan.zhihu.com/p/366461413
边栏推荐
- 开源物联网平台ThingsBoard的安装
- 使用CLion编译OGLPG-9th-Edition源码
- 2022 compilation principle final examination recall Edition
- R language uses Cox of epidisplay package Display function obtains the summary statistical information of Cox regression model (risk rate HR, adjusted risk rate and its confidence interval, P value of
- Learning summary of MySQL advanced 6: concept and understanding of index, detailed explanation of b+ tree generation process, comparison between MyISAM and InnoDB
- C的内存管理
- 页面标题组件
- 性能测试如何创造业务价值
- 中国信通院《数据安全产品与服务图谱》,美创科技实现四大板块全覆盖
- 二进制操作
猜你喜欢

Compile oglpg-9th-edition source code with clion

数据降维——因子分析

SLC、MLC、TLC 和 QLC NAND SSD 之间的区别:哪个更好?

思维意识转变是施工企业数字化转型成败的关键

Kubernetes three open interfaces first sight

Troubleshooting: kubectl reports an error validationerror: unknown field \u00a0

ICDE 2023|TKDE Poster Session(CFP)

消息队列消息丢失和消息重复发送的处理策略

Singapore summer tourism strategy: play Singapore Sentosa Island in one day

使用 Cheat Engine 修改 Kingdom Rush 中的金钱、生命、星
随机推荐
High frequency interview questions
ICDE 2023|TKDE Poster Session(CFP)
Kubernetes three open interfaces first sight
Gstore weekly gstore source code analysis (4): black and white list configuration analysis of security mechanism
STM32G0 USB DFU 升级校验出错-2
Mysql高级篇学习总结8:InnoDB数据存储结构页的概述、页的内部结构、行格式
聊聊电商系统中红包活动设计
Installation of thingsboard, an open source IOT platform
Introduction to the paper | analysis and criticism of using the pre training language model as a knowledge base
How performance testing creates business value
The R language dplyr package rowwise function and mutate function calculate the maximum value of multiple data columns in each row in the dataframe data, and generate the data column (row maximum) cor
metric_logger小解
Stratégie touristique d'été de Singapour: un jour pour visiter l'île de San taosha à Singapour
Stm32g0 USB DFU upgrade verification error -2
Use cheat engine to modify money, life and stars in Kingdom rush
R语言dplyr包rowwise函数、mutate函数计算dataframe数据中多个数据列在每行的最大值、并生成行最大值对应的数据列(row maximum)
产品经理应具备的能力
论文导读 | 机器学习在数据库基数估计中的应用
What is 9D movie like? (+ common sense of dimension space)
[paper reading] Ca net: leveraging contextual features for lung cancer prediction