🤖 AI/ML

Autoencoder

Autoencoder

A neural network that compresses its input and then reconstructs it. Used for dimensionality reduction, anomaly detection, and generative models.

📖 Detailed Explanation

An autoencoder is an unsupervised-learning neural network that is trained to compress input data into a low-dimensional latent space and then reconstruct the original from it. It has a symmetric structure in which the encoder compresses the input and the decoder reconstructs it.

It was first proposed by Rumelhart in 1986, and it drew attention as a key technology in the revival of deep learning along with Hinton's 2006 research on Deep Belief Networks. Since then, various variants such as VAE (2013) and NVAE (2020) have advanced the field of generative models.

The core principle is the bottleneck structure. Because the latent space has fewer dimensions than the input, the network learns to preserve only the essential characteristics of the data. It is trained to minimize the reconstruction loss, and in this process it automatically learns meaningful representations.

In practice, it is widely used for anomaly detection (training only on normal data, then identifying samples with a large reconstruction error as outliers), noise removal (Denoising AE), dimensionality reduction (a nonlinear extension of PCA), and generative models (VAE). Its range of application is broad, from defect detection in manufacturing to fraud detection in finance.

💻 Code Example

# PyTorch로 이상 탐지용 Autoencoder 구현
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, TensorDataset

class Autoencoder(nn.Module):
    def __init__(self, input_dim, latent_dim=32):
        super().__init__()
        # 인코더: 입력 -> 잠재 공간
        self.encoder = nn.Sequential(
            nn.Linear(input_dim, 128),
            nn.ReLU(),
            nn.Linear(128, 64),
            nn.ReLU(),
            nn.Linear(64, latent_dim)
        )
        # 디코더: 잠재 공간 -> 복원
        self.decoder = nn.Sequential(
            nn.Linear(latent_dim, 64),
            nn.ReLU(),
            nn.Linear(64, 128),
            nn.ReLU(),
            nn.Linear(128, input_dim)
        )

    def forward(self, x):
        latent = self.encoder(x)
        reconstructed = self.decoder(latent)
        return reconstructed

# 학습 함수
def train_autoencoder(model, data, epochs=100, lr=1e-3):
    optimizer = torch.optim.Adam(model.parameters(), lr=lr)
    criterion = nn.MSELoss()

    for epoch in range(epochs):
        for batch in data:
            x = batch[0]
            x_recon = model(x)
            loss = criterion(x_recon, x)

            optimizer.zero_grad()
            loss.backward()
            optimizer.step()

        if (epoch + 1) % 20 == 0:
            print(f"Epoch {epoch+1}, Loss: {loss.item():.4f}")

# 이상 탐지: 복원 오차 기반
def detect_anomaly(model, x, threshold):
    model.eval()
    with torch.no_grad():
        x_recon = model(x)
        errors = torch.mean((x - x_recon) ** 2, dim=1)
    return errors > threshold

🗣️ Examples of Practical Conversations

At the kickoff of a manufacturing anomaly detection project

"Defective samples make up only 0.1% of the total, so supervised learning is difficult. We propose training an Autoencoder on normal data only and classifying samples whose reconstruction error exceeds the 95th percentile as outliers."

In an architecture discussion with a senior engineer

"If you set the latent dimension too small, information loss is large, and if you set it too large, it reconstructs outliers well too. Our sensor data is 100-dimensional, so let's start at around 32 and adjust it while watching reconstruction quality and anomaly detection performance."

In a technical interview

"The biggest difference between a VAE and a regular Autoencoder is the structure of the latent space. A VAE constrains the latent variables with KL divergence so that they follow a normal distribution, which makes it possible to sample from the latent space and generate new data."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Cautions

1
Risk of Learning an Identity Function

If the latent dimension is equal to or larger than the input, the network simply learns an identity function that copies the input. Be sure to maintain the bottleneck structure or add Sparse/Denoising constraints.

2
Setting the Anomaly Detection Threshold

You must not set the reconstruction error threshold arbitrarily without validation data. Analyze the distribution of reconstruction errors on normal data, and decide it according to business requirements (recall vs. precision).

3
Training Data Contamination

An AE for anomaly detection must be trained only on normal data. If outliers are mixed into the training set, it will reconstruct them well too, which degrades detection performance.

🔗 Related Terms

📚 Learn More