python
import math
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms.functional as TF
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
"""
CIFAR-10 の画像分類(GridMask で学習する)
"""
# ハイパーパラメータ
batch_size = 128 # バッチサイズ
epochs = 10 # エポック数
learning_rate = 1e-3 # 学習率
ratio = 0.4 # r:単位の中で残す帯の割合(論文の CIFAR-10 の設定。ImageNet は 0.6)
d_min, d_max = 8, 32 # 単位の一辺 d を選ぶ範囲(論文の ImageNet の設定は 224 × 224 の画像で [96, 224])
max_prob = 0.8 # かける確率の上限 P
rise_epochs = 8 # 確率を 0 から P まで上げるエポック数(論文の ImageNet は 300 エポック中 240)
rotate = 1 # マスクを回す角度の上限(度)。1 なら回さない。ImageNet の設定では回す
# cudaを使えるなら'cuda', Apple Siliconなら'mps', それ以外なら'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
class GridMask:
# 論文の公式実装(JIA-Lab-research/GridMask の Grid クラス、mode=1)と同じ手順。
# 一辺 d の単位ごとに、幅 l = ceil(d·r) の帯(縦と横)を残し、残りの (1 − r)d の正方形を 0 にする
def __init__(self, d_min, d_max, ratio, rotate=1, prob=1.0):
self.d_min, self.d_max = d_min, d_max
self.ratio = ratio
self.rotate = rotate
self.max_prob = prob
self.prob = prob
def set_prob(self, epoch, rise_epochs):
# かける確率を、学習が進むにつれて上限まで直線的に上げる
self.prob = self.max_prob * min(1.0, epoch / rise_epochs)
def __call__(self, img): # img: 正規化したあとの [C, H, W] のテンソル
if np.random.rand() > self.prob:
return img
h, w = img.size(1), img.size(2)
hh = math.ceil(math.sqrt(h * h + w * w)) # 回しても画像を覆えるように、対角線の長さの正方形で作る
d = np.random.randint(self.d_min, self.d_max) # 単位の一辺 d
l = math.ceil(d * self.ratio) # 残す帯の幅 r·d
st_h, st_w = np.random.randint(d), np.random.randint(d) # 格子のずれ δy, δx(0〜d−1)
keep = torch.zeros(hh, hh)
for i in range(-1, hh // d + 1):
s = d * i + st_h
keep[max(min(s, hh), 0):max(min(s + l, hh), 0), :] = 1 # 横の帯を残す
s = d * i + st_w
keep[:, max(min(s, hh), 0):max(min(s + l, hh), 0)] = 1 # 縦の帯を残す
angle = float(np.random.randint(self.rotate))
keep = TF.rotate(keep[None], angle)[0] # マスクを回す(rotate=1 なら 0 度)
top, left = (hh - h) // 2, (hh - w) // 2
mask = keep[top:top + h, left:left + w] # 中央を画像の大きさに切り出す
return img * mask # x̃ = x × M。ラベルは変えない
grid_mask = GridMask(d_min, d_max, ratio, rotate=rotate, prob=max_prob)
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 で塗る=平均の色で塗る)
grid_mask, # 正規化のあとにかける
])
test_transform = transforms.Compose([ # 評価では GridMask を使わない
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)
# num_workers=0:データの読み込みを同じプロセスで行い、set_prob で変えた確率がそのまま効くようにする
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=0)
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)
# 学習:GridMask はデータの読み込みの中でかかる。ラベルはそのまま使う
for epoch in range(epochs):
grid_mask.set_prob(epoch, rise_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}%")