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

如何在全连接层后应用组归一化?假设全连接层的输出是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个组,如图所示。

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

当输入张量是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')

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注