敵対的生成ネットワーク (GAN) とは何ですか?

敵対的生成ネットワーク (GAN) とは何ですか?

1. 説明

        GAN (Generative Adversarial Network) ネットワークは、ジェネレーターとディスクリミネーターの 2 つのニューラル ネットワークで構成される深層学習モデルです。ジェネレーターは偽のデータを生成する責任を負い、ディスクリミネーターはデータの信頼性を判断する責任を負います。これらは敵対的学習を通じて相互作用し、互いに学習し、最終的にジェネレーターはより現実的なデータを生成し、ディスクリミネーターはデータの信頼性をより正確に判断できるようになります。GAN ネットワークは、生成モデルで最も有望な手法の 1 つであると考えられています。

2. GAN の概要

        GAN (Generative Adversarial Network) は、ジェネレーター ネットワークとディスクリミネーター ネットワークという 2 つの主要コンポーネントで構成されるニューラル ネットワーク アーキテクチャです。GAN の目的は、入力データの分布をシミュレートする現実的なデータを生成することです。

        生成ネットワークは、ランダム ノイズ ベクトルを入力として受け取り、入力データの分布に似るように設計された新しいデータ ポイントを生成します。弁別器ネットワークは、入力分布から生成されたデータ ポイントと実際のデータ ポイントを取得し、各入力が実際のものであるか生成されたものであるかを予測します。

        トレーニング中、ジェネレーター ネットワークはデータ ポイントを生成し、ディスクリミネーター ネットワークはそれが本物であるか生成されたものであるかを予測します。次に、ジェネレータ ネットワークは、ディスクリミネータの出力に基づいて、生成したデータがどの程度現実的であるかに関するフィードバックを受け取ります。このプロセスは、生成ネットワークが、弁別ネットワークが実際のデータと区別できない実際のデータを生成できるようになるまで繰り返されます。

        GAN のトレーニング プロセスは、ジェネレーター ネットワークとディスクリミネーター ネットワークが常にお互いを出し抜こうとする 2 人用ゲームとして説明できます。ジェネレーター ネットワークは、ディスクリミネーター ネットワークを欺くのに十分現実的なデータを生成することを目的としていますが、ディスクリミネーター ネットワークは、特定のデータ ポイントが本物であるか生成されたものであるかを正確に識別しようとします。

        トレーニング後、ジェネレーター ネットワークを使用して、入力データ分布と同様の新しいデータを生成できます。GAN は、画像やビデオの生成、テキストの生成、音楽の生成など、さまざまなアプリケーションで使用されて成功しています。ただし、GAN のトレーニングは困難な場合もあり、ジェネレーター ネットワークが限定された範囲の出力を生成するモード崩壊などの問題が発生しやすい場合があります。

        GAN アプリケーションの例は画像生成です。このスキームでは、生成ネットワークがランダム ノイズ ベクトルを受け取り、入力画像分布と同様の新しい画像を生成します。弁別ネットワークは、入力分布から生成された画像と実際の画像を取得し、各画像が実際のものであるか生成されたものであるかを予測します。

        トレーニング中、ジェネレーター ネットワークは画像を生成し、ディスクリミネーター ネットワークはそれが本物であるか生成されたものであるかを予測します。次に、生成ネットワークは、弁別器の出力に基づいて生成する画像の現実的な性質に関するフィードバックを受け取ります。このプロセスは、生成ネットワークが識別ネットワークと区別できない実際の画像を生成できるようになるまで繰り返されます。

        トレーニング後、ジェネレーター ネットワークを使用して、入力画像分布と同様の新しい画像を生成できます。たとえば、有名人の顔のデータセットで GAN をトレーニングし、それを使用して新しい現実的な有名人の顔を生成できます。GAN は、画像間の変換など、他の画像関連タスクにも使用されます。この場合、GAN は、画像の内容を維持しながら、画像を 1 つの領域 (昼間など) から別の領域 (夜間など) に変換するために使用されます。 。

        GAN ネットワーク用の疑似コードを書いてみましょう

Initialize the generator network G with random weights
Initialize the discriminator network D with random weights
Set the learning rate for both networks
Set the number of training epochs
Set the batch size

for epoch in range(num_epochs):
    for batch in data:
        # Train the discriminator network
        Sample a batch of real images from the training data
        Generate a batch of fake images from the generator network
        Train the discriminator network on the real and fake images
        Compute the discriminator loss
        
        # Train the generator network
        Generate a new batch of fake images from the generator network
        Compute the generator loss based on the discriminator's output
        Backpropagate the loss and update the generator's weights
        
        # Update the discriminator's weights
        Backpropagate the loss and update the discriminator's weights
    
    # Generate a sample of fake images from the generator
    Save the generator's weights

3. GANコーディングとPython

        GAN 用の完全な Python コードを作成するには、多くの時間とリソースが必要です。ただし、PyTorch ライブラリを使用して GAN をトレーニングする手順を簡単に説明します。

import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torch.utils.data import DataLoader

PyTorch を使用してジェネレーターとディスクリミネーターのネットワークを定義します。nn.Module

class Generator(nn.Module):
    def __init__(self):
        super(Generator, self).__init__()
        # Define the layers of the generator network
        
    def forward(self, z):
        # Define the forward pass of the generator network
        
class Discriminator(nn.Module):
    def __init__(self):
        super(Discriminator, self).__init__()
        # Define the layers of the discriminator network
        
    def forward(self, x):
        # Define the forward pass of the discriminator network

ハイパーパラメータを定義します。

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
batch_size = 128
num_epochs = 100
learning_rate = 2e-4
latent_size = 100
image_size = 28*28

MNIST データセットをロードし、データ ローダーを作成します。

train_dataset = datasets.MNIST(root='data/', train=True, transform=transforms.ToTensor(), download=True)
train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)

損失関数とオプティマイザーを定義します。

criterion = nn.BCELoss()
d_optimizer = optim.Adam(discriminator.parameters(), lr=learning_rate, betas=(0.5, 0.999))
g_optimizer = optim.Adam(generator.parameters(), lr=learning_rate, betas=(0.5, 0.999))

GAN のトレーニング:

for epoch in range(num_epochs):
    for batch_idx, (real_images, _) in enumerate(train_loader):
        # Train discriminator with real images
        real_images = real_images.view(-1, image_size).to(device)
        real_labels = torch.ones(batch_size, 1).to(device)
        fake_labels = torch.zeros(batch_size, 1).to(device)

        # Train discriminator with fake images
        z = torch.randn(batch_size, latent_size).to(device)
        fake_images = generator(z)
        d_real_loss = criterion(discriminator(real_images), real_labels)
        d_fake_loss = criterion(discriminator(fake_images), fake_labels)
        d_loss = d_real_loss + d_fake_loss
        d_optimizer.zero_grad()
        d_loss.backward()
        d_optimizer.step()

        # Train generator
        z = torch.randn(batch_size, latent_size).to(device)
        fake_images = generator(z)
        g_loss = criterion(discriminator(fake_images), real_labels)
        g_optimizer.zero_grad()
        g_loss.backward()
        g_optimizer.step()

トレーニングされたジェネレーターを使用して新しい画像を生成します。

z = torch.randn(64, latent_size).to(device)
generated_images = generator(z)

上記のコードは概要にすぎず、GAN の特定の使用例では追加の手順や変更が必要になる場合があることに注意してください。

コード内の空白を埋めてみましょう:)

import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torch.utils.data import DataLoader

# Define the generator network
class Generator(nn.Module):
    def __init__(self, input_size=100, output_size=784):
        super(Generator, self).__init__()
        self.input_size = input_size
        self.output_size = output_size
        
        self.fc1 = nn.Linear(input_size, 256)
        self.bn1 = nn.BatchNorm1d(256)
        self.fc2 = nn.Linear(256, 512)
        self.bn2 = nn.BatchNorm1d(512)
        self.fc3 = nn.Linear(512, 1024)
        self.bn3 = nn.BatchNorm1d(1024)
        self.fc4 = nn.Linear(1024, output_size)
        self.activation = nn.Tanh()
        
    def forward(self, x):
        x = self.fc1(x)
        x = self.bn1(x)
        x = self.activation(x)
        x = self.fc2(x)
        x = self.bn2(x)
        x = self.activation(x)
        x = self.fc3(x)
        x = self.bn3(x)
        x = self.activation(x)
        x = self.fc4(x)
        x = self.activation(x)
        return x

# Define the discriminator network
class Discriminator(nn.Module):
    def __init__(self, input_size=784, output_size=1):
        super(Discriminator, self).__init__()
        self.input_size = input_size
        self.output_size = output_size
        
        self.fc1 = nn.Linear(input_size, 1024)
        self.activation = nn.LeakyReLU(0.2)
        self.fc2 = nn.Linear(1024, 512)
        self.fc3 = nn.Linear(512, 256)
        self.fc4 = nn.Linear(256, output_size)
        self.sigmoid = nn.Sigmoid()
        
    def forward(self, x):
        x = self.fc1(x)
        x = self.activation(x)
        x = self.fc2(x)
        x = self.activation(x)
        x = self.fc3(x)
        x = self.activation(x)
        x = self.fc4(x)
        x = self.sigmoid(x)
        return x

# Define the hyperparameters
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
batch_size = 128
num_epochs = 50
learning_rate = 0.0002
input_size = 100
image_size = 28 * 28

# Load the MNIST dataset
train_dataset = datasets.MNIST(root="./data", train=True, transform=transforms.ToTensor(), download=True)
train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)

# Initialize the generator and discriminator networks
generator = Generator(input_size).to(device)
discriminator = Discriminator().to(device)

# Define the loss functions and optimizers
criterion = nn.BCELoss()
g_optimizer = optim.Adam(generator.parameters(), lr=learning_rate)
d_optimizer = optim.Adam(discriminator.parameters(), lr=learning_rate)

# Train the GAN
for epoch in range(num_epochs):
    for batch_idx, (real_images, _) in enumerate(train_loader):
        real_images = real_images.view(-1, image_size).to(device)
        batch_size = real_images.shape[0]
        
        # Train the discriminator network
        d_optimizer.zero_grad()
        
        # Train on real images
        real_labels = torch.ones(batch

おすすめ

転載: blog.csdn.net/gongdiwudu/article/details/132840583