L2 范数归一化(L2 Normalization)是将每个样本(向量)除以其 L2 范数,以使得每个样本的 L2 范数为 1, 这样做可以使得样本在欧几里得空间中位于单元圆上。L2范数(L2 norm),也称为欧几里德范数(Euclidean norm)或2-范数,是向量元素的平方和的平方根。
对于一个 n n n 维向量 x x x,其 L 2 L2 L2 范数计算公式为
∥ x ∥ 2 = ∑ i = 1 n x i 2 \|x\|_2 = \sqrt{\sum_{i=1}^n x_i^2} ∥x∥2=i=1∑nxi2
而 L2 范数归一化就是将向量 x x x 中的每隔元素除以 L 2 L2 L2 范数,即
o u t i = x i ∥ x ∥ 2 out_i = \frac{x_i}{\|x\|_2} outi=∥x∥2xi
class L2Norm(nn.Module):
def __init__(self,n_channels, scale):
super(L2Norm,self).__init__()
self.n_channels = n_channels
self.gamma = scale or None
self.eps = 1e-10
self.weight = nn.Parameter(torch.Tensor(self.n_channels))
self.reset_parameters()
def reset_parameters(self):
init.constant_(self.weight,self.gamma)
def forward(self, x):
norm = x.pow(2).sum(dim=1, keepdim=True).sqrt()+self.eps
#x /= norm
x = torch.div(x,norm)
out = self.weight.unsqueeze(0).unsqueeze(2).unsqueeze(3).expand_as(x) * x
return out 这个 L2 norm 的数学公式是什么