1. 定義殘差塊 (Residual Block)
import torch.nn as nn
class ResidualBlock(nn.Module):
    def __init__(self, in_channels, out_channels, stride=1):
        super(ResidualBlock, self).__init__()
        self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1)
        self.bn1 = nn.BatchNorm2d(out_channels)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1)
        self.bn2 = nn.BatchNorm2d(out_channels)
        if stride != 1 or in_channels != out_channels:
            self.shortcut = nn.Sequential(
                nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride),
                nn.BatchNorm2d(out_channels)
            )
        else:
            self.shortcut = nn.Identity()
    def forward(self, x):
        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)
        out = self.conv2(out)
        out = self.bn2(out)
        out += self.shortcut(x)
        out = self.relu(out)
        return out
接下來,修改 UNetGenerator 類別,在第 3 層和第 5 層之後添加殘差塊。找到 UNetGenerator 的定義,並在 forward 函數中加入以下程式碼:
Python
# ... (其他程式碼)
x1 = self.down1(x)
x2 = self.down2(x1)
x3 = self.down3(x2)
x3 = self.res_block3(x3) # 在第 3 層之後加入殘差塊
x4 = self.down4(x3)
x5 = self.down5(x4)
x5 = self.res_block5(x5) # 在第 5 層之後加入殘差塊
# ... (其他程式碼)
記得在 UNetGenerator 的 __init__ 函數中初始化殘差塊:
Python
class UNetGenerator(nn.Module):
    def __init__(self, in_channels, out_channels):
        super(UNetGenerator, self).__init__()
        # ... (其他程式碼)
        self.res_block3 = ResidualBlock(256, 256) # 假設第 3 層的輸出通道數為 256
        self.res_block5 = ResidualBlock(512, 512) # 假設第 5 層的輸出通道數為 512
        # ... (其他程式碼)
3. 調整通道數
請確保殘差塊的輸入和輸出通道數與相應層的通道數匹配。
4. 訓練模型
完成以上修改後,重新訓練你的模型。你可能需要調整一些超參數,例如學習率,以獲得最佳效果。
注意事項
- 增加殘差塊可能會增加模型的計算複雜度和記憶體使用量。
- 殘差塊的位置和數量可以根據你的需求進行調整。
- 除了基本的殘差塊,你也可以嘗試其他變體,例如 bottleneck 殘差塊。
