python
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torchvision.transforms import AutoAugment, AutoAugmentPolicy, InterpolationMode
from torch.utils.data import DataLoader
'''
CIFAR-10 の画像分類(論文で見つかった CIFAR-10 の方策で学習する)
'''
# ハイパーパラメータ
batch_size = 128 # バッチサイズ
epochs = 5 # エポック数
learning_rate = 1e-3 # 学習率
# 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 = transforms.Compose([
transforms.RandomCrop(32, padding=4), # 1. いつものデータ拡張
transforms.RandomHorizontalFlip(),
AutoAugment( # 2. AutoAugment の方策(PIL か uint8 のテンソルに使うので ToTensor の前)
policy=AutoAugmentPolicy.CIFAR10, # 初期値は IMAGENET。ほかに SVHN がある
interpolation=InterpolationMode.NEAREST, # 回転などの補間(初期値)
fill=None, # はみ出した所を埋める値(None なら 0)
),
transforms.ToTensor(),
transforms.Normalize(mean, std),
transforms.RandomErasing(p=1.0, scale=(0.25, 0.25), ratio=(1.0, 1.0), value=0), # 3. Cutout に近い処理(16×16)
])
test_transform = transforms.Compose([ # 評価ではデータ拡張をしない
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)
# 方策の中身:25 個の小方策。各小方策は ((種類, 確率, 強さ), (種類, 確率, 強さ))
policy = AutoAugment(AutoAugmentPolicy.CIFAR10).policies
print(len(policy), policy[1]) # 25 (('Rotate', 0.7, 2), ('TranslateX', 0.3, 9))
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)
# 学習:データ拡張はデータの読み込みの中でかかる
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}%")