Pytorch本人疑问(1) torch.nn和torch.nn.functional之间的区别
在写代码时发现我们在定义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之间的区别的更多相关文章
- Pytorch本人疑问(2)model.train()和model.eval()的区别
我们在训练时如果使用了BN层和Dropout层,我们需要对model进行标识: model.train():在训练时使用BN层和Dropout层,对模型进行更改. model.eval():在评价时将 ...
- [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 ...
- 小白学习之pytorch框架(2)-动手学深度学习(begin-random.shuffle()、torch.index_select()、nn.Module、nn.Sequential())
在这向大家推荐一本书-花书-动手学深度学习pytorch版,原书用的深度学习框架是MXNet,这个框架经过Gluon重新再封装,使用风格非常接近pytorch,但是由于pytorch越来越火,个人又比 ...
- 从 relu 的多种实现来看 torch.nn 与 torch.nn.functional 的区别与联系
从 relu 的多种实现来看 torch.nn 与 torch.nn.functional 的区别与联系 relu多种实现之间的关系 relu 函数在 pytorch 中总共有 3 次出现: torc ...
- pytorch记录:seq2seq例子看看这torch怎么玩的
先看看简单例子: import torch import torch.autograd as autograd import torch.nn as nn import torch.nn.functi ...
- 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 ...
- 【Pytorch】关于torch.matmul和torch.bmm的输出tensor数值不一致问题
发现 对于torch.matmul和torch.bmm,都能实现对于batch的矩阵乘法: a = torch.rand((2,3,10))b = torch.rand((2,2,10))### ma ...
- PyTorch 中,nn 与 nn.functional 有什么区别?
作者:infiniteft链接:https://www.zhihu.com/question/66782101/answer/579393790来源:知乎著作权归作者所有.商业转载请联系作者获得授权, ...
- pytorch(11)模型创建步骤与nn.Module
模型创建与nn.Module 网络模型创建步骤 nn.Module graph LR 模型 --> 模型创建 模型创建 --> 构建网络层 构建网络层 --> id[卷积层,池化层, ...
随机推荐
- PHP基础学习笔记5
一.连接MYSQL 1.1 MySQLi - 面向对象 <?php $servername = "localhost"; $username = "username ...
- December 31st, Week 53rd Tuesday, 2019
Nothing comes from nothing. 天下没有免费的午餐. Nothing comes from nothing, and in some cases, even something ...
- [转]工作量证明(PoW)权益证明(PoS)和委任权益证明(DPoS)区别
原文链接 Both in the glossary and in some of our previous posts we've touched on mining and the two main ...
- pandas库笔记
本笔记为自学笔记 1.pandas.DataFrame() 一种保存矩阵的数据格式 grades_df = pd.DataFrame( data={'exam1': [43, 81, 78, 75, ...
- 吴裕雄 python 神经网络——TensorFlow实现搭建基础神经网络
import numpy as np import tensorflow as tf import matplotlib.pyplot as plt def add_layer(inputs, in_ ...
- Tiny-shell
Tiny-shell:一个模仿bash的极简shell (一) 概述 通过构建一个简单的shell,能够对shell的工作原理进行一些了解.主要有: 重定向 流水线 前台信号处理 进程组 后台进程 作 ...
- Ubuntu mysql 在线安装
$ sudo apt install mysql-server
- zookeeper的安装(单机版)
一.获取zookeeper的安装包 zookeeper的官网下载:wget https://archive.apache.org/dist/zookeeper/zookeeper-3.4.10/zo ...
- VS2017中使用C++语言编写delay函数实现延迟
秒级别的延时 //定义函数 void delay(int sec){ time_t start_time, cur_time; // 变量声明 time(&start_time); do { ...
- idea中使用Autowired注入时报红,但是运行不报错
在Preferences中如下设置,即可解除报红错误: 将Autowiring for Bean Class的Severity级别设置为Warning