解决RuntimeError: running_mean should contain 36864 elements not 4096

简介: 一般在卷积层Conv2d后添加正则化BNBatchNormal,使得数据在relu激活前不会因为数据过大而导致网络不稳定,而我在代码中BatchNorm2d的输入通道数与前一层Conv2d的输出通道数不一致,导致报这个错,两者修改一直即可(这里修改为36864即可)。

一、问题描述

在模型微调最后2层时,BatchNorm1d如题报错。

def get_model():
    model_pre = models.resnet50(pretrained=True) # 获取预训练模型
    # 冻结预训练模型中所有参数
    for param in model_pre.parameters():
        param.requires_grad = False
    # 替换ResNet最后的两层网络,返回一个新的模型(迁移学习)
    model_pre.avgpool = AdaptiveConcatPool2d() # 池化层替换
    model_pre.fc = nn.Sequential(
            nn.Flatten(), # 所有维度拉平
            # nn.BatchNorm1d(4096), # 正则化处理
            nn.BatchNorm1d(36864), # 正则化处理
            nn.Dropout(0.5), # 丢掉神经元
            # nn.Linear(4096, 512), # 线性层处理
            nn.Linear(36864, 512), # 线性层处理
            nn.ReLU(), # 激活函数
            nn.BatchNorm1d(512), # 正则化处理
            nn.Dropout(p=0.5), # 丢掉神经元
            nn.Linear(512, 2), # 线性层
            nn.LogSoftmax(dim=1) # 损失函数
    )
    return model_pre
torch.nn.Conv2d(in_channels, out_channels, kernel_size, 
stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros')

二、解决方法

一般在卷积层Conv2d后添加正则化BNBatchNormal,使得数据在relu激活前不会因为数据过大而导致网络不稳定,而我在代码中BatchNorm2d的输入通道数与前一层Conv2d的输出通道数不一致,导致报这个错,两者修改一直即可(这里修改为36864即可)。


相关文章
|
6月前
(145) Table ‘./addon_collect_wukong_spider‘ is marked as crashed and should be repaired解决思路
(145) Table ‘./addon_collect_wukong_spider‘ is marked as crashed and should be repaired解决思路
26 0
|
7月前
|
自然语言处理 数据库
Expected one result (or null) to be returned by selectOne(), but found: 2
Expected one result (or null) to be returned by selectOne(), but found: 2
101 0
|
Java Go API
译|Don’t just check errors, handle them gracefully(二)
译|Don’t just check errors, handle them gracefully(二)
100 0
|
程序员 Go API
译|Don’t just check errors, handle them gracefully(一)
译|Don’t just check errors, handle them gracefully
83 0
|
Java Maven
An attempt was made to call a method that does not exist. The attempt was made from the following
An attempt was made to call a method that does not exist. The attempt was made from the following
472 0
|
PyTorch 算法框架/工具 Python
RuntimeError: Integer division of tensors using div or / is no longer supported, and in a future rel
RuntimeError: Integer division of tensors using div or / is no longer supported, and in a future rel
116 0
|
数据库
Incorrect result size: expected 1, actual 2
Incorrect result size: expected 1, actual 2
914 0
|
JavaScript 安全 前端开发
What Is ElectronJS and Why Should You Use It?
In this three-part tutorial, we will explore how to create a fully functional invoice application using ElectronJS and ApsaraDB for MongoDB.
2663 0
What Is ElectronJS and Why Should You Use It?
|
Java Apache
Failed to place enough replicas
如果DataNode的dfs.datanode.data.dir全配置成SSD类型,则执行“hdfs dfs -put /etc/hosts hdfs:///tmp/”时会报如下错误: 2017-05-04 16:08:22,545 WARN org.
3315 0