如何在全连接层之后应用组规范化?假设全连接层的输出为1024.分组归一化层使用16组。
self.gn1 = nn.GroupNorm(16, hidden_size)
h1 = F.relu(self.gn1(self.fc1(x))))我说的对吗?如果将组规范化应用于全连接层的输出,我们应该如何理解它?
发布于 2021-07-12 15:46:05
您的代码是正确的,但是让我们看看在一个小示例中发生了什么。
完全连接层的输出通常是二维张量,形状为(batch_size, hidden_size),所以我将重点讨论这类输入,但请记住,GroupNorm支持任意维数的张量。事实上,GroupNorm总是在张量的最后一个维上工作。
GroupNorm将批处理中的所有样本视为独立的,它从张量的最后一个维度创建n_groups,从图像中可以看到这一点。

当输入张量为2D时,图像中的立方体由于没有三维垂直维数而变成正方形,因此在实际应用中,归一化是在输入矩阵的连续行的固定大小的连续段上进行的。
让我们看一个有一些代码的例子。
import torch
import torch.nn as nn
batch_size = 2
hidden_size = 32
n_groups = 8
group_size = hidden_size // n_groups # = 4
# Input tensor that can be the result of a fully-connected layer
x = torch.rand(batch_size, hidden_size)
# GroupNorm with affine disabled to simplify the inspection of results
gn1 = nn.GroupNorm(n_groups, hidden_size, affine=False)
r = gn1(x)
# The rows are split into n_groups (8) groups of size group_size (4)
# and the normalization is applied to these pieces of rows.
# We can check it for the first group x[0, :group_size] with the following code
first_group = x[0, :group_size]
normalized_first_group = (first_group - first_group.mean())/torch.sqrt(first_group.var(unbiased=False) + gn1.eps)
print(r[0, :4])
print(normalized_first_group)
if(torch.allclose(r[0, :4], normalized_first_group)):
print('The result on the first group is the expected one')https://stackoverflow.com/questions/68286001
复制相似问题