PyTorch torch.nn.InstanceNorm2d Funktion
PyTorch torch.nn Referenzhandbuch
torch.nn.InstanceNorm2dEs ist das Instanznormalisierungsmodul in PyTorch.
Es normalisiert jeden Kanal jedes Samples unabhängig und wird häufig beim Style Transfer verwendet.
Funktionsdefinition
torch.nn.InstanceNorm2d(num_features, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)
Parameters
num_features: Anzahl der Kanäleaffine: ob lernbare Parameter verwendet werden
Anwendungsbeispiele
Beispiel 1: Grundlegende Verwendung
Beispiel
import torch
import torch.nn as nn
inorm = nn.InstanceNorm2d(64)
# Eingabe
x = torch.randn(4, 64, 16, 16)
output = inorm(x)
print("Eingabe:", x.shape, "-> Ausgabe:", output.shape)
import torch.nn as nn
inorm = nn.InstanceNorm2d(64)
# Eingabe
x = torch.randn(4, 64, 16, 16)
output = inorm(x)
print("Eingabe:", x.shape, "-> Ausgabe:", output.shape)
Beispiel 2: Style Transfer
Beispiel
import torch
import torch.nn as nn
# Style-Transfer-Netzwerke verwenden häufig 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("Eingabe:", x.shape, "-> Ausgabe:", output.shape)
import torch.nn as nn
# Style-Transfer-Netzwerke verwenden häufig 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("Eingabe:", x.shape, "-> Ausgabe:", output.shape)
Beispiel 3: Vergleich mit BatchNorm
Beispiel
import torch
import torch.nn as nn
bn = nn.BatchNorm2d(32)
inorm = nn.InstanceNorm2d(32)
x = torch.randn(4, 32, 8, 8)
print("BatchNorm Mittelwert:", bn(x).mean(dim=(0, 2, 3))[:5].tolist())
print("InstanceNorm Mittelwert:", inorm(x).mean(dim=(0, 2, 3))[:5].tolist())
import torch.nn as nn
bn = nn.BatchNorm2d(32)
inorm = nn.InstanceNorm2d(32)
x = torch.randn(4, 32, 8, 8)
print("BatchNorm Mittelwert:", bn(x).mean(dim=(0, 2, 3))[:5].tolist())
print("InstanceNorm Mittelwert:", inorm(x).mean(dim=(0, 2, 3))[:5].tolist())
Anwendungsfälle
- Stilübertragung: NIN、AdaIN
- Textursynthese
- Kleiner Batch: geeignet für batch=1
Hinweis: Standardmäßig affine=False, enthält keine lernbaren Parameter.
Andere Erweiterungen