GAN
Generative Adversarial Network
A generative model trained by a generator and a discriminator competing. Used for image generation, style transfer, and more.
Generative Adversarial Network
A generative model trained by a generator and a discriminator competing. Used for image generation, style transfer, and more.
GAN (Generative Adversarial Network) is a generative model proposed by Ian Goodfellow in 2014, with a structure in which two neural networks learn by competing adversarially. The Generator creates realistic-looking data from noise, and the Discriminator tries to distinguish the generated data from real data.
The core idea of GAN was inspired by game theory. The generator and the discriminator play a min-max game, in which the generator tries to fool the discriminator and the discriminator tries not to be fooled. Through this competition, the generator produces increasingly realistic data.
During training, the discriminator's loss function uses binary cross-entropy, and the generator is trained to make the discriminator judge the generated images as real. When the Nash equilibrium is reached, the generator produces a distribution identical to the real data distribution.
In practice, GANs are used for image generation (StyleGAN), image-to-image translation (Pix2Pix, CycleGAN), super-resolution (ESRGAN), data augmentation, face generation, and more. NVIDIA's StyleGAN3 generates photorealistic faces at 1024x1024 resolution, and training takes about 25 days on 8 V100 GPUs.
import torch
import torch.nn as nn
# 생성자 네트워크
class Generator(nn.Module):
def __init__(self, latent_dim=100, img_shape=(1, 28, 28)):
super().__init__()
self.img_shape = img_shape
self.model = nn.Sequential(
nn.Linear(latent_dim, 256),
nn.LeakyReLU(0.2),
nn.Linear(256, 512),
nn.LeakyReLU(0.2),
nn.Linear(512, 1024),
nn.LeakyReLU(0.2),
nn.Linear(1024, int(torch.prod(torch.tensor(img_shape)))),
nn.Tanh()
)
def forward(self, z):
img = self.model(z)
return img.view(img.size(0), *self.img_shape)
# 판별자 네트워크
class Discriminator(nn.Module):
def __init__(self, img_shape=(1, 28, 28)):
super().__init__()
self.model = nn.Sequential(
nn.Flatten(),
nn.Linear(int(torch.prod(torch.tensor(img_shape))), 512),
nn.LeakyReLU(0.2),
nn.Linear(512, 256),
nn.LeakyReLU(0.2),
nn.Linear(256, 1),
nn.Sigmoid()
)
def forward(self, img):
return self.model(img)
# 학습 루프 예시
def train_gan(generator, discriminator, dataloader, epochs=100):
criterion = nn.BCELoss()
g_optimizer = torch.optim.Adam(generator.parameters(), lr=0.0002)
d_optimizer = torch.optim.Adam(discriminator.parameters(), lr=0.0002)
for epoch in range(epochs):
for real_imgs, _ in dataloader:
batch_size = real_imgs.size(0)
# 판별자 학습
z = torch.randn(batch_size, 100)
fake_imgs = generator(z)
d_loss = criterion(discriminator(real_imgs), torch.ones(batch_size, 1)) + \
criterion(discriminator(fake_imgs.detach()), torch.zeros(batch_size, 1))
d_optimizer.zero_grad()
d_loss.backward()
d_optimizer.step()
# 생성자 학습
g_loss = criterion(discriminator(fake_imgs), torch.ones(batch_size, 1))
g_optimizer.zero_grad()
g_loss.backward()
g_optimizer.step()
print(f"Epoch {epoch}: D_loss={d_loss.item():.4f}, G_loss={g_loss.item():.4f}")
"What methods did you use to solve the mode collapse problem of GANs?" - "In our project, we applied Wasserstein GAN to improve training stability, and added the minibatch discrimination technique to improve it so that it generates diverse outputs. As a result, the FID score improved from 45 to 28."
"We're considering adopting GAN for this data augmentation. What are the pros and cons compared to existing augmentation?" - "GAN-based augmentation can learn domain-specific transformations, so it is effective for specialized data such as medical images. However, training requires a lot of GPU resources, and to verify generation quality, metrics such as FID or IS need to be monitored together."
"Is there a reason you used InstanceNorm instead of BatchNorm in the generator?" - "Yes, in image style transfer tasks, InstanceNorm normalizes the style of each sample independently, which enables more consistent style transfer. It is in the same context as using AdaIN in StyleGAN."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
This is a phenomenon in which the generator loses diversity and generates only similar images. It can be mitigated with techniques such as Wasserstein loss, spectral normalization, and progressive growing.
If the discriminator becomes too strong, the generator cannot learn, and in the opposite case, generation quality drops. Adjusting the training ratio between the generator and the discriminator (e.g., 1:5) and tuning the learning rate are essential.
A low FID (Frechet Inception Distance) is not always a good thing. Generation diversity and quality must be evaluated together, and the appropriate evaluation method differs by domain.