Pytorch model.apply/net.apply

Pytorch model.apply/net.apply

net.apply(fn: Callable[[ForwardRef(‘Module’)], NoneType]) -> ~T

  • 介绍:Pytorch 中的 model.apply(fn) 会递归地将函数 fn 应用到父模块的每个子模块以及model这个父模块自身。通常用于初始化模型的参数
  • 参数:fn (:class:`Module` -> None)->将应用于每个子模块的函数
  • 返回:Module: self

示例1:

来看以下示例:

@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)

在这个网络示例中,模块 net 有两个子模块,均为 Linear(2,4)。函数首先对这两个子模块调用 init_weights 函数,然后再对 net 模块进行同样的操作
会打印以下信息:
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)
)

可以看见的使,不仅仅分别打印两个Linear,还加上父模块自身自己父模块的返回Sequential。

示例2

或者下面这个例子:

net = nn.Sequential(nn.Flatten(), 
                    nn.Linear(784, 256),
                    nn.ReLU(), 
                    nn.Linear(256, 10))
def init_weights(m):
    print(m)
        
net.apply(init_weights)

会打印以下信息:
Flatten(start_dim=1, end_dim=-1)
Linear(in_features=784, out_features=256, bias=True)
ReLU()
Linear(in_features=256, out_features=10, bias=True)
Sequential(
   (0): Flatten(start_dim=1, end_dim=-1)
   (1): Linear(in_features=784, out_features=256, bias=True)
   (2): ReLU()
   (3): Linear(in_features=256, out_features=10, bias=True)
)

示例3

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

net = nn.Sequential(nn.Flatten(), 
                    nn.Linear(784, 256),
                    nn.ReLU(), 
                    nn.Linear(256, 10))
def init_weights(m):
    if type(m) == nn.Linear:
        nn.init.normal_(m.weight, std=0.01)
        
net.apply(init_weights)
  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
/home/dss/Code/7_20/Condition_DDPM_7_20.py:14: DeprecationWarning: Please use `rotate` from the `scipy.ndimage` namespace, the `scipy.ndimage.interpolation` namespace is deprecated. from scipy.ndimage.interpolation import rotate Traceback (most recent call last): File "/home/dss/Code/7_20/Condition_DDPM_7_20.py", line 509, in <module> ddpm = DDPM(device, beta_1, beta_T, T, drop_prob=0.1) File "/home/dss/Code/7_20/Condition_DDPM_7_20.py", line 309, in __init__ self.model = UNet(T).to(device) File "/home/dss/.conda/envs/DSS_env/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1145, in to return self._apply(convert) File "/home/dss/.conda/envs/DSS_env/lib/python3.9/site-packages/torch/nn/modules/module.py", line 797, in _apply module._apply(fn) File "/home/dss/.conda/envs/DSS_env/lib/python3.9/site-packages/torch/nn/modules/module.py", line 797, in _apply module._apply(fn) File "/home/dss/.conda/envs/DSS_env/lib/python3.9/site-packages/torch/nn/modules/module.py", line 797, in _apply module._apply(fn) File "/home/dss/.conda/envs/DSS_env/lib/python3.9/site-packages/torch/nn/modules/module.py", line 820, in _apply param_applied = fn(param) File "/home/dss/.conda/envs/DSS_env/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1143, in convert return t.to(device, dtype if t.is_floating_point() or t.is_complex() else None, non_blocking) File "/home/dss/.conda/envs/DSS_env/lib/python3.9/site-packages/torch/cuda/__init__.py", line 239, in _lazy_init raise AssertionError("Torch not compiled with CUDA enabled") AssertionError: Torch not compiled with CUDA enabled
07-21

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

泠山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值