1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
| class LANet(nn.Module): """ 通道注意力模块 (Local Attention Network) 强调通道维度的重要性 """ def __init__(self, in_channels: int, reduction: int = 16): super().__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.max_pool = nn.AdaptiveMaxPool2d(1) self.fc = nn.Sequential( nn.Linear(in_channels, in_channels // reduction), nn.ReLU(), nn.Linear(in_channels // reduction, in_channels), nn.Sigmoid() ) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x: 输入特征, shape=(B, C, H, W) Returns: channel_attended: 通道注意力加权特征 """ B, C, _, _ = x.shape avg_out = self.avg_pool(x).view(B, C) avg_out = self.fc(avg_out) max_out = self.max_pool(x).view(B, C) max_out = self.fc(max_out) channel_weights = torch.sigmoid(avg_out + max_out).view(B, C, 1, 1) return x * channel_weights
class SENet(nn.Module): """ 空间注意力模块 (Spatial Enhancement Network) 强调空间位置的重要性 """ def __init__(self, kernel_size: int = 7): super().__init__() self.conv = nn.Sequential( nn.Conv2d(2, 1, kernel_size, padding=kernel_size // 2), nn.Sigmoid() ) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x: 输入特征, shape=(B, C, H, W) Returns: spatial_attended: 空间注意力加权特征 """ avg_out = torch.mean(x, dim=1, keepdim=True) max_out, _ = torch.max(x, dim=1, keepdim=True) concat = torch.cat([avg_out, max_out], dim=1) spatial_weights = self.conv(concat) return x * spatial_weights
class LASENet(nn.Module): """ LASE-Net: 空间-通道注意力融合模块 结合 LANet 和 SENet 的优势 """ def __init__( self, in_channels: int, reduction: int = 16, kernel_size: int = 7 ): super().__init__() self.lanet = LANet(in_channels, reduction) self.senet = SENet(kernel_size) self.fusion = nn.Conv2d(in_channels * 2, in_channels, 1) def forward(self, x: torch.Tensor) -> torch.Tensor: """ 前向传播 Args: x: 输入特征, shape=(B, C, H, W) Returns: fused: 融合特征 """ channel_attended = self.lanet(x) spatial_attended = self.senet(x) concat = torch.cat([channel_attended, spatial_attended], dim=1) fused = self.fusion(concat) return fused + x
if __name__ == "__main__": lase_net = LASENet(512) x = torch.randn(4, 512, 7, 7) output = lase_net(x) print(f"输入形状: {x.shape}") print(f"输出形状: {output.shape}")
|