PyTorch torch.nn.InstanceNorm2d 関数

PyTorch torch.nn 参考手册PyTorch torch.nn リファレンスマニュアル


torch.nn.InstanceNorm2dこれはPyTorchのインスタンス正規化モジュールです。

各サンプルの各チャンネルを独立に正規化し、スタイル転送でよく使用されます。

関数定義

torch.nn.InstanceNorm2d(num_features, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)

パラメータ

  • num_features: チャンネル数
  • affine: 学習可能なパラメータを使用するかどうか

使用例

例1: 基本的な使い方

実例

import torch
import torch.nn as nn

inorm = nn.InstanceNorm2d(64)

# 入力
x = torch.randn(4, 64, 16, 16)
output = inorm(x)

print("入力:", x.shape, "-> 出力:", output.shape)

例2: スタイル転送

実例

import torch
import torch.nn as nn

# スタイル転送ネットワークではInstanceNormをよく使用
class StyleNet(nn.Module):
    def __init__(self):
        super(StyleNet, self).__init__()
        self.conv1 = nn.Conv2d(3, 32, 3, padding=1)
        self.in1 = nn.InstanceNorm2d(32)
        self.conv2 = nn.Conv2d(32, 64, 3, padding=1)
        self.in2 = nn.InstanceNorm2d(64)

    def forward(self, x):
        x = self.conv1(x)
        x = self.in1(x)
        x = torch.relu(x)
        x = self.conv2(x)
        x = self.in2(x)
        return x

net = StyleNet()
x = torch.randn(1, 3, 256, 256)
output = net(x)

print("入力:", x.shape, "-> 出力:", output.shape)

例3: BatchNormとの比較

実例

import torch
import torch.nn as nn

bn = nn.BatchNorm2d(32)
inorm = nn.InstanceNorm2d(32)

x = torch.randn(4, 32, 8, 8)

print("BatchNorm mean:", bn(x).mean(dim=(0, 2, 3))[:5].tolist())
print("InstanceNorm mean:", inorm(x).mean(dim=(0, 2, 3))[:5].tolist())

使用シーン

  • スタイル転送: NIN、AdaIN
  • テクスチャ合成
  • 小さいバッチ: batch=1に適している

注意:デフォルトではaffine=Falseで、学習可能なパラメータは含まれません。


PyTorch torch.nn 参考手册PyTorch torch.nn リファレンスマニュアル

その他の拡張