我在pytorch
有一个CNN,我需要在每次迭代中用L2范数规范化卷积权重(滤波器)。最有效的方法是什么?
基本上,在我的特定实验中,我需要用模型中的标准化值替换过滤器(在训练和测试期间)。
我不确定我是否正确理解了你的问题。但是如果我被要求在每次迭代时标准化NN层的权重,我会做如下的事情。
for ite in range(100): # training iteration
# write your code to train your model
# update the parameters using optimizer.step() and then normalize
with torch.no_grad():
model.conv.weight.div_(torch.norm(model.conv.weight, dim=2, keepdim=True)
这里,model.conv
指的是模型的卷积层。请确保您在dim
函数中适当地给出torch.norm()
参数。我只是将它设置为2给你一个例子。
例如,如果你使用Conv1d
,那么权重参数的形状将是(out_channels, in_channels, kW)
,那么你可以设置dim=2
。
显然,torch.norm()
不够快。
import torch
x = torch.randn(1024,100)
y = torch.randn(1024,100)
%timeit torch.sqrt((x - y).pow(2).sum(1))
%timeit torch.norm(x - y, 2, 1)
#outputs
129 µs ± 1.79 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
291 µs ± 17.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
另外,请检查this doc,它可能会让您在模型中使用BatchNorm。