小白程序员必看:AI大模型将如何颠覆你的工作与生活?
2026/10/13 7:00:40
nn.AdaptiveAvgPool2d(1))。reduction_ratio=16),减少计算量并引入非线性。Sigmoid激活函数,输出每个通道的权重(范围 0~1)。x * y),完成特征重标定。# 基础CNN模型classCNN(nn.Module):def__init__(self):super(CNN,self).__init__()self.conv1=nn.Conv2d(3,32,3,padding=1)self.bn1=nn.BatchNorm2d(32)self.relu1=nn.ReLU()self.pool1=nn.MaxPool2d(2,2)self.conv2=nn.Conv2d(32,64,3,padding=1)self.bn2=nn.BatchNorm2d(64)self.relu2=nn.ReLU()self.pool2=nn.MaxPool2d(2)self.conv3=nn.Conv2d(64,128,3,padding=1)self.bn3=nn.BatchNorm2d(128)self.relu3=nn.ReLU()self.pool3=nn.MaxPool2d(2)self.fc1=nn.Linear(128*4*4,512)self.dropout=nn.Dropout(p=0.5)self.fc2=nn.Linear(512,10)defforward(self,x):x=self.pool1(self.relu1(self.bn1(self.conv1(x))))x=self.pool2(self.relu2(self.bn2(self.conv2(x))))x=self.pool3(self.relu3(self.bn3(self.conv3(x))))x=x.view(-1,128*4*4)x=self.fc2(self.dropout(self.relu3(self.fc1(x))))returnx# 通道注意力模块 (SE Block)classChannelAttention(nn.Module):def__init__(self,in_channels,reduction_ratio=16):super(ChannelAttention,self).__init__()self.avg_pool=nn.AdaptiveAvgPool2d(1)self.fc=nn.Sequential(nn.Linear(in_channels,in_channels//reduction_ratio,bias=False),nn.ReLU(inplace=True),nn.Linear(in_channels//reduction_ratio,in_channels,bias=False),nn.Sigmoid())defforward(self,x):b,c,_,_=x.size()y=self.avg_pool(x).view(b,c)y=self.fc(y).view(b,c,1,1)returnx*y# 带通道注意力的CNN模型classCNN_SE(nn.Module):def__init__(self):super(CNN_SE,self).__init__()self.conv1=nn.Conv2d(3,32,3,padding=1)self.bn1=nn.BatchNorm2d(32)self.relu1=nn.ReLU()self.ca1=ChannelAttention(32)self.pool1=nn.MaxPool2d(2,2)self.conv2=nn.Conv2d(32,64,3,padding=1)self.bn2=nn.BatchNorm2d(64)self.relu2=nn.ReLU()self.ca2=ChannelAttention(64)self.pool2=nn.MaxPool2d(2)self.conv3=nn.Conv2d(64,128,3,padding=1)self.bn3=nn.BatchNorm2d(128)self.relu3=nn.ReLU()self.ca3=ChannelAttention(128)self.pool3=nn.MaxPool2d(2)self.fc1=nn.Linear(128*4*4,512)self.dropout=nn.Dropout(p=0.5)self.fc2=nn.Linear(512,10)defforward(self,x):x=self.pool1(self.ca1(self.relu1(self.bn1(self.conv1(x)))))x=self.pool2(self.ca2(self.relu2(self.bn2(self.conv2(x)))))x=self.pool3(self.ca3(self.relu3(self.bn3(self.conv3(x)))))x=x.view(-1,128*4*4)x=self.fc2(self.dropout(self.relu3(self.fc1(x))))returnx代码中定义了两个模型进行对比:
CNN):CNN_SE):ChannelAttention模块。train_and_log函数,统一管理训练循环。Adam优化器和ReduceLROnPlateau学习率调度策略。visualize_feature_maps):visualize_attention_map):通过在卷积神经网络中引入通道注意力机制(SE Block),模型能够以极小的计算代价(少量的参数增加),显式地建模通道间的依赖关系,从而提升特征表示能力。这种机制是即插即用的,可以方便地集成到现有的 CNN 架构中。
@浙大疏锦行
Block),模型能够以极小的计算代价(少量的参数增加),显式地建模通道间的依赖关系,从而提升特征表示能力。这种机制是即插即用的,可以方便地集成到现有的 CNN 架构中。
@浙大疏锦行