python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
"""
論文(LeCun ら 1998)の II.B 節のとおりに組んだ LeNet-5 を、MNIST で学習する例
・活性化関数は 1.7159 × tanh(2/3 × a)
・S2・S4 は「2×2 の和 × 学習できる係数 + バイアス」の後に活性化関数
・C3 は Table I のつなぎ方(S2 の一部の特徴マップだけを使う)
・出力は RBF(F6 の出力と、固定したお手本のベクトルとの二乗距離)。損失は式(9)の MAP 基準
PyTorch に LeNet-5 の組み込みはない
"""
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
# 入力:28×28 を 32×32 に広げ、背景を -0.1、文字を 1.175 にする(ToTensor は背景 0・文字 1)
transform = transforms.Compose([
transforms.Pad(2),
transforms.ToTensor(),
transforms.Lambda(lambda x: x * 1.275 - 0.1),
])
train_loader = DataLoader(datasets.MNIST('./data', train=True, download=True, transform=transform), batch_size=32, shuffle=True)
test_loader = DataLoader(datasets.MNIST('./data', train=False, download=True, transform=transform), batch_size=1000)
def scaled_tanh(a):
return 1.7159 * torch.tanh(2.0 / 3.0 * a) # 式(6)。f(1)=1, f(-1)=-1
class Subsampling(nn.Module):
"""2×2 の 4 つの入力を足し、特徴マップごとの係数をかけてバイアスを足す(パラメータは 2 × 枚数)"""
def __init__(self, channels):
super().__init__()
self.coef = nn.Parameter(torch.ones(1, channels, 1, 1))
self.bias = nn.Parameter(torch.zeros(1, channels, 1, 1))
def forward(self, x):
s = F.avg_pool2d(x, 2) * 4 # 2×2 の和(重なりなし)
return scaled_tanh(s * self.coef + self.bias)
# Table I:C3 の各特徴マップ(列)が使う S2 の特徴マップ
C3_TABLE = [
[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 0], [5, 0, 1],
[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 0], [4, 5, 0, 1], [5, 0, 1, 2],
[0, 1, 3, 4], [1, 2, 4, 5], [0, 2, 3, 5],
[0, 1, 2, 3, 4, 5],
]
class C3(nn.Module):
"""つながっていない入力の重みを 0 に固定した 5×5 の畳み込み(パラメータは 1,516)"""
def __init__(self):
super().__init__()
self.conv = nn.Conv2d(6, 16, 5)
mask = torch.zeros(16, 6, 1, 1)
for out_ch, ins in enumerate(C3_TABLE):
mask[out_ch, ins] = 1
self.register_buffer('mask', mask)
def forward(self, x):
return F.conv2d(x, self.conv.weight * self.mask, self.conv.bias)
class LeNet5(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
self.c1 = nn.Conv2d(1, 6, 5) # 32×32 → 6@28×28
self.s2 = Subsampling(6) # → 6@14×14
self.c3 = C3() # → 16@10×10
self.s4 = Subsampling(16) # → 16@5×5
self.c5 = nn.Conv2d(16, 120, 5) # → 120@1×1
self.f6 = nn.Linear(120, 84)
# RBF のお手本(学習しない)。論文は 7×12 の文字の絵(±1)。ここでは ±1 をランダムに選ぶ
self.register_buffer('prototypes', torch.randint(0, 2, (num_classes, 84)).float() * 2 - 1)
for m in self.modules(): # 付録 A:±2.4 / ファンイン の一様分布
if isinstance(m, (nn.Conv2d, nn.Linear)):
fan_in = m.weight[0].numel()
nn.init.uniform_(m.weight, -2.4 / fan_in, 2.4 / fan_in)
nn.init.zeros_(m.bias)
def forward(self, x):
x = scaled_tanh(self.c1(x))
x = self.s2(x)
x = scaled_tanh(self.c3(x))
x = self.s4(x)
x = scaled_tanh(self.c5(x)).flatten(1)
x = scaled_tanh(self.f6(x)) # [N, 84]
return torch.cdist(x, self.prototypes) ** 2 # 式(7):各クラスのお手本との二乗距離 [N, 10]
def map_loss(y, target, j=1.0):
"""式(9):正解の距離 + log(e^{-j} + Σ e^{-y_i})。j は正の定数(ここでは 1 とした)"""
y_correct = y.gather(1, target[:, None]).squeeze(1)
others = torch.cat([y.new_full((y.size(0), 1), j), y], dim=1)
return (y_correct + torch.logsumexp(-others, dim=1)).mean()
model = LeNet5().to(device)
# 論文は確率的対角レーベンバーグ・マルカート法。ここでは SGD で代える(学習率は論文の値と対応しない)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
for epoch in range(20): # 論文は学習データ全体を 20 回
model.train() # この形にはドロップアウトも BN もないので、train/eval で挙動は変わらない
for images, labels in train_loader:
images, labels = images.to(device), labels.to(device)
loss = map_loss(model(images), labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
model.eval()
correct = 0
with torch.no_grad():
for images, labels in test_loader:
images, labels = images.to(device), labels.to(device)
pred = model(images).argmin(1) # 距離がいちばん小さいクラスが答え
correct += (pred == labels).sum().item()
print(f"Test error: {100 * (1 - correct / len(test_loader.dataset)):.2f}%")