使用LayerNorm报错维度问题不匹配的解决方法

文章讲述了在PyTorch中使用LayerNorm遇到RuntimeError,因为输入形状不符合要求。解决方法是在定义LayerNorm时根据实际输出尺寸扩展维度。给出了两个代码示例,展示了如何适应不同卷积层输出的1x1和3x3区域的LayerNorm操作。
摘要由CSDN通过智能技术生成

使用Layernorm时,出现问题:

RuntimeError: Given normalized_shape=[16], expected input with shape [*, 16], but got input of size[24, 16, 64, 64]

直接在使用时扩展所需的维度即可

nn.LayerNorm([16,64,64])

代码示例:

import torch
import torch.nn as nn

data= torch.Tensor(64, 80, 3,3)
out_w, out_h = 1, 1
out_layer1 = nn.Sequential(
    nn.Conv2d(80, 32,kernel_size=3,groups=2),
    nn.LayerNorm([32,out_w,out_h]),
    nn.Dropout(0.1)
)
out = out_layer1(data)
print(out.shape)

data= torch.Tensor(64, 80, 5,5)
out_w, out_h = 3, 3
out_layer1 = nn.Sequential(
    nn.Conv2d(80, 32,kernel_size=3,groups=2),
    nn.LayerNorm([32,out_w,out_h]),
    nn.Dropout(0.1)
)
out = out_layer1(data)
print(out.shape)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值