『pytorch』第十二弹_nn.module和nn.functional

叠加态的猫 叠加态的猫     2022-10-22     428

关键词:

大部分nn中的层class都有nn.function对应,其区别是:

  • nn.Module实现的layer是由class Layer(nn.Module)定义的特殊类,会自动提取可学习参数nn.Parameter
  • nn.functional中的函数更像是纯函数,由def function(input)定义。

由于两者性能差异不大,所以具体使用取决于个人喜好。对于激活函数和池化层,由于没有可学习参数,一般使用nn.functional完成,其他的有学习参数的部分则使用类。但是Droupout由于在训练和测试时操作不同,所以建议使用nn.Module实现,它能够通过model.eval加以区分。

一、nn.functional函数基本使用

import torch as t
import torch.nn as nn
from torch.autograd import Variable as V

input_ = V(t.randn(2, 3))
model = nn.Linear(3, 4)
output1 = model(input_)
output2 = nn.functional.linear(input_, model.weight, model.bias)
print(output1 == output2)

b1 = nn.functional.relu(input_)
b2 = nn.ReLU()(input_)
print(b1 == b2)

 

二、搭配使用nn.Module和nn.functional

并不是什么难事,之前有接触过,nn.functional不需要放入__init__进行构造,所以不具有可学习参数的部分可以使用nn.functional进行代替。

 『PyTorch』第四弹_通过LeNet初识pytorch神经网络_下

# Author : Hellcat
# Time   : 2018/2/11
 
import torch as t
import torch.nn as nn
import torch.nn.functional as F
 
class LeNet(nn.Module):
    def __init__(self):
        super(LeNet,self).__init__()
        self.conv1 = nn.Conv2d(3, 6, 5)
        self.conv2 = nn.Conv2d(6,16,5)
        self.fc1 = nn.Linear(16*5*5,120)
        self.fc2 = nn.Linear(120,84)
        self.fc3 = nn.Linear(84,10)
 
    def forward(self,x):
        x = F.max_pool2d(F.relu(self.conv1(x)),(2,2))
        x = F.max_pool2d(F.relu(self.conv2(x)),2)
        x = x.view(x.size()[0], -1)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x
 

 

三、nn.functional函数构造nn.Module类

两者主要的区别就是对于可学习参数nn.Parameter的识别能力,所以构造时添加了识别能力即可。

『PyTorch』第七弹_nn.Module扩展层

class Linear(nn.Module):
    def __init__(self, in_features, out_features):
        # nn.Module.__init__(self)
        super(Linear, self).__init__()
        self.w = nn.Parameter(t.randn(out_features, in_features))  # nn.Parameter是特殊Variable
        self.b = nn.Parameter(t.randn(out_features))

    def forward(self, x):
        # wx+b
        return F.linear(x, self.w, self.b)

layer = Linear(4, 3)
input = V(t.randn(2, 4))
output = layer(input)
print(output)

Variable containing:
 1.7498 -0.8839  0.5314
-2.4863 -0.6442  1.1036
[torch.FloatTensor of size 2x3]

 

『pytorch』第十三弹_torch.nn.init参数初始化

初始化参数的方法nn.Module模块对于参数进行了内置的较为合理的初始化方式,当我们使用nn.Parameter时,初始化就很重要,而且我们也可以指定代替内置初始化的方式对nn.Module模块进行补充。除了之前的.data进行赋值,或者.data.初... 查看详情

『pytorch』第十一弹_torch.optim优化器

一、简化前馈网络LeNetimporttorchastclassLeNet(t.nn.Module):def__init__(self):super(LeNet,self).__init__()self.features=t.nn.Sequential(t.nn.Conv2d(3,6,5),t.nn.ReLU(),t.nn.MaxPool2d(2,2),t.nn.Conv2d(6,16,5),t. 查看详情

『pytorch』第七弹_nn.module扩展层(代码片段)

有下面代码可以看出torch层函数(nn.Module)用法,使用超参数实例化层函数类(常位于网络class的__init__中),而网络class实际上就是一个高级的递归的nn.Module的class。 通常torch.nn的核心数据结构是Module,它是一个抽象概念,既可以... 查看详情

每天讲解一点pytorch14模型定义,继承nn.module(代码片段)

今天我们讲解class的定义和实现:classDec(nn.Module):#继承nn.Module类def__init__(self,***,***):#构建模块super(Dec,self).__init__()#父类初始化self.***=***self.***=***defforward(self,x,***):#组装x=***returnself.* 查看详情

每天讲解一点pytorch14模型定义,继承nn.module(代码片段)

今天我们讲解class的定义和实现:classDec(nn.Module):#继承nn.Module类def__init__(self,***,***):#构建模块super(Dec,self).__init__()#父类初始化self.***=***self.***=***defforward(self,x,***):#组装x=***returnself.* 查看详情

pytorch基础(代码片段)

目录AneasywaySaveandreloadTrainonbatchOptimizersCNNAneasyway使用torch.nn.Sequential()来更快地构建神经网络:importtorchimporttorch.nn.functionalasF#replacefollowingclasscodewithaneasysequentialnetworkclassNet(torch.nn.Module):def__init__(self,n_feature,n_hidden,n_output):super(Net,self... 查看详情

pytorch:torch.nn(代码片段)

importtorchastfromtorchimportnnclassLinear(nn.Module):#继承nn.Moduledef__init__(self,in_features,out_features):super(Linear,self).__init__()#等价于nn.Module.__init__(self)self.w=nn.Parameter(t.randn(in_features,out_features))self.b=nn.Parameter(t.randn(out_features))defforward(self,x):x=x.mm(se... 查看详情

pytorch中module,parameter和buffer的区别(代码片段)

下文都将torch.nn简写成nnModule:就是我们常用的torch.nn.Module类,你定义的所有网络结构都必须继承这个类。Buffer:buffer和parameter相对,就是指那些不需要参与反向传播的参数示例如下:classMyModel(nn.Module):def__init__(self):super(MyModel,self)._... 查看详情

第十二弹:ss(selectivesearch)

以下开始介绍基于区域选择的目标识别任务的模型。首先介绍一个选择搜索的方法,接着介绍一篇评述所有区域选择算法优劣的论文 一、论文笔记一、摘要本文主要介绍物体识别中的一种选择性搜索(SelectiveSearch)方法。物... 查看详情

pytorch中nn.module类简介(代码片段)

   torch.nn.Module类是所有神经网络模块(modules)的基类,它的实现在torch/nn/modules/module.py中。你的模型也应该继承这个类,主要重载__init__、forward和extra_repr函数。Modules还可以包含其它Modules,从而可以将它们嵌套在树结... 查看详情

pytorch加载预训练模型前n层

importtorch.nnasnnimporttorchvision.modelsasmodelsclassresnet(nn.Module):def__init__(self):super(resnet,self).__init__()self.model=models.resnet18(pretrained=True)self.encoder=nn.Sequential(*list(self 查看详情

pytorch之bulid_nn_with_2_method(代码片段)

1importtorch2importtorch.nn.functionalasF345#replacefollowingclasscodewithaneasysequentialnetwork6classNet(torch.nn.Module):7def__init__(self,n_feature,n_hidden,n_output):8super(Net,self).__init__()9self.hidden=torch.nn.Linear(n_feature,n_hidden)#hiddenlayer10self.predict=torch.nn.Linear(n_hidden,n_... 查看详情

PyTorch:保存权重和模型定义

】PyTorch:保存权重和模型定义【英文标题】:PyTorch:savingbothweightsandmodeldefinition【发布时间】:2021-06-1313:44:48【问题描述】:在原型设计期间,我经常对PyTorch模型进行大量更改。例如,假设我正在试验的第一个模型是:classModel(n... 查看详情

pytorch实现sevariants(代码片段)

importtorchimporttorch.nnasnnimporttorchvisionclasscSE_Module(nn.Module):def__init__(self,channel,ratio=16):super(cSE_Module,self).__init__()self.squeeze=nn.AdaptiveAvgPool2d(1)self.excitation=nn.Sequential(nn.Linear(in_features=channel,out_features=channel//ratio),nn.ReLU(inplac... 查看详情

pytorch(网络模型)(代码片段)

上一篇神经网络鸡翅nn.Module官网importtorch.nnasnnimporttorch.nn.functionalasFclassModel(nn.Module):def__init__(self):super().__init__()self.conv1=nn.Conv2d(1,20,5)self.conv2=nn.Conv2d(20,20,5)defforward( 查看详情

pytorch深度学习实战3-6:详解网络骨架模块nn.module(附实例)(代码片段)

...多输出(MIMO)、多分支模型、跨层连接模型等。nn.Module就是Pytorch中用于自定义模型的核心方法。在Pytorch中,自定义层、自定义块、自定义模型,都是通过继承nn.Module类完成的。nn.Module的定义如下classModule(object):def__init__(self... 查看详情

pytorch 是不是在 nn.Linear 中自动应用 softmax

】pytorch是不是在nn.Linear中自动应用softmax【英文标题】:Doespytorchapplysoftmaxautomaticallyinnn.Linearpytorch是否在nn.Linear中自动应用softmax【发布时间】:2019-12-2206:29:06【问题描述】:在pytorch中定义了一个分类网络模型,classNet(torch.nn.Modul... 查看详情

pytorch-卷积基本网络结构-提取网络参数-初始化网络参数(代码片段)

基本的卷积神经网络fromtorchimportnnclassSimpleCNN(nn.Module):def__init__(self):super(SimpleCNN,self).__init__()layer1=nn.Sequential()#将网络模型进行添加layer1.add_module(‘conv1‘,nn.Conv2d(3,32,3,1,padding=1))#nn.Convlayer1.add_module(‘relu1‘,nn.ReLU(True))layer1.add_module(... 查看详情