VAE
Variational Autoencoder (VAE)
A generative model that learns a probabilistic latent space. A deep learning architecture used for image generation, representation learning, and data compression.
Variational Autoencoder (VAE)
A generative model that learns a probabilistic latent space. A deep learning architecture used for image generation, representation learning, and data compression.
VAE (Variational Autoencoder) is a generative model that learns a latent representation of data probabilistically. Proposed by Kingma and Welling in 2013, this model combines a probabilistic approach with the traditional autoencoder, giving it the ability to generate new data rather than merely compress it. In a VAE, the Encoder encodes the input as a probability distribution (mean and variance) in the latent space, and the Decoder samples from this distribution to reconstruct the data.
The core of a VAE lies in its loss function. It consists of two terms: the Reconstruction Loss and the KL Divergence (Kullback-Leibler Divergence). The reconstruction loss minimizes the difference between input and output to ensure information is preserved, and the KL divergence regularizes the learned latent distribution so that it approaches the standard normal distribution. Thanks to this regularization, the latent space has a continuous and meaningful structure, so valid data can be generated even when sampling from an arbitrary point.
In practice, VAEs are used for image generation, anomaly detection, data augmentation, feature learning, and more. In particular, they are used as a key component of modern image generation models such as Stable Diffusion, enabling high-resolution images to be processed efficiently in a low-dimensional latent space. In the medical field, the reconstruction error of a VAE trained on normal data is used to detect abnormal (disease) patterns.
Variants of the VAE include Beta-VAE (learning interpretable latent variables), Conditional VAE (conditional generation), and VQ-VAE (discrete latent space). Compared with a GAN (Generative Adversarial Network), a VAE trains stably and its latent space is easier to interpret, but the generated images tend to be somewhat blurry. Recently, Latent Diffusion, which combines a VAE with a Diffusion Model, has become the standard for image generation.
VAE model and training code implemented in PyTorch:
# VAE (Variational Autoencoder) PyTorch ꡬν
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
class VAE(nn.Module):
"""Variational Autoencoder"""
def __init__(self, input_dim=784, hidden_dim=400, latent_dim=20):
super(VAE, self).__init__()
self.latent_dim = latent_dim
# Encoder: μ
λ ₯ -> μ μ¬ λΆν¬μ νκ· κ³Ό λΆμ°
self.encoder = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, hidden_dim // 2),
nn.ReLU()
)
# μ μ¬ λΆν¬ νλΌλ―Έν°
self.fc_mu = nn.Linear(hidden_dim // 2, latent_dim) # νκ·
self.fc_logvar = nn.Linear(hidden_dim // 2, latent_dim) # λ‘κ·Έ λΆμ°
# Decoder: μ μ¬ λ²‘ν° -> μ¬κ΅¬μ±λ μ
λ ₯
self.decoder = nn.Sequential(
nn.Linear(latent_dim, hidden_dim // 2),
nn.ReLU(),
nn.Linear(hidden_dim // 2, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, input_dim),
nn.Sigmoid() # 0-1 λ²μλ‘ μΆλ ₯
)
def encode(self, x):
"""μ
λ ₯μ μ μ¬ λΆν¬μ νλΌλ―Έν°λ‘ μΈμ½λ©"""
h = self.encoder(x)
mu = self.fc_mu(h)
logvar = self.fc_logvar(h)
return mu, logvar
def reparameterize(self, mu, logvar):
"""
Reparameterization Trick
z = mu + std * epsilon ννλ‘ μνλ§νμ¬ μμ ν κ°λ₯νκ² ν¨
"""
std = torch.exp(0.5 * logvar)
epsilon = torch.randn_like(std) # νμ€ μ κ·λΆν¬μμ μνλ§
z = mu + std * epsilon
return z
def decode(self, z):
"""μ μ¬ λ²‘ν°λ₯Ό μλ³Έ 곡κ°μΌλ‘ λμ½λ©"""
return self.decoder(z)
def forward(self, x):
"""μμ ν: μΈμ½λ© -> μνλ§ -> λμ½λ©"""
mu, logvar = self.encode(x)
z = self.reparameterize(mu, logvar)
reconstructed = self.decode(z)
return reconstructed, mu, logvar
def generate(self, num_samples, device='cpu'):
"""μλ‘μ΄ μν μμ±"""
# νμ€ μ κ·λΆν¬μμ μνλ§
z = torch.randn(num_samples, self.latent_dim).to(device)
samples = self.decode(z)
return samples
def vae_loss(reconstructed, original, mu, logvar, beta=1.0):
"""
VAE μμ€ ν¨μ
Args:
reconstructed: μ¬κ΅¬μ±λ μΆλ ₯
original: μλ³Έ μ
λ ₯
mu: μ μ¬ λΆν¬μ νκ·
logvar: μ μ¬ λΆν¬μ λ‘κ·Έ λΆμ°
beta: KL λ°μ° κ°μ€μΉ (Beta-VAEμ©)
Returns:
total_loss, recon_loss, kl_loss
"""
# 1. μ¬κ΅¬μ± μμ€ (Binary Cross Entropy)
recon_loss = F.binary_cross_entropy(reconstructed, original, reduction='sum')
# 2. KL Divergence: μ μ¬ λΆν¬μ νμ€ μ κ·λΆν¬ κ°μ 거리
# KL(q(z|x) || p(z)) = -0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)
kl_loss = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
total_loss = recon_loss + beta * kl_loss
return total_loss, recon_loss, kl_loss
def train_vae(model, train_loader, optimizer, device, epoch):
"""VAE νμ΅ ν¨μ"""
model.train()
total_loss = 0
total_recon = 0
total_kl = 0
for batch_idx, (data, _) in enumerate(train_loader):
data = data.view(-1, 784).to(device) # Flatten
optimizer.zero_grad()
reconstructed, mu, logvar = model(data)
loss, recon_loss, kl_loss = vae_loss(reconstructed, data, mu, logvar)
loss.backward()
optimizer.step()
total_loss += loss.item()
total_recon += recon_loss.item()
total_kl += kl_loss.item()
avg_loss = total_loss / len(train_loader.dataset)
print(f'Epoch {epoch}: Loss={avg_loss:.4f}, '
f'Recon={total_recon/len(train_loader.dataset):.4f}, '
f'KL={total_kl/len(train_loader.dataset):.4f}')
return avg_loss
def visualize_latent_space(model, test_loader, device):
"""μ μ¬ κ³΅κ° μκ°ν (2D μ μ¬ κ³΅κ°μΈ κ²½μ°)"""
model.eval()
z_list = []
label_list = []
with torch.no_grad():
for data, labels in test_loader:
data = data.view(-1, 784).to(device)
mu, _ = model.encode(data)
z_list.append(mu.cpu())
label_list.append(labels)
z = torch.cat(z_list, dim=0).numpy()
labels = torch.cat(label_list, dim=0).numpy()
if z.shape[1] == 2:
plt.figure(figsize=(10, 8))
scatter = plt.scatter(z[:, 0], z[:, 1], c=labels, cmap='tab10', alpha=0.6)
plt.colorbar(scatter)
plt.xlabel('Latent Dimension 1')
plt.ylabel('Latent Dimension 2')
plt.title('VAE Latent Space Visualization')
plt.savefig('vae_latent_space.png')
print("Latent space visualization saved to 'vae_latent_space.png'")
# μ¬μ© μμ
if __name__ == "__main__":
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f"Using device: {device}")
# MNIST λ°μ΄ν°μ
λ‘λ
transform = transforms.ToTensor()
train_dataset = datasets.MNIST('./data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST('./data', train=False, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=128, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=128, shuffle=False)
# VAE λͺ¨λΈ μ΄κΈ°ν
vae = VAE(input_dim=784, hidden_dim=400, latent_dim=20).to(device)
optimizer = torch.optim.Adam(vae.parameters(), lr=1e-3)
# νμ΅
print("Training VAE on MNIST...")
for epoch in range(1, 11):
train_vae(vae, train_loader, optimizer, device, epoch)
# μλ‘μ΄ μν μμ±
print("\nGenerating new samples...")
samples = vae.generate(16, device)
print(f"Generated samples shape: {samples.shape}")