python
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets
from torchvision.transforms import v2
from torch.utils.data import DataLoader
'''
CIFAR-10 の画像分類(CutMix で学習する)
'''
# ハイパーパラメータ
batch_size = 128 # バッチサイズ
epochs = 5 # エポック数
learning_rate = 1e-3 # 学習率
alpha = 1.0 # Beta(α, α) の α(論文はすべての実験で 1)
num_classes = 10
# cudaを使えるなら'cuda', Apple Siliconなら'mps', それ以外なら'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
mean, std = (0.4914, 0.4822, 0.4465), (0.2470, 0.2435, 0.2616)
train_transform = v2.Compose([ # 1 枚ずつのデータ拡張(CutMix はここに入れない)
v2.RandomCrop(32, padding=4),
v2.RandomHorizontalFlip(),
v2.ToImage(),
v2.ToDtype(torch.float32, scale=True),
v2.Normalize(mean, std),
])
test_transform = v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True), v2.Normalize(mean, std)])
train_dataset = datasets.CIFAR10(root='./data', train=True, download=True, transform=train_transform)
test_dataset = datasets.CIFAR10(root='./data', train=False, download=True, transform=test_transform)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True) # 相手は隣の画像なので並びを混ぜる
test_loader = DataLoader(test_dataset, batch_size=batch_size)
# torchvision の CutMix:ミニバッチにかける。クラス番号のラベルなら num_classes が必須
# 出力のラベルは (バッチ, num_classes) の確率になる。かける確率の引数はない(毎回かかる)
cutmix = v2.CutMix(alpha=alpha, num_classes=num_classes)
# Mixup と半々で使うなら:mix = v2.RandomChoice([v2.CutMix(num_classes=num_classes), v2.MixUp(num_classes=num_classes)])
def cutmix_manual(x, y, alpha):
# 論文の Algorithm A1 と同じ処理(参考)。y はクラス番号
lam = float(np.random.beta(alpha, alpha))
index = torch.randperm(x.size(0), device=x.device) # 並べ替えて相手を選ぶ
H, W = x.size(2), x.size(3)
rx, ry = np.random.randint(W), np.random.randint(H) # 箱の中心は一様
rw, rh = int(W * np.sqrt(1 - lam)), int(H * np.sqrt(1 - lam)) # 面積は 1 - λ
x1, x2 = np.clip(rx - rw // 2, 0, W), np.clip(rx + rw // 2, 0, W)
y1, y2 = np.clip(ry - rh // 2, 0, H), np.clip(ry + rh // 2, 0, H)
x = x.clone()
x[:, :, y1:y2, x1:x2] = x[index, :, y1:y2, x1:x2] # 箱の中を相手の画像で置き換える
lam = 1 - (x2 - x1) * (y2 - y1) / (W * H) # はみ出した分を除いた実際の面積で λ を直す
return x, y, y[index], lam # 損失は lam * CE(out, y) + (1 - lam) * CE(out, y[index])
class SmallCNN(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 32, kernel_size=3, padding=1), # [B, 3, 32, 32] -> [B, 32, 32, 32]
nn.BatchNorm2d(32),
nn.ReLU(),
nn.MaxPool2d(2), # -> [B, 32, 16, 16]
nn.Conv2d(32, 64, kernel_size=3, padding=1), # -> [B, 64, 16, 16]
nn.BatchNorm2d(64),
nn.ReLU(),
nn.MaxPool2d(2), # -> [B, 64, 8, 8]
nn.Flatten(),
)
self.classifier = nn.Linear(64 * 8 * 8, num_classes)
def forward(self, x):
return self.classifier(self.features(x))
model = SmallCNN(num_classes).to(device)
criterion = nn.CrossEntropyLoss() # 確率の形のラベル (B, num_classes) もそのまま受け取れる
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# 学習:ミニバッチを作ってから CutMix をかける
for epoch in range(epochs):
model.train()
for images, labels in train_loader:
images, labels = cutmix(images, labels) # labels: (B,) -> (B, num_classes) の確率
images, labels = images.to(device), labels.to(device)
loss = criterion(model(images), labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 評価:貼り替えずに、元の画像で確かめる
model.eval()
correct = 0
total = 0
with torch.no_grad():
for images, labels in test_loader:
images, labels = images.to(device), labels.to(device)
predicted = model(images).argmax(dim=1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print(f"Test Accuracy: {100 * correct / total:.2f}%")