Pytorch 缓解过拟合和网络退化

一 添加BN模块

BN模块应该添加 激活层前面

在模型实例化后,我们需要对BN层进行初始化。PyTorch中的BN层是通过nn.BatchNorm1d或nn.BatchNorm2d类来实现的。

bn = nn.BatchNorm1d(20) #

对于1D输入数据,使用nn.BatchNorm1d;对于2D输入数据,使用nn.BatchNorm2d

在模型的前向传播过程中,我们需要将BN层应用到适当的位置。以全连接层为例,我们需要在全连接层的输出之后调用BN层。

python 复制代码
class MyModel(nn.Module):
    def __init__(self):
        super(MyModel, self).__init__()
        self.fc1 = nn.Linear(10, 20)
        self.bn = nn.BatchNorm1d(20)
        self.fc2 = nn.Linear(20, 30)
        self.fc3 = nn.Linear(30, 2)

    def forward(self, x):
        x = self.fc1(x)
        x = self.bn(x)
        x = self.fc2(x)
        x = self.fc3(x)
        return x

二 添加残差连接

最主要的是需要注意输入参数的维度是否一致

python 复制代码
import torch
import torch.nn as nn

class ResidualBlock(nn.Module):
    def __init__(self, input_size, hidden_size):
        super(ResidualBlock, self).__init__()
        self.fc1 = nn.Linear(input_size, hidden_size)
        self.fc2 = nn.Linear(hidden_size, input_size)
        self.relu = nn.ReLU()
        
    def forward(self, x):
        residual = x
        out = self.fc1(x)
        out = self.relu(out)
        out = self.fc2(out)
        out += residual
        out = self.relu(out)
        return out
-----------------------------------
©著作权归作者所有:来自51CTO博客作者mob649e8166c3a5的原创作品,请联系作者获取转载授权,否则将追究法律责任
pytorch 全链接层设置残差模块
https://blog.51cto.com/u_16175510/6892589

1、Pytorch搭建残差网络

2、

相关推荐
阿里云大数据AI技术28 分钟前
从“重复造轮”到“自主交付”---万物云 DataWorks Data Agent 落地实践实录
人工智能·agent
掘金安东尼30 分钟前
智能体时代的预填充,为什么适合用流水线并行(Inferact 全文转译)
人工智能·agent
阿enna44 分钟前
检测指标入门:IoU、Precision、Recall与mAP
人工智能·深度学习·算法·yolo·目标检测·计算机视觉·cnn
掘金安东尼1 小时前
Google Antigravity 和 Gemini Neon:哪些行为会封号,怎么降低风险(Flavio Copes 全文转译)
人工智能·google·gemini
kaixin_啊啊1 小时前
【零基础学AI】第 35 章——添加网页界面并部署
人工智能
程序员cxuan1 小时前
绝了,WorkBuddy 可以打通微信了
人工智能·后端·程序员
程序员cxuan1 小时前
再见了反重力,Google 又来搞事了
人工智能·后端·程序员
阿里云大数据AI技术2 小时前
阿里云灵骏真武超节点 Day0 适配星辰大模型 Xing4.1-Preview
人工智能
阿里云大数据AI技术2 小时前
EMR Serverless Ray 正式发布一站式具身智能数据处理平台
人工智能
专注仿真2 小时前
仿真智能体训练:强化学习多目标奖励算法与实战
python·算法·强化学习·afsim智能体