在写代码时发现我们在定义Model时,有两种定义方法:

torch.nn.Conv2d()和torch.nn.functional.conv2d()

那么这两种方法到底有什么区别呢,我们通过下述代码看出差别,先拿torch.nn.Conv2d

  • torch.nn.Conv2d
class Conv2d(_ConvNd):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, dilation=1, groups=1,
bias=True, padding_mode='zeros'):
kernel_size = _pair(kernel_size)
stride = _pair(stride)
padding = _pair(padding)
dilation = _pair(dilation)
super(Conv2d, self).__init__(
in_channels, out_channels, kernel_size, stride, padding, dilation,
False, _pair(0), groups, bias, padding_mode) def forward(self, input):
return self.conv2d_forward(input, self.weight)
  • torch.nn.functional.conv2d
def conv2d(input, weight, bias=None, stride=1, padding=0, dilation=1,
groups=1):
if input is not None and input.dim() != 4:
raise ValueError("Expected 4D tensor as input, got {}D tensor instead.".format(input.dim()))
f = _ConvNd(_pair(stride), _pair(padding), _pair(dilation), False,
_pair(0), groups, torch.backends.cudnn.benchmark,
torch.backends.cudnn.deterministic,torch.backends.cudnn.enabled)
return f(input, weight, bias)

对比上述代码我们可以发现,torch.nn.Conv2d是一个类,而torch.nn.functiona.conv2d()是一个函数,并且torch.nn.Conv2d中的forward()函数

是由torch.nn.functiona.conv2d()实现的(在Module类中有一个__call__实现了forward的调用)所以他们在功能的使用上并没有什么区别,但是我

们有了一个疑问,为什么要有着两个功能一样的方法呢?

其实主要的原因在乎我们构建计算图的时候,有些操作不需要进行体现在计算图中的,例如ReLu层,池化层。但是像卷积层、全连接层还是

需要体现在计算图中的。如果所有的层我们都用torch.nn.functional来定义,那么我们需要将卷积层和全连接层中的weights、bias全部手动写入

计算图中去,这样是非常不方便的。如果我们全部使用类的方式来构建计算图,这样即使是非常简单的操作都需要构建类,这样是写代码的效率是

非常低的。所以我们将卷积层、全连接层使用类的方式来进行定义,将池化和激活操作使用函数的方式进行使用,这样使我们更方便的构建计算图。

Pytorch本人疑问(1) torch.nn和torch.nn.functional之间的区别的更多相关文章

  1. Pytorch本人疑问(2)model.train()和model.eval()的区别

    我们在训练时如果使用了BN层和Dropout层,我们需要对model进行标识: model.train():在训练时使用BN层和Dropout层,对模型进行更改. model.eval():在评价时将 ...

  2. [pytorch笔记] torch.nn vs torch.nn.functional; model.eval() vs torch.no_grad(); nn.Sequential() vs nn.moduleList

    1. torch.nn与torch.nn.functional之间的区别和联系 https://blog.csdn.net/GZHermit/article/details/78730856 nn和n ...

  3. 小白学习之pytorch框架(2)-动手学深度学习(begin-random.shuffle()、torch.index_select()、nn.Module、nn.Sequential())

    在这向大家推荐一本书-花书-动手学深度学习pytorch版,原书用的深度学习框架是MXNet,这个框架经过Gluon重新再封装,使用风格非常接近pytorch,但是由于pytorch越来越火,个人又比 ...

  4. 从 relu 的多种实现来看 torch.nn 与 torch.nn.functional 的区别与联系

    从 relu 的多种实现来看 torch.nn 与 torch.nn.functional 的区别与联系 relu多种实现之间的关系 relu 函数在 pytorch 中总共有 3 次出现: torc ...

  5. pytorch记录:seq2seq例子看看这torch怎么玩的

    先看看简单例子: import torch import torch.autograd as autograd import torch.nn as nn import torch.nn.functi ...

  6. PyTorch - torch.eq、torch.ne、torch.gt、torch.lt、torch.ge、torch.le

    PyTorch - torch.eq.torch.ne.torch.gt.torch.lt.torch.ge.torch.le 参考:https://flyfish.blog.csdn.net/art ...

  7. 【Pytorch】关于torch.matmul和torch.bmm的输出tensor数值不一致问题

    发现 对于torch.matmul和torch.bmm,都能实现对于batch的矩阵乘法: a = torch.rand((2,3,10))b = torch.rand((2,2,10))### ma ...

  8. PyTorch 中,nn 与 nn.functional 有什么区别?

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

  9. pytorch(11)模型创建步骤与nn.Module

    模型创建与nn.Module 网络模型创建步骤 nn.Module graph LR 模型 --> 模型创建 模型创建 --> 构建网络层 构建网络层 --> id[卷积层,池化层, ...

随机推荐

  1. Atcoder Beginner Contest151E(排列组合)

    排列组合 #define HAVE_STRUCT_TIMESPEC #include<bits/stdc++.h> using namespace std; ]; ; ]; long lo ...

  2. go基础_函数

    函数的基本写法 func add(a int, b int) int { return a + b } 如果2个参数的类型一样,可以简写为 func add(a, b int) int { retur ...

  3. centos 6.10 安装mysql 5.7.27 出现缺少libnuma.so.1的问题

    centos 6.10安装mysql 5.7.27出现以下报错: [root@localhost /]# /usr/local/mysql/app/mysql/bin/mysqld --default ...

  4. JS中constructor属性

    constructor属性用于对当前对象的构造函数的引用.可以用来判断对象的类型: <script> var newStr = new String("One world One ...

  5. 「JSOI2016」灯塔

    「JSOI2016」灯塔 传送门 我们先只计算照亮左边的灯塔的最低高度,计算右边的类同,然后只要取 \(\max\) 就好了. 那么稍微整理一下式子:\(p_i \ge h_j - h_i + \sq ...

  6. Azure虚拟机网站部署 防火墙设置

    唯一需要注意的是当你的网站设置的端口不是默认的80的时候,需要在防火墙那里将你新设置的端口设置为allow 先要到云的后台设置  “入站安全规则”--> 将你的网站端口设置为Allow 1.通过 ...

  7. k8s Learning Notes

    Kubernetes - 组件介绍 MESOS APACHE 分布式资源管理框架 2019-5 Twitter > Kubernetes Docker Swarm 2019-07 阿里云宣布 D ...

  8. Java 线程高级

    1.volatile关键字:当多个线程操作共享数据时,可以保证内存中的数据可见,相较于syncronized是一种较为轻量级的同步策略, 注意:1.volatile不具有“互斥性” 2.volatil ...

  9. 最长公共子序列-Hdu1159

    Common Subsequence Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Other ...

  10. Fluent_Python_Part3函数即对象,05-1class-func,一等函数,函数即对象

    一等函数 一等函数即将函数看作一等对象.一等对象满足一下条件: 在运行时创建 能赋值给变量或数据结构中的元素 能作为参数传给函数 能作为函数的返回结果 1. 一等函数 例子1. 证明function是 ...