python
import torch
import torch.nn as nn
import torch.nn.functional as F
from PIL import Image
from torchvision.models import densenet121, DenseNet121_Weights
"""
1. 論文の式(2)のとおりに、DenseNet-BC の密なブロックと遷移層を組む(CIFAR 向けの小さな例)
2. torchvision の学習済み DenseNet-121 で、画像を分類する
"""
class DenseLayer(nn.Module):
"""DenseNet-B の 1 層:BN-ReLU-1×1 畳み込み(4k 枚)-BN-ReLU-3×3 畳み込み(k 枚)"""
def __init__(self, in_ch, growth_rate, drop_rate=0.0):
super().__init__()
self.bottleneck = nn.Sequential(
nn.BatchNorm2d(in_ch), nn.ReLU(inplace=True),
nn.Conv2d(in_ch, 4 * growth_rate, 1, bias=False),
)
self.conv = nn.Sequential(
nn.BatchNorm2d(4 * growth_rate), nn.ReLU(inplace=True),
nn.Conv2d(4 * growth_rate, growth_rate, 3, padding=1, bias=False), # パディング 1 で縦横を保つ
)
self.drop_rate = drop_rate
def forward(self, features): # features:前のすべての層の出力のリスト
x = torch.cat(features, dim=1) # 式(2):[x0, x1, ..., x_{l-1}] をチャネル方向に連結
out = self.conv(self.bottleneck(x))
return F.dropout(out, self.drop_rate, self.training) # train のときだけドロップアウト
class DenseBlock(nn.Module):
def __init__(self, num_layers, in_ch, growth_rate, drop_rate=0.0):
super().__init__()
self.layers = nn.ModuleList(
[DenseLayer(in_ch + i * growth_rate, growth_rate, drop_rate) for i in range(num_layers)])
def forward(self, x):
features = [x]
for layer in self.layers:
features.append(layer(features)) # 各層は k 枚を「全体の状態」に書き足す
return torch.cat(features, dim=1) # 出力は in_ch + num_layers × k 枚
class Transition(nn.Sequential):
"""遷移層:BN-ReLU-1×1 畳み込み(θm 枚に圧縮)-2×2 平均プーリング"""
def __init__(self, in_ch, out_ch):
super().__init__(nn.BatchNorm2d(in_ch), nn.ReLU(inplace=True),
nn.Conv2d(in_ch, out_ch, 1, bias=False), nn.AvgPool2d(2))
class DenseNetBC(nn.Module):
"""CIFAR 向けの DenseNet-BC:3 つの密なブロック(32×32、16×16、8×8)。L=100、k=12 なら各ブロック 16 層"""
def __init__(self, depth=100, growth_rate=12, theta=0.5, num_classes=10, drop_rate=0.0):
super().__init__()
n = (depth - 4) // 6 # ブロックごとの層の数(1 層 = 1×1 と 3×3 の 2 つの畳み込み)
ch = 2 * growth_rate # 最初の畳み込みは 2k チャネル
layers = [nn.Conv2d(3, ch, 3, padding=1, bias=False)]
for i in range(3):
layers.append(DenseBlock(n, ch, growth_rate, drop_rate))
ch += n * growth_rate
if i < 2:
out_ch = int(theta * ch) # 圧縮率 θ
layers.append(Transition(ch, out_ch))
ch = out_ch
layers += [nn.BatchNorm2d(ch), nn.ReLU(inplace=True), nn.AdaptiveAvgPool2d(1)]
self.features = nn.Sequential(*layers)
self.fc = nn.Linear(ch, num_classes)
for m in self.modules(): # He の初期化
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight)
def forward(self, x):
return self.fc(self.features(x).flatten(1))
model = DenseNetBC(depth=100, growth_rate=12)
print(sum(p.numel() for p in model.parameters()) / 1e6, "M") # 論文の Table 2 では 0.8M
optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9, nesterov=True, weight_decay=1e-4)
model.train() # BN はミニバッチの統計を使う
loss = F.cross_entropy(model(torch.randn(4, 3, 32, 32)), torch.randint(0, 10, (4,)))
optimizer.zero_grad()
loss.backward()
optimizer.step()
# --- torchvision の学習済み DenseNet-121(k=32、ブロックの層の数 6・12・24・16)---
weights = DenseNet121_Weights.IMAGENET1K_V1
net = densenet121(weights=weights) # memory_efficient=True で勾配チェックポイントを使い、メモリを減らせる(遅くなる)
net.eval() # BN は学習中に貯めた平均と分散を使う
preprocess = weights.transforms()
image = Image.open("cat.jpg").convert("RGB")
with torch.no_grad():
probs = net(preprocess(image).unsqueeze(0)).softmax(dim=1) # [1, 1000]
print(weights.meta["categories"][probs.argmax().item()])