python
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
'''
CIFAR-10 の画像分類(Cutout で学習する)
'''
# ハイパーパラメータ
batch_size = 128 # バッチサイズ
epochs = 5 # エポック数
learning_rate = 1e-3 # 学習率
length = 16 # 正方形の一辺(論文の CIFAR-10 の設定。CIFAR-100 は 8)
# cudaを使えるなら'cuda', Apple Siliconなら'mps', それ以外なら'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
class Cutout:
# 論文の公式実装(uoguelph-mlrg/Cutout)と同じ処理。
# 中心を画像の中から一様に選び、はみ出した部分は切り捨てる(画像の中に収まるようにずらさない)
def __init__(self, length, n_holes=1):
self.length = length
self.n_holes = n_holes
def __call__(self, img): # img: 正規化したあとの [C, H, W] のテンソル
h, w = img.size(1), img.size(2)
mask = torch.ones(h, w)
for _ in range(self.n_holes):
cy, cx = np.random.randint(h), np.random.randint(w)
y1, y2 = np.clip(cy - self.length // 2, 0, h), np.clip(cy + self.length // 2, 0, h)
x1, x2 = np.clip(cx - self.length // 2, 0, w), np.clip(cx + self.length // 2, 0, w)
mask[y1:y2, x1:x2] = 0.0
return img * mask # ラベルは変えない
mean, std = (0.4914, 0.4822, 0.4465), (0.2470, 0.2435, 0.2616)
train_transform = transforms.Compose([
transforms.RandomCrop(32, padding=4), # いつものデータ拡張(切り抜き・左右反転)
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean, std), # 先に平均 0 に正規化する(0 で塗る=平均の色で塗る)
Cutout(length=length), # 正規化のあとにかける
# torchvision の RandomErasing で近いことをする場合(四角形は必ず画像の中に収まる点が論文と違う):
# transforms.RandomErasing(p=1.0, scale=(0.25, 0.25), ratio=(1.0, 1.0), value=0),
# p:かける確率(初期値 0.5)、scale:画像の面積に対する割合(16×16 / 32×32 = 0.25)、
# ratio:縦横比の範囲(1 で正方形)、value:塗る値。テンソルにしか使えないので ToTensor のあとに置く
])
test_transform = transforms.Compose([ # 評価では Cutout を使わない
transforms.ToTensor(),
transforms.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)
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().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# 学習:Cutout はデータの読み込みの中でかかる。ラベルはそのまま使う
for epoch in range(epochs):
model.train()
for images, labels in train_loader:
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}%")