gpt4 book ai didi

python - 如何在全连接层之后应用组归一化?

转载 作者:行者123 更新时间:2023-12-04 13:08:28 25 4
gpt4 key购买 nike

如何在全连接层之后应用组归一化?假设全连接层的输出是 1024。组归一化层使用 16 个组。

self.gn1 = nn.GroupNorm(16, hidden_size)
h1 = F.relu(self.gn1(self.fc1(x))))

我说的对吗?如果将组归一化应用于全连接层的输出,我们应该如何理解?

最佳答案

您的代码是正确的,但让我们看看在一个小示例中会发生什么。

全连接层的输出通常是形状为 (batch_size, hidden_​​size) 的二维张量,所以我将重点关注这种输入,但请记住 GroupNorm 支持具有任意维数的张量。事实上,GroupNorm 始终在张量的最后一个维度上工作。

GroupNorm 将批处理中的所有样本视为独立的,并从张量的最后一个维度创建 n_groups,如您从图像中看到的那样。

GroupNorm on a (N, W, H, C) tensor

当输入张量为二维时,图像中的立方体变为正方形,因为没有第三个垂直维度,因此实际上归一化是对输入矩阵的固定大小的连续行片段执行的。

让我们看一个带有一些代码的示例。

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

关于python - 如何在全连接层之后应用组归一化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68286001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com