생성적 적대 신경망(GAN)이란 무엇입니까?

생성적 적대 신경망(GAN)이란 무엇입니까?

1. 설명

        GAN(Generative Adversarial Network) 네트워크는 생성기와 판별기라는 두 개의 신경망으로 구성된 딥러닝 모델입니다. 생성자는 잘못된 데이터를 생성하는 역할을 담당하고, 판별자는 데이터의 진위 여부를 판단하는 역할을 담당합니다. 그들은 적대적 학습을 통해 서로 상호 작용하고 학습하며, 궁극적으로 생성자는 보다 현실적인 데이터를 생성할 수 있고, 판별자는 데이터의 진위 여부를 보다 정확하게 판단할 수 있습니다. GAN 네트워크는 생성 모델에서 가장 유망한 방법 중 하나로 간주됩니다.

2. GAN 소개

        GAN(Generative Adversarial Network)은 생성자 네트워크와 판별자 네트워크라는 두 가지 주요 구성 요소로 구성된 신경망 아키텍처입니다. GAN의 목적은 입력 데이터의 분포를 시뮬레이션하는 현실적인 데이터를 생성하는 것입니다.

        생성기 네트워크는 임의의 잡음 벡터를 입력으로 사용하고 입력 데이터 분포와 유사하도록 설계된 새로운 데이터 포인트를 생성합니다. 판별자 네트워크는 입력 분포에서 생성된 데이터 포인트와 실제 데이터 포인트를 가져와 각 입력이 실제인지 생성되었는지 예측합니다.

        훈련 중에 생성기 네트워크는 데이터 포인트를 생성하고 판별기 네트워크는 그것이 실제인지 생성되었는지 예측합니다. 그런 다음 생성기 네트워크는 판별기의 출력을 기반으로 생성된 데이터가 얼마나 현실적인지에 대한 피드백을 받습니다. 이 프로세스는 생성자 네트워크가 판별자 네트워크가 실제 데이터와 구별할 수 없는 실제 데이터를 생성할 수 있을 때까지 반복됩니다.

        GAN의 훈련 과정은 생성자 네트워크와 판별자 네트워크가 끊임없이 서로를 능가하려고 노력하는 2인 게임으로 설명할 수 있습니다. 생성자 네트워크는 판별자 네트워크를 속일 수 있을 만큼 현실적인 데이터를 생성하는 것을 목표로 하고, 판별자 네트워크는 주어진 데이터 포인트가 실제인지 아니면 생성된 것인지 정확하게 식별하려고 시도합니다.

        훈련 후에는 생성기 네트워크를 사용하여 입력 데이터 분포와 유사한 새 데이터를 생성할 수 있습니다. GAN은 이미지 및 비디오 생성, 텍스트 생성, 음악 생성을 포함한 다양한 애플리케이션에서 성공적으로 사용되었습니다. 그러나 GAN 훈련은 어려울 수 있으며 생성기 네트워크가 제한된 범위의 출력을 생성하는 모드 붕괴와 같은 문제가 발생하기 쉽습니다.

        GAN 애플리케이션의 예로는 이미지 생성이 있습니다. 이 방식에서 생성기 네트워크는 무작위 노이즈 벡터를 수신하고 입력 이미지 분포와 유사한 새로운 이미지를 생성합니다. 판별자 네트워크는 입력 분포에서 생성된 이미지와 실제 이미지를 가져와 각 이미지가 실제인지 생성된 것인지 예측합니다.

        훈련 중에 생성기 네트워크는 이미지를 생성하고 판별기 네트워크는 그것이 실제인지 생성되었는지 예측합니다. 그런 다음 생성기 네트워크는 판별기의 출력을 기반으로 생성한 이미지의 현실적인 특성에 대한 피드백을 받습니다. 이 프로세스는 생성기 네트워크가 판별기 네트워크와 구별할 수 없는 실제 이미지를 생성할 수 있을 때까지 반복됩니다.

        훈련 후 생성기 네트워크를 사용하여 입력 이미지 분포와 유사한 새로운 이미지를 생성할 수 있습니다. 예를 들어, GAN은 유명한 얼굴 데이터 세트로 학습한 다음 새롭고 현실적인 유명인 얼굴을 생성하는 데 사용될 수 있습니다. GAN은 이미지의 내용을 유지하면서 이미지를 한 도메인(예: 주간)에서 다른 도메인(예: 야간)으로 변환하는 데 사용되는 이미지 간 변환과 같은 다른 이미지 관련 작업에도 사용됩니다. .

        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