栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Pytorch apply函数

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Pytorch apply函数

apply 函数是nn.Module 中实现的, 递归地调用self.children() 去处理自己以及子模块

我们知道pytorch的任何网络net,都是torch.nn.Module的子类,都算是module, 也就是模块。

pytorch中的model.apply(fn)会递归地将函数fn应用到父模块的每个子模块submodule,也包括model这个父模块自身。经常用于初始化init_weights的操作

from torch import nn

@torch.no_grad()
def init_weights(m):
    print(m)
    if type(m) == nn.Linear:
        print(m.weight)
        m.weight.fill_(1.0)
        print(m.weight)

net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))
a = net[0];
net.apply(init_weights)
b = net[0];

'''
Linear(in_features=2, out_features=2, bias=True)
Parameter containing:
tensor([[0.3706, 0.5069],
        [0.3494, 0.2712]], requires_grad=True)
Parameter containing:
tensor([[1., 1.],
        [1., 1.]], requires_grad=True)
Linear(in_features=2, out_features=2, bias=True)
Parameter containing:
tensor([[ 0.3507,  0.2883],
        [-0.2437, -0.4020]], requires_grad=True)
Parameter containing:
tensor([[1., 1.],
        [1., 1.]], requires_grad=True)
Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
)
'''
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/934562.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号