详情可参考:https://pytorch.org/docs/1.11/generated/torch.nn.Module.html?highlight=torch%20nn%20module%20apply#torch.nn.Module.apply

首先,我们知道pytorch的任何网络net,都是torch.nn.Module的子类,都算是module,也就是模块。
pytorch中的model.apply(fn)会递归地将函数fn应用到父模块的每个子模块submodule,也包括model这个父模块自身。
比如下面的网络例子中。net这个模块有两个子模块,分别为Linear(2,4)和Linear(4,8)。函数首先对Linear(2,4)和Linear(4,8)两个子模块调用init_weights函数,即print(m)打印Linear(2,4)和Linear(4,8)两个子模块。然后再对net模块进行同样的操作。如此完成递归地调用。从而完成model.apply(fn)或者net.apply(fn)。
个人水平有限,不足处望指正。
参考链接:https://blog.csdn.net/qq_37025073/article/details/106739513

@torch.no_grad()
def init_weights(m):
print(m)
if type(m) == nn.Linear:
m.weight.fill_(1.0)
print(m.weight)
net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))
net.apply(init_weights)

  

#输出:
Linear(in_features=2, out_features=2, bias=True)
Parameter containing:
tensor([[ 1., 1.],
[ 1., 1.]])
Linear(in_features=2, out_features=2, bias=True)
Parameter containing:
tensor([[ 1., 1.],
[ 1., 1.]])
Sequential(
(0): Linear(in_features=2, out_features=2, bias=True)
(1): Linear(in_features=2, out_features=2, bias=True)
)
Sequential(
(0): Linear(in_features=2, out_features=2, bias=True)
(1): Linear(in_features=2, out_features=2, bias=True)
)

  https://pytorch.org/docs/stable/generated/torch.nn.Module.html?highlight=nn%20module%20apply#torch.nn.Module.apply

如果我们想对某些特定的子模块submodule做一些针对性的处理,该怎么做呢。我们可以加入type(m) == nn.Linear:这类判断语句,从而对子模块m进行处理。如下,读者可以细细体会一下。

import torch.nn as nn
@torch.no_grad()
def init_weights(m):
print(m)
if type(m) == nn.Linear:
m.weight.fill_(1.0)
print(m.weight)
net = nn.Sequential(nn.Linear(2,4), nn.Linear(4, 8))
print(net)
print('isinstance torch.nn.Module',isinstance(net,torch.nn.Module))
print(' ')
net.apply(init_weights)

  可以先打印网络整体看看。调用apply函数后,先逐一打印子模块m,然后对子模块进行判断,打印Linear这类子模块m的权重。

#输出:
Sequential(
(0): Linear(in_features=2, out_features=4, bias=True)
(1): Linear(in_features=4, out_features=8, bias=True)
)
isinstance torch.nn.Module True Linear(in_features=2, out_features=4, bias=True)
Parameter containing:
tensor([[1., 1.],
[1., 1.],
[1., 1.],
[1., 1.]], requires_grad=True)
Linear(in_features=4, out_features=8, bias=True)
Parameter containing:
tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]], requires_grad=True)
Sequential(
(0): Linear(in_features=2, out_features=4, bias=True)
(1): Linear(in_features=4, out_features=8, bias=True)
)

  

网友:所以说apply函数是有顺序的,先在子模块上操作,最后在父模块上操作。

model.apply(fn)或net.apply(fn)的更多相关文章

  1. Function.apply.bind()与Function.apply.bind()

    1.Function.apply.bind(…) 我在学习promise部分的时候遇到了这样的代码: Promise.resolve([10,20]).then(Function.apply.bind ...

  2. jQuery源码-jQuery.fn.attr与jQuery.fn.prop

    jQuery.fn.attr.jQuery.fn.prop的区别 假设页面有下面这么个标签,$('#ddd').attr('nick').$('#ddd').prop('nick')分别会取得什么值? ...

  3. jQuery.fn.attr与jQuery.fn.prop

    jQuery.fn.attr与jQuery.fn.prop jQuery.fn.attr.jQuery.fn.prop的区别 假设页面有下面这么个标签,$('#ddd').attr('nick').$ ...

  4. 探索 Reflect.apply 与 Function.prototype.apply 的区别

    探索 Reflect.apply 与 Function.prototype.apply 的区别 众所周知, ES6 新增了一个全局.内建.不可构造的 Reflect 对象,并提供了其下一系列可被拦截的 ...

  5. django(新增model)No migrations to apply.

    django 1.8版本,在models下新建一个class,无法在数据库创建新表的问题: - models.py class HostPwd(models.Model): hostname = mo ...

  6. $.extend() 或 jQuery.extend() 与 $.fn.Xxx 或 jQuery.fn.extend(object) 之jQuery插件开发

    jQuery为开发插件提拱了两个方法 语法现象1:$.extend() 或 jQuery.extend() 或 jQuery.extend(object)//可以理解为为jQuery类添加类方法或静态 ...

  7. 【JavaScript】JQuery中$.fn、$.extend、$.fn.extend

    Web开发肯定要使用第三方插件,对于一个炫丽的效果都忍不住想看看对方是如何实现的,刚下载了一个仿京东商品鼠标经过时局部放大的插件.看了两眼JQuery源码,看看就感觉一头雾水.JQuery本来自己学的 ...

  8. jQuery属性--html([val|fn])、text([val|fn])和val([val|fn|arr])

    html([val|fn]) 概述 取得第一个匹配元素的html内容,这个函数不能用于XML文档.但可以用于XHTML文档. 在一个 HTML 文档中, 我们可以使用 .html() 方法来获取任意一 ...

  9. angularJS $watch $apply $digest

    看O'Reilly的书看到$watch这部分,不过没看懂,网上很多资料也含糊不清,不过还是找到了几个好的,简单记录一下. 一句话说明,$watch是用来监视变量的,好了直接上代码 <html&g ...

随机推荐

  1. JavaScript遍历表单元素

    运行效果: 源代码: 1 <!DOCTYPE html> 2 <html lang="zh"> 3 <head> 4 <meta char ...

  2. 将子分支代码merge到主分支master分支

    1.首先切换到子分支: git checkout develop2.使用git pull 把分支代码pull下来: git pull3.切换到主分支: git checkout master4.把分支 ...

  3. TypeScript学习文档-基础篇(完结)

    目录 TypeScript学习第一章:TypeScript初识 1.1 TypeScript学习初见 1.2 TypeScript介绍 1.3 JS .TS 和 ES之间的关系 1.4 TS的竞争者有 ...

  4. (ICONIP2021)On the Unreasonable Effectiveness of Centroids in Image

    目录 摘要 1.引言 2.提出的方法 2.1 CentroidTripletloss 2.2 聚合表示 3.实验 3.1 数据集 3.2 应用细节 3.3 Fashion检索结果 3.4 行人再识别结 ...

  5. Installing github.com/mdempsky/gocode FAILED ----vscode安装go插件中的一些坑

    问题前景: 最近在使用vscode,编写一些go的代码,但发现调试的时候,会需要安装很多插件,但通过vscode之间安装的话,会出现如下的错误: Installing github.com/mdemp ...

  6. docker入门_image、container相关命令

    docker入门_image.container相关命令 镜像仓库服务.镜像仓库.镜像相关概念 镜像仓库服务:docker镜像仓库服务.阿里云镜像服务 镜像仓库:docker镜像仓库服务中会有很多仓库 ...

  7. .NET Core(.NET6)中gRPC注册到Consul

    一.简介 上一篇文章介绍了.NET Core 中使用gRPC,在微服务中,我们通常要把服务做成服务注册,服务发现的方式,那么这里来说一下gRPC是如何注册到Consul中的. Consul的安装这里就 ...

  8. Electron结合React和TypeScript进行开发

    目录 结合React+TypeScript进行Electron开发 1. electron基本简介 为什么选择electron? 2. 快速上手 2.1 安装React(template为ts) 2. ...

  9. NLP教程(2) | GloVe及词向量的训练与评估

    作者:韩信子@ShowMeAI 教程地址:http://www.showmeai.tech/tutorials/36 本文地址:http://www.showmeai.tech/article-det ...

  10. 【openstack】cloudkitty组件,入门级安装(快速)

    @ 目录 前言 架构 安装 配置 启动 检索并安装 CloudKitty 的仪表板 前言 什么是CloudKitty? CloudKitty是OpenStack等的评级即服务项目.该项目旨在成为云的退 ...