在使用 InstanceNorm2d 情況下, 遇到 down_x shape torch.Size([16, 512, 1, 1]) 時, 可以輸出submodule: torch.Size([16, 1024, 2, 2]) 的結果?

如果你希望將 down_x[16, 512, 1, 1] 轉換成 [16, 1024, 2, 2],你需要使用 卷積層 (Conv2d) 或 反池化層 (ConvTranspose2d) 來改變通道數和空間尺寸,同時保持 InstanceNorm2d 的應用。


解決方案

  1. 使用 nn.Conv2d 增加通道數
  2. 使用 nn.Upsamplenn.ConvTranspose2d 擴大空間尺寸
  3. 使用 InstanceNorm2d 正規化

方法 1:使用 Conv2d + Upsample

你可以先使用 Conv2d 改變通道數,然後用 Upsample 調整空間大小:

import torch
import torch.nn as nn

class MyModel(nn.Module):
    def __init__(self):
        super(MyModel, self).__init__()
        self.conv = nn.Conv2d(512, 1024, kernel_size=3, stride=1, padding=1)
        self.norm = nn.InstanceNorm2d(1024, affine=True)  # InstanceNorm2d 需要對應通道數
        self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)

    def forward(self, x):
        print(f"Before Conv: {x.shape}")  # torch.Size([16, 512, 1, 1])
        x = self.conv(x)
        x = self.norm(x)
        x = self.upsample(x)
        print(f"After Conv + Upsample: {x.shape}")  # torch.Size([16, 1024, 2, 2])
        return x

# 測試
x = torch.randn(16, 512, 1, 1)
model = MyModel()
output = model(x)

方法 2:使用 ConvTranspose2d

如果你希望更直接地進行升尺度 (upsampling),你可以用 轉置卷積 (deconvolution) 來實現:

class MyModel(nn.Module):
    def __init__(self):
        super(MyModel, self).__init__()
        self.conv_transpose = nn.ConvTranspose2d(512, 1024, kernel_size=2, stride=2)
        self.norm = nn.InstanceNorm2d(1024, affine=True)

    def forward(self, x):
        print(f"Before ConvTranspose: {x.shape}")  # torch.Size([16, 512, 1, 1])
        x = self.conv_transpose(x)
        x = self.norm(x)
        print(f"After ConvTranspose: {x.shape}")  # torch.Size([16, 1024, 2, 2])
        return x

# 測試
x = torch.randn(16, 512, 1, 1)
model = MyModel()
output = model(x)

哪種方法比較好?

  • 如果你想要更平滑的結果 → 用 方法 1 (Conv2d + Upsample)
  • 如果你想讓模型學習擴展方式 → 用 方法 2 (ConvTranspose2d)

這兩種方式都能達到 down_x: torch.Size([16, 1024, 2, 2]) 的結果,你可以選擇最適合你的需求!🚀

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *