如何在全连接层后应用组归一化?假设全连接层的输出是1024。并且组归一化层使用16个组。
self.gn1 = nn.GroupNorm(16, hidden_size)h1 = F.relu(self.gn1(self.fc1(x))))
我的代码对吗?如果将组归一化应用于全连接层的输出,我们应该如何理解组归一化?
回答:
你的代码是正确的,但让我们通过一个小例子来看看到底发生了什么。
全连接层的输出通常是一个形状为(batch_size, hidden_size)
的2D张量,所以我将重点放在这种输入上,但请记住,GroupNorm
支持任意维度的张量。实际上,GroupNorm
总是对张量的最后一个维度进行操作。
GroupNorm
将批次中的所有样本视为独立的,并从张量的最后一个维度创建n_groups
个组,如图所示。
当输入张量是2D时,图中的立方体变成一个正方形,因为没有第三个垂直维度,所以实际上归一化是在输入矩阵的行的固定大小连续片段上进行的。
让我们通过一些代码来看一个例子。
import torchimport torch.nn as nnbatch_size = 2hidden_size = 32n_groups = 8group_size = hidden_size // n_groups # = 4# Input tensor that can be the result of a fully-connected layerx = torch.rand(batch_size, hidden_size)# GroupNorm with affine disabled to simplify the inspection of resultsgn1 = 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 codefirst_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')