pytorch中的LayerNorm有一个名为normalized_shape
的参数。normalized_shape
:如果使用单个整数,则将其视为单例列表,并且此模块将在最后一个维度上进行规范化,该维度预计具有该特定大小。
因此,它告诉pytorch在哪些维度上进行归一化。
当在pytorch中计算mean或任何其他op时,这样的信息只传递聚合将要发生的维度号,-1表示最后一个维度。如果你传递错误的元素数量,LayerNorm甚至不能应用。那么,为什么要这样设计选择呢?
范例:
from torch import nn
import torch
ln = nn.LayerNorm(3) #only 3 or (2,3) would be accepted
###ln = nn.LayerNorm(1) #fails with runtime error telling you the shape mismatch problem
ln(torch.randn(2,3))
字符串
为什么nn.LayerNorm(across_how_many_last_dimensions)
不是函数的签名?我错过了什么用例,这个参数选择是为了服务?
1条答案
按热度按时间gblwokeq1#
这也困扰了我,我在源代码中找到了答案(
nn.LayerNorm
的init
函数)字符串
如果
elemenetwise_affine
是True
(默认情况下是True
),则normalized_shape
参数需要精确,以便初始化weight
和bias
参数。我不太喜欢这种设计选择,但我不得不承认这比在第一次调用
forward
时计算尺寸要好。