メインコンテンツへスキップ
見出し画像

PyTorchでGANを実装する|手書き数字の生成

    GeneratorとDiscriminatorを競わせて、ノイズから画像を生み出す。その仕組みを、コードで確かめる。


    この記事について

    GAN(Generative Adversarial Network)は、2つのネットワークを敵対的に学習させることで、データを生成する手法。画像生成AIの出発点にあたる技術でもある。

    論文や数式だけを追うと複雑に見えるけれど、PyTorchで実装してみると構造は意外にもシンプル。この記事では、MNIST(手書き数字)データセットを使い、最も基本的なGANをゼロから実装する。


    GANの仕組み

    GANは、2つのネットワークを競わせながら学習させる。

    • Generator(生成器):ランダムなノイズから偽の画像を作る「贋作師」

    • Discriminator(識別器):画像が本物か偽物かを見破る「鑑定士」

    最初、Generatorはノイズしか出力できない。しかしDiscriminatorに見破られるたびに改善を重ね、やがて本物と見分けがつかない画像を生成できるようになる。

    画像

    モジュールのインポートとグローバル設定

    使用するモジュールと、画像サイズ・潜在変数の次元数などを指定する。

    import os
    import torch
    import torch.nn as nn
    import torch.optim as optim
    from torchvision import datasets, transforms
    from torch.utils.data import DataLoader
    import matplotlib.pyplot as plt
    import numpy as np
    
    # ハイパーパラメータ
    img_rows = 28
    img_cols = 28
    channels = 1
    img_shape = (channels, img_rows, img_cols)  # PyTorchは (C, H, W) 形式
    z_dim = 100  # 潜在空間の次元数
    
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    

    モデルの定義

    Generator(生成器)

    潜在空間のランダムなノイズベクトル(100次元)を受け取り、28×28ピクセルの画像を出力する。最後にTanh関数を通すことで、出力の値域を-1から1に収めている。

    class Generator(nn.Module):
        def __init__(self, z_dim, img_shape):
            super(Generator, self).__init__()
            self.img_shape = img_shape
    
            self.model = nn.Sequential(
                nn.Linear(z_dim, 128),
                nn.LeakyReLU(0.01, inplace=True),
                nn.Linear(128, int(np.prod(img_shape))),
                nn.Tanh()
            )
    
        def forward(self, z):
            img = self.model(z)
            return img.view(img.size(0), *self.img_shape)
    

    Discriminator(識別器)

    28×28の画像を受け取り、「その画像が本物である確率」を0〜1で出力する。Sigmoid関数によって確率値に変換している。

    class Discriminator(nn.Module):
        def __init__(self, img_shape):
            super(Discriminator, self).__init__()
    
            self.model = nn.Sequential(
                nn.Flatten(),
                nn.Linear(int(np.prod(img_shape)), 128),
                nn.LeakyReLU(0.01, inplace=True),
                nn.Linear(128, 1),
                nn.Sigmoid()
            )
    
        def forward(self, img):
            return self.model(img)
    

    モデルの構築と最適化の設定

    GeneratorとDiscriminatorをそれぞれ個別に最適化する。損失関数にはBinary Cross Entropyを使用。

    generator = Generator(z_dim, img_shape).to(device)
    discriminator = Discriminator(img_shape).to(device)
    
    criterion = nn.BCELoss()
    
    optimizer_G = optim.Adam(generator.parameters(), lr=0.0002, betas=(0.5, 0.999))
    optimizer_D = optim.Adam(discriminator.parameters(), lr=0.0002, betas=(0.5, 0.999))
    

    学習ループ

    コードは長く見えるが、やっていることはシンプル。Discriminatorは本物と偽物を正しく見分けるように学習し、Generatorは偽物を本物と誤認させるように学習する。この二者の競争が、生成画像の品質を徐々に引き上げていく。

    def sample_images(generator, rows=4, cols=4):
        generator.eval()
        z = torch.randn(rows * cols, z_dim).to(device)
        gen_imgs = generator(z).detach().cpu()
        gen_imgs = 0.5 * gen_imgs + 0.5  # [-1, 1] -> [0, 1]
    
        fig, axs = plt.subplots(rows, cols, figsize=(4, 4))
        cnt = 0
        for i in range(rows):
            for j in range(cols):
                axs[i, j].imshow(gen_imgs[cnt, 0, :, :], cmap='gray')
                axs[i, j].axis('off')
                cnt += 1
        plt.show()
    
    
    def train(iterations, batch_size, sample_interval):
        os.makedirs("checkpoints", exist_ok=True)
    
        # MNISTデータの読み込みと前処理([-1, 1]に正規化)
        transform = transforms.Compose([
            transforms.ToTensor(),
            transforms.Normalize([0.5], [0.5])
        ])
        dataloader = DataLoader(
            datasets.MNIST('.', train=True, download=True, transform=transform),
            batch_size=batch_size, shuffle=True, drop_last=True
        )
    
        losses = []
        iteration_checkpoints = []
        data_iter = iter(dataloader)
    
        for iteration in range(iterations + 1):
    
            # --- データの準備 ---
            try:
                real_imgs, _ = next(data_iter)
            except StopIteration:
                data_iter = iter(dataloader)
                real_imgs, _ = next(data_iter)
    
            real_imgs = real_imgs.to(device)
            valid = torch.ones(batch_size, 1).to(device)
            fake = torch.zeros(batch_size, 1).to(device)
    
            # --- Discriminatorの学習 ---
            optimizer_D.zero_grad()
            d_loss_real = criterion(discriminator(real_imgs), valid)
    
            z = torch.randn(batch_size, z_dim).to(device)
            gen_imgs = generator(z)
            d_loss_fake = criterion(discriminator(gen_imgs.detach()), fake)
    
            d_loss = 0.5 * (d_loss_real + d_loss_fake)
            d_loss.backward()
            optimizer_D.step()
    
            # --- Generatorの学習 ---
            optimizer_G.zero_grad()
            g_loss = criterion(discriminator(gen_imgs), valid)
            g_loss.backward()
            optimizer_G.step()
    
            # --- ログとチェックポイントの保存 ---
            if iteration % sample_interval == 0:
                print(f"{iteration} [D loss: {d_loss.item():.4f}] [G loss: {g_loss.item():.4f}]")
                losses.append((d_loss.item(), g_loss.item()))
                iteration_checkpoints.append(iteration + 1)
    
                sample_images(generator)
    
                torch.save(generator.state_dict(), f"checkpoints/generator_{iteration}.pth")
                torch.save(discriminator.state_dict(), f"checkpoints/discriminator_{iteration}.pth")
                print(f"Saved model checkpoints at iteration {iteration}")
    
        return np.array(losses), iteration_checkpoints
    
    
    losses, checkpoints = train(iterations=10000, batch_size=128, sample_interval=1000)
    

    sample_intervalで指定したイテレーションごとに、生成画像のサンプルが表示され、モデルのチェックポイントが保存される。

    今回は全結合層(Linear)のみのシンプルな構成のため、生成画像にはノイズが残る。畳み込み層(Conv2d)を導入したDCGANに進めば、より鮮明な画像を生成できるようになる。

    画像

    学習済みGeneratorによる画像生成

    保存したチェックポイントを読み込めば、学習済みのGeneratorで画像を生成できる。

    checkpoint_path = "checkpoints/generator_10000.pth"
    
    generator = Generator(z_dim, img_shape).to(device)
    generator.load_state_dict(torch.load(checkpoint_path, map_location=device))
    
    generator.eval()
    z = torch.randn(1, z_dim).to(device)
    
    with torch.no_grad():
        gen_img = generator(z)
    
    image = gen_img.squeeze().cpu().numpy()
    image = 0.5 * image + 0.5  # [-1, 1] -> [0, 1]
    
    plt.imshow(image, cmap='gray')
    plt.axis('off')
    plt.show()


    画像

    おわりに

    今回はわかりやすさを優先し、全結合層のみでGANを構成した。生成画像の品質はまだ粗いけれど、「GeneratorとDiscriminatorを競わせて学習させる」というGANの核となる仕組みはこれですべて。

    ここからの発展として、畳み込み層を使ったDCGANや、条件付きで生成を制御するConditional GANなどがある。この基本形を押さえておけば、そうした応用への見通しも立ちやすくなる。


    最近読んでよかった本(プロモーションを含みます)
    紙の書籍

    電子書籍


     
     
    本業は深層学習のエンジニア。2026年に兼業で個人事業を開業し、余計なものを削ぎ落とした「静かなアプリ」をつくる minimalab を立ち上げました。アプリ開発の過程や、深層学習関連の話題、読んだ本の感想など書いていきます。 https://minimalab.app/

    あなたへのおすすめ