python
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from tqdm import tqdm
'''
MNISTデータを使った画像分類タスク
'''
# ハイパーパラメータ
batch_size = 64 # バッチサイズ
epochs = 10 # エポック数
learning_rate = 1e-3 # 学習率
num_blocks = 2 # MLP-Mixer Blockを何層重ねるか (2層->96.90%, 3層->97.35%)
# windowsでcudaを使えるなら'cuda', Apple Siliconなら'mps', それ以外なら'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
# データセットとローダー
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size)
# MLP-Mixer Block
class MLPMixerBlock(nn.Module):
def __init__(self, num_patches: int, hidden_dim: int, token_dim: int, channel_dim: int):
super().__init__()
self.token_mixing = nn.Sequential(
nn.LayerNorm(num_patches),
nn.Linear(num_patches, token_dim),
nn.GELU(),
nn.Linear(token_dim, num_patches)
)
self.channel_mixing = nn.Sequential(
nn.LayerNorm(hidden_dim),
nn.Linear(hidden_dim, channel_dim),
nn.GELU(),
nn.Linear(channel_dim, hidden_dim)
)
def forward(self, x):
# 転置
y = x.permute(0, 2, 1)
# Token Mixer (MLP1)
x = x + self.token_mixing(y).permute(0, 2, 1)
# Channel Mixer (MLP2)
x = x + self.channel_mixing(x)
return x
# MLP-Mixer モデル
class MLPMixer(nn.Module):
def __init__(self, image_size=28, patch_size=7, hidden_dim=64, token_dim=32, channel_dim=128, num_classes=10):
super().__init__()
assert image_size % patch_size == 0
num_patches = (image_size // patch_size) ** 2
self.patch_embedding = nn.Conv2d(1, hidden_dim, kernel_size=patch_size, stride=patch_size)
self.mixer_blocks = nn.Sequential(*[
MLPMixerBlock(num_patches, hidden_dim, token_dim, channel_dim)
for _ in range(num_blocks)
])
self.layer_norm = nn.LayerNorm(hidden_dim)
self.classifier = nn.Linear(hidden_dim, num_classes)
def forward(self, x):
x = self.patch_embedding(x) # [B, hidden_dim, H', W']
x = x.flatten(2).transpose(1, 2) # [B, num_patches, hidden_dim]
x = self.mixer_blocks(x) # [B, num_patches, hidden_dim]
x = self.layer_norm(x)
x = x.mean(dim=1) # Global average pooling
return self.classifier(x)
# 学習と評価
model = MLPMixer().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# 学習ループ
for epoch in tqdm(range(epochs)):
model.train()
for images, labels in train_loader:
images, labels = images.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
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)
outputs = model(images)
_, predicted = torch.max(outputs, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
accuracy = 100 * correct / total
print(f"Test Accuracy: {accuracy:.2f}%")