python コピー
import torch
import torch.nn as nn
"""
Radford et al. (2015) の DCGAN(64×64 のカラー画像)
・生成器:z(100 次元)→ 射影して 4×4×1024 → 5×5・ストライド 2 の転置畳み込み 4 回 → 64×64×3(Figure 1)
・識別器:ストライド付きの畳み込み(論文は層ごとの図を示していない。チャネル数 64→128→256→512 はこの例で決めたもの)
・初期値 N(0, 0.02)、Adam(lr=0.0002, beta1=0.5)、LeakyReLU の傾き 0.2、バッチサイズ 128(4 節)
"""
z_dim = 100
def up(cin, cout):
# 5×5・ストライド 2 の転置畳み込みで縦横をちょうど 2 倍にする(padding=2, output_padding=1)
return nn.ConvTranspose2d(cin, cout, 5, stride=2, padding=2, output_padding=1, bias=False)
def down(cin, cout):
# 5×5・ストライド 2 の畳み込みで縦横を半分にする(プーリングは使わない)
return nn.Conv2d(cin, cout, 5, stride=2, padding=2, bias=False)
class Generator(nn.Module):
def __init__(self):
super().__init__()
self.project = nn.Linear(z_dim, 4 * 4 * 1024, bias=False) # 射影(行列の積)
self.bn0 = nn.BatchNorm2d(1024)
self.net = nn.Sequential(
up(1024, 512), nn.BatchNorm2d(512), nn.ReLU(True), # 8×8×512
up(512, 256), nn.BatchNorm2d(256), nn.ReLU(True), # 16×16×256
up(256, 128), nn.BatchNorm2d(128), nn.ReLU(True), # 32×32×128
up(128, 3), nn.Tanh(), # 64×64×3。出力層はバッチ正規化なし・Tanh
)
def forward(self, z):
h = self.project(z).view(-1, 1024, 4, 4) # 4 次元のテンソルに変形
return self.net(torch.relu(self.bn0(h)))
class Discriminator(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(
down(3, 64), nn.LeakyReLU(0.2, True), # 入力層はバッチ正規化なし。32×32
down(64, 128), nn.BatchNorm2d(128), nn.LeakyReLU(0.2, True), # 16×16
down(128, 256), nn.BatchNorm2d(256), nn.LeakyReLU(0.2, True), # 8×8
down(256, 512), nn.BatchNorm2d(512), nn.LeakyReLU(0.2, True), # 4×4
nn.Flatten(),
nn.Linear(4 * 4 * 512, 1), # 1 つの出力(シグモイド関数は損失の中で計算する)
)
def forward(self, x):
return self.net(x)
def init_weights(m):
# すべての重みを平均 0・標準偏差 0.02 の正規分布で初期化する
if isinstance(m, (nn.Conv2d, nn.ConvTranspose2d, nn.Linear)):
nn.init.normal_(m.weight, 0.0, 0.02)
elif isinstance(m, nn.BatchNorm2d):
nn.init.normal_(m.weight, 1.0, 0.02)
nn.init.zeros_(m.bias)
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
G, D = Generator().to(device), Discriminator().to(device)
G.apply(init_weights)
D.apply(init_weights)
bce = nn.BCEWithLogitsLoss()
opt_g = torch.optim.Adam(G.parameters(), lr=2e-4, betas=(0.5, 0.999))
opt_d = torch.optim.Adam(D.parameters(), lr=2e-4, betas=(0.5, 0.999))
def sample_z(m):
# 一様分布のノイズ(範囲 -1〜1 はこの例で決めたもの)
return torch.rand(m, z_dim, device=device) * 2 - 1
def train_step(x):
"""x:[128, 3, 64, 64]、画素は -1〜1 にそろえておく"""
m = x.size(0)
ones = torch.ones(m, 1, device=device)
zeros = torch.zeros(m, 1, device=device)
# 識別器:本物に 1、偽物に 0(生成器まで勾配を流さない)
fake = G(sample_z(m)).detach()
loss_d = bce(D(x), ones) + bce(D(fake), zeros)
opt_d.zero_grad()
loss_d.backward()
opt_d.step()
# 生成器:識別器に「本物」と判定させる(log D(G(z)) を大きくする)
loss_g = bce(D(G(sample_z(m))), ones)
opt_g.zero_grad()
loss_g.backward()
opt_g.step()
return loss_d.item(), loss_g.item()
# 使い方:G.train(); D.train() にして、データローダーの各バッチで train_step(x.to(device)) を呼ぶ
# 生成するときはバッチ正規化を移動平均に切り替える
G.eval()
with torch.no_grad():
images = G(sample_z(64)) # [64, 3, 64, 64]、-1〜1