作者:infiniteft
链接:https://www.zhihu.com/question/66782101/answer/579393790
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

两者的相同之处:

  • nn.Xxxnn.functional.xxx的实际功能是相同的,即nn.Conv2dnn.functional.conv2d 都是进行卷积,nn.Dropoutnn.functional.dropout都是进行dropout,。。。。。;
  • 运行效率也是近乎相同。

nn.functional.xxx是函数接口,而nn.Xxxnn.functional.xxx的类封装,并且nn.Xxx都继承于一个共同祖先nn.Module这一点导致nn.Xxx除了具有nn.functional.xxx功能之外,内部附带了nn.Module相关的属性和方法,例如train(), eval(),load_state_dict, state_dict 等。

两者的差别之处:

  • 两者的调用方式不同。

nn.Xxx 需要先实例化并传入参数,然后以函数调用的方式调用实例化的对象并传入输入数据。

inputs = torch.rand(64, 3, 244, 244)
conv = nn.Conv2d(in_channels=3, out_channels=64, kernel_size=3, padding=1)
out = conv(inputs)

nn.functional.xxx同时传入输入数据和weight, bias等其他参数 。

weight = torch.rand(64,3,3,3)
bias = torch.rand(64)
out = nn.functional.conv2d(inputs, weight, bias, padding=1)
  • nn.Xxx继承于nn.Module, 能够很好的与nn.Sequential结合使用, 而nn.functional.xxx无法与nn.Sequential结合使用。
 fm_layer = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=3, padding=1),
nn.BatchNorm2d(num_features=64),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2),
nn.Dropout(0.2)
)
  • nn.Xxx不需要你自己定义和管理weight;而nn.functional.xxx需要你自己定义weight,每次调用的时候都需要手动传入weight, 不利于代码复用。

使用nn.Xxx定义一个CNN 。

class CNN(nn.Module):

    def __init__(self):
super(CNN, self).__init__() self.cnn1 = nn.Conv2d(in_channels=1, out_channels=16, kernel_size=5,padding=0)
self.relu1 = nn.ReLU()
self.maxpool1 = nn.MaxPool2d(kernel_size=2) self.cnn2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=5, padding=0)
self.relu2 = nn.ReLU()
self.maxpool2 = nn.MaxPool2d(kernel_size=2) self.linear1 = nn.Linear(4 * 4 * 32, 10) def forward(self, x):
x = x.view(x.size(0), -1)
out = self.maxpool1(self.relu1(self.cnn1(x)))
out = self.maxpool2(self.relu2(self.cnn2(out)))
out = self.linear1(out.view(x.size(0), -1))
return out

使用nn.function.xxx定义一个与上面相同的CNN。

class CNN(nn.Module):

    def __init__(self):
super(CNN, self).__init__() self.cnn1_weight = nn.Parameter(torch.rand(16, 1, 5, 5))
self.bias1_weight = nn.Parameter(torch.rand(16)) self.cnn2_weight = nn.Parameter(torch.rand(32, 16, 5, 5))
self.bias2_weight = nn.Parameter(torch.rand(32)) self.linear1_weight = nn.Parameter(torch.rand(4 * 4 * 32, 10))
self.bias3_weight = nn.Parameter(torch.rand(10)) def forward(self, x):
x = x.view(x.size(0), -1)
out = F.conv2d(x, self.cnn1_weight, self.bias1_weight)
out = F.relu(out)
out = F.max_pool2d(out) out = F.conv2d(x, self.cnn2_weight, self.bias2_weight)
out = F.relu(out)
out = F.max_pool2d(out) out = F.linear(x, self.linear1_weight, self.bias3_weight)
return out

上面两种定义方式得到CNN功能都是相同的,至于喜欢哪一种方式,是个人口味问题,但PyTorch官方推荐:具有学习参数的(例如,conv2d, linear, batch_norm)采用nn.Xxx方式,没有学习参数的(例如,maxpool, loss func, activation func)等根据个人选择使用nn.functional.xxx或者nn.Xxx方式。但关于dropout,个人强烈推荐使用nn.Xxx方式,因为一般情况下只有训练阶段才进行dropout,在eval阶段都不会进行dropout。使用nn.Xxx方式定义dropout,在调用model.eval()之后,model中所有的dropout layer都关闭,但以nn.function.dropout方式定义dropout,在调用model.eval()之后并不能关闭dropout。

class Model1(nn.Module):

    def __init__(self):
super(Model1, self).__init__()
self.dropout = nn.Dropout(0.5) def forward(self, x):
return self.dropout(x) class Model2(nn.Module): def __init__(self):
super(Model2, self).__init__() def forward(self, x):
return F.dropout(x) m1 = Model1()
m2 = Model2()
inputs = torch.rand(10)
print(m1(inputs))
print(m2(inputs))
print(20 * '-' + "eval model:" + 20 * '-' + '\r\n')
m1.eval()
m2.eval()
print(m1(inputs))
print(m2(inputs))

输出:

从上面输出可以看出m2调用了eval之后,dropout照样还在正常工作。当然如果你有强烈愿望坚持使用nn.functional.dropout,也可以采用下面方式来补救。

 class Model3(nn.Module):

    def __init__(self):
super(Model3, self).__init__() def forward(self, x):
return F.dropout(x, training=self.training)

什么时候使用nn.functional.xxx,什么时候使用nn.Xxx?

这个问题依赖于你要解决你问题的复杂度和个人风格喜好。在nn.Xxx不能满足你的功能需求时,nn.functional.xxx是更佳的选择,因为nn.functional.xxx更加的灵活(更加接近底层),你可以在其基础上定义出自己想要的功能。

个人偏向于在能使用nn.Xxx情况下尽量使用,不行再换nn.functional.xxx ,感觉这样更能显示出网络的层次关系,也更加的纯粹(所有layer和model本身都是Module,一种和谐统一的感觉)。

PyTorch 中,nn 与 nn.functional 有什么区别?的更多相关文章

  1. pytorch 中序列化容器nn.Sequential

    按下图顺序搭建以及执行

  2. pytorch 中 repeat 和 expend 的功能和区别

    功能 均是用于扩展张量的维度 区别 tensor.expand(*sizes) 将张量中单维度(singleton dimensions,即张量在某个维度上为1的维度,exp(1,2,3),其中在第一 ...

  3. pytorch中文文档-torch.nn.init常用函数-待添加

    参考:https://pytorch.org/docs/stable/nn.html torch.nn.init.constant_(tensor, val) 使用参数val的值填满输入tensor ...

  4. pytorch 中的重要模块化接口nn.Module

    torch.nn 是专门为神经网络设计的模块化接口,nn构建于autgrad之上,可以用来定义和运行神经网络 nn.Module 是nn中重要的类,包含网络各层的定义,以及forward方法 对于自己 ...

  5. pytorch中文文档-torch.nn常用函数-待添加-明天继续

    https://pytorch.org/docs/stable/nn.html 1)卷积层 class torch.nn.Conv2d(in_channels, out_channels, kerne ...

  6. [转载]Pytorch中nn.Linear module的理解

    [转载]Pytorch中nn.Linear module的理解 本文转载并援引全文纯粹是为了构建和分类自己的知识,方便自己未来的查找,没啥其他意思. 这个模块要实现的公式是:y=xAT+*b 来源:h ...

  7. Pytorch中nn.Dropout2d的作用

    Pytorch中nn.Dropout2d的作用 首先,关于Dropout方法,这篇博文有详细的介绍.简单来说, 我们在前向传播的时候,让某个神经元的激活值以一定的概率p停止工作,这样可以使模型泛化性更 ...

  8. Pytorch中nn.Conv2d的用法

    Pytorch中nn.Conv2d的用法 nn.Conv2d是二维卷积方法,相对应的还有一维卷积方法nn.Conv1d,常用于文本数据的处理,而nn.Conv2d一般用于二维图像. 先看一下接口定义: ...

  9. pytorch中的nn.CrossEntropyLoss()

    nn.CrossEntropyLoss()这个损失函数和我们普通说的交叉熵还是有些区别 x是模型生成的结果,class是对应的label 具体代码可参见如下 import torch import t ...

随机推荐

  1. Spring boot 整合hive-jdbc导致无法启动的问题

    使用Spring boot整合Hive,在启动Spring boot项目时,报出异常: 经过排查,是maven的包冲突引起的,具体做法,排除:jetty-all.hive-shims依赖包.对应的po ...

  2. Centos7搭建Postfix发送邮件 Connection timed out

    telent  mx1.qq.com 25 25这个端口是不加密的,不安全,qq邮箱和网易的邮箱早就不用了.采用加密的方式

  3. centos6.6 7 vim编辑器中文乱码

    编辑~/.vimrc文件,加上如下几行: set fileencodings=utf-8,ucs-bom,gb18030,gbk,gb2312,cp936 set termencoding=utf-8 ...

  4. nginx: [error] invalid PID number "" in "/usr/local/webserver/nginx/logs/nginx.pid" (原)

    进入nginx文件下,例如 :/usr/local/nginx/sbin [root@iZ25f7emo7cZ /]# cd /usr/local/nginx/sbin 运行命令: [root@iZ2 ...

  5. ecshop 前台分页

    在当前需要分页的if最后div里面加入这句, <!-- #BeginLibraryItem "/library/pages.lbi" --><!-- #EndLi ...

  6. MyBatis基础入门《十二》删除数据 - @Param参数

    MyBatis基础入门<十二>删除数据 - @Param参数 描述: 删除数据,这里使用了@Param这个注解,其实在代码中,不使用这个注解也可以的.只是为了学习这个@Param注解,为此 ...

  7. Docker 在转发端口时的这个错误Error starting userland proxy: mkdir /port/tcp:0.0.0.0:3306:tcp:172.17.0.2:3306: input/output error.

    from:https://www.v2ex.com/amp/t/463719 系统环境是 Windows 10 Pro,Docker 版本 18.03.1-ce,电脑开机之后第一次运行 docker ...

  8. scala mysql jdbc oper

    package egsql import java.util.Properties import com.sun.org.apache.xalan.internal.xsltc.compiler.ut ...

  9. Web界面进行用户管理

    Web界面进行用户管理 添加用户           Tags:表示账号的角色 Admin:超级管理员 No access :表示没有可以访问的virtual host虚拟机(相当于数据库)     ...

  10. 使用.NET向webService传double、int、DateTime 服务器得到的数据时null的问题(转http://blog.csdn.net/slimboy123/article/details/4366701)

    用C#.NET调用Java开发的WebService时,先在客户端封装的带有int属性的对象,当将该对象传到服务器端时,服务器端可以得到string类型的属性值,却不能得到int类型.double和D ...