Autoencoders

Learn autoencoders with interactive simulations. Understand dimensionality reduction, anomaly detection, and generative modeling through hands-on visualizations and real-world examples.

Encoder Network Decoder Network Latent Space Reconstruction Loss Optimization Denoising Autoencoder Visual Learning

What are Autoencoders?

Autoencoders are a type of artificial neural network used for unsupervised learning that aims to learn efficient representations (encoding) of input data by training the network to copy its input to its output. The network consists of two main components: an encoder that compresses the input into a lower-dimensional representation, and a decoder that reconstructs the input from this compressed representation.

Key Benefits

  • Dimensionality Reduction: Compress high-dimensional data into lower-dimensional representations
  • Anomaly Detection: Identify outliers by measuring reconstruction errors
  • Feature Learning: Automatically learn meaningful features without manual engineering
  • Generative Modeling: Generate new data samples similar to the training data
  • Data Denoising: Remove noise from corrupted input data

Common Applications

  • Image compression and denoising
  • Anomaly detection in industrial systems
  • Feature extraction for downstream tasks
  • Generative modeling and data synthesis
  • Recommendation systems and collaborative filtering
Compression
Reconstruction
Unsupervised
Efficient

Autoencoder Architecture Overview

Encoder

Maps input data to a compressed latent representation through successive transformations.

  • • Input layer
  • • Hidden layers
  • • Bottleneck layer
  • • Dimensionality reduction

Latent Space

Compressed representation containing essential features of the input data.

  • • Bottleneck representation
  • • Learned features
  • • Lower dimensionality
  • • Information preservation

Decoder

Reconstructs the original input from the compressed latent representation.

  • • Expansion layers
  • • Hidden layers
  • • Output layer
  • • Reconstruction

Autoencoder Simulation

Visualize how autoencoders compress and reconstruct data. Adjust parameters and see how the reconstruction quality changes!

20%
5%
10
Input Dimensions
2
Latent Dimensions
0.15
Reconstruction Error
5:1
Compression Ratio
How to use:
  • Select an autoencoder type to visualize different architectures
  • Adjust input and latent dimensions to see compression effects
  • Click "New Dataset" to generate sample data
  • Click "Run Simulation" to see compression and reconstruction
  • Try different types to understand their unique properties

Latent Space Visualization

Vanilla Autoencoder

Architecture and Training Process:

1
Encoder Network

Maps input x to latent representation z through successive linear transformations and non-linear activations

2
Latent Space

Compressed representation z with dimensionality much smaller than input x

3
Decoder Network

Maps latent representation z back to reconstructed output x' with same dimensionality as input

4
Loss Function

Minimize reconstruction error between input x and output x' using mean squared error or cross-entropy

Mathematical Formulation:

Encoder: z = f(x) = σ(W₁x + b₁)

Decoder: x' = g(z) = σ(W₂z + b₂)

Loss: L = ||x - x'||²

Time Complexity:

O(n × m × k) where:
  • n = number of samples
  • m = input dimensionality
  • k = number of hidden units

Advantages & Disadvantages:

Advantages
  • Simple architecture and training process
  • Effective for dimensionality reduction
  • Can learn non-linear mappings
  • Unsupervised learning capability
Disadvantages
  • May learn identity function without constraints
  • Latent representations may not be meaningful
  • Prone to overfitting with insufficient regularization
  • Limited generative capabilities

Other Autoencoder Variants

Description: Adds sparsity constraints to the hidden layer activations to learn more meaningful features.

Constraint: Uses KL divergence to enforce that average activation of hidden units is close to a small sparsity parameter ρ.

Application: Feature learning and representation learning for high-dimensional data.

Description: Trained to reconstruct clean input from corrupted versions, making the model robust to noise.

Training: Input is corrupted with noise (e.g., masking, Gaussian noise) and model learns to recover original.

Benefit: Learns more robust and generalizable representations compared to vanilla autoencoders.

Description: Probabilistic autoencoder that learns a continuous latent space distribution for generative modeling.

Architecture: Encoder outputs parameters of a distribution (mean and variance) instead of deterministic values.

Training: Combines reconstruction loss with KL divergence regularization to learn smooth latent space.

Description: Uses convolutional layers in encoder and transposed convolutional layers in decoder for image data.

Architecture: Encoder with conv layers and pooling, decoder with transposed conv layers and upsampling.

Application: Image compression, denoising, and generative modeling for visual data.

Advanced Autoencoder Simulations

Image Denoising Autoencoder

Visualize how autoencoders remove noise from corrupted images.

Variational Autoencoder

Understand how VAEs learn continuous latent distributions for generation.

Anomaly Detection

See how autoencoders identify outliers through reconstruction errors.

Dimensionality Reduction

Visualize how autoencoders compress high-dimensional data.

Python Implementation

Vanilla Autoencoder with TensorFlow/Keras

import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers import matplotlib.pyplot as plt # Generate sample data np.random.seed(42) X_train = np.random.randn(1000, 20) X_test = np.random.randn(200, 20) # Add some structure to the data X_train = X_train + 0.5 * np.outer(np.sin(np.arange(1000) * 0.1), np.ones(20)) X_test = X_test + 0.5 * np.outer(np.sin(np.arange(200) * 0.1), np.ones(20)) class Autoencoder(keras.Model): def __init__(self, input_dim, latent_dim): super(Autoencoder, self).__init__() self.latent_dim = latent_dim # Encoder self.encoder = keras.Sequential([ layers.Dense(64, activation='relu', input_shape=(input_dim,)), layers.Dense(32, activation='relu'), layers.Dense(latent_dim, activation='linear') ]) # Decoder self.decoder = keras.Sequential([ layers.Dense(32, activation='relu', input_shape=(latent_dim,)), layers.Dense(64, activation='relu'), layers.Dense(input_dim, activation='linear') ]) def call(self, x): encoded = self.encoder(x) decoded = self.decoder(encoded) return decoded # Create and compile autoencoder input_dim = 20 latent_dim = 2 autoencoder = Autoencoder(input_dim, latent_dim) autoencoder.compile(optimizer='adam', loss='mse') # Train the autoencoder history = autoencoder.fit(X_train, X_train, epochs=100, batch_size=32, validation_data=(X_test, X_test), verbose=0) # Evaluate reconstruction reconstructed = autoencoder.predict(X_test) reconstruction_error = np.mean(np.square(X_test - reconstructed)) print(f"Reconstruction error: {reconstruction_error:.4f}") # Visualize original vs reconstructed plt.figure(figsize=(12, 4)) plt.subplot(1, 2, 1) plt.imshow(X_test[:10], aspect='auto', cmap='viridis') plt.title('Original Data') plt.xlabel('Features') plt.ylabel('Samples') plt.subplot(1, 2, 2) plt.imshow(reconstructed[:10], aspect='auto', cmap='viridis') plt.title(f'Reconstructed Data\nError: {reconstruction_error:.4f}') plt.xlabel('Features') plt.ylabel('Samples') plt.tight_layout() plt.show() # Visualize latent space encoded_data = autoencoder.encoder.predict(X_test) plt.figure(figsize=(8, 6)) plt.scatter(encoded_data[:, 0], encoded_data[:, 1], alpha=0.7) plt.xlabel('Latent Dimension 1') plt.ylabel('Latent Dimension 2') plt.title('Latent Space Representation') plt.grid(True, alpha=0.3) plt.show()

Denoising Autoencoder with PyTorch

import torch import torch.nn as nn import torch.optim as optim import numpy as np import matplotlib.pyplot as plt class DenoisingAutoencoder(nn.Module): def __init__(self, input_dim, hidden_dim, latent_dim): super(DenoisingAutoencoder, self).__init__() # Encoder self.encoder = nn.Sequential( nn.Linear(input_dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, latent_dim), nn.ReLU() ) # Decoder self.decoder = nn.Sequential( nn.Linear(latent_dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, input_dim) ) def forward(self, x): encoded = self.encoder(x) decoded = self.decoder(encoded) return decoded def add_noise(data, noise_factor=0.2): noise = torch.randn_like(data) * noise_factor return data + noise # Generate sample data torch.manual_seed(42) input_dim = 20 hidden_dim = 64 latent_dim = 4 # Create sample data with patterns n_samples = 1000 X_clean = torch.randn(n_samples, input_dim) * 0.5 # Add some structure for i in range(5): X_clean[:, i*4:(i+1)*4] += 0.3 * torch.sin(torch.arange(n_samples).float() * (0.1 * (i+1))).unsqueeze(1) # Split data X_train = X_clean[:800] X_test = X_clean[800:] # Add noise to training data X_train_noisy = add_noise(X_train, noise_factor=0.2) X_test_noisy = add_noise(X_test, noise_factor=0.2) # Initialize model, loss, and optimizer model = DenoisingAutoencoder(input_dim, hidden_dim, latent_dim) criterion = nn.MSELoss() optimizer = optim.Adam(model.parameters(), lr=0.001) # Training loop num_epochs = 100 for epoch in range(num_epochs): model.train() optimizer.zero_grad() # Forward pass outputs = model(X_train_noisy) loss = criterion(outputs, X_train) # Backward pass loss.backward() optimizer.step() if (epoch+1) % 20 == 0: print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}') # Evaluate on test set model.eval() with torch.no_grad(): reconstructed = model(X_test_noisy) test_loss = criterion(reconstructed, X_test) print(f'\nTest Reconstruction Loss: {test_loss.item():.4f}') # Visualize results with torch.no_grad(): # Show first 5 samples fig, axes = plt.subplots(3, 5, figsize=(15, 8)) for i in range(5): # Original axes[0, i].plot(X_test[i].numpy(), 'b-', linewidth=2) axes[0, i].set_title(f'Original {i+1}') axes[0, i].set_ylim([-2, 2]) # Noisy axes[1, i].plot(X_test_noisy[i].numpy(), 'r-', alpha=0.7) axes[1, i].set_title(f'Noisy {i+1}') axes[1, i].set_ylim([-2, 2]) # Reconstructed axes[2, i].plot(reconstructed[i].numpy(), 'g-', linewidth=2) axes[2, i].set_title(f'Reconstructed {i+1}') axes[2, i].set_ylim([-2, 2]) plt.tight_layout() plt.show()

Anomaly Detection with Autoencoders

import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler # Generate normal data (Gaussian distribution) np.random.seed(42) normal_data = np.random.multivariate_normal( mean=[0, 0], cov=[[1, 0.5], [0.5, 1]], size=800 ) # Generate anomalous data (uniform distribution in a ring) anomaly_data = [] for _ in range(200): angle = np.random.uniform(0, 2 * np.pi) radius = np.random.uniform(3, 4) anomaly_data.append([radius * np.cos(angle), radius * np.sin(angle)]) anomaly_data = np.array(anomaly_data) # Combine data and create labels X = np.concatenate([normal_data, anomaly_data]) y = np.concatenate([np.zeros(len(normal_data)), np.ones(len(anomaly_data))]) # Split data X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42, stratify=y) # Standardize features scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) X_test_scaled = scaler.transform(X_test) # Simple autoencoder for anomaly detection class SimpleAutoencoder: def __init__(self, input_dim, hidden_dim, latent_dim): # Initialize weights self.W1 = np.random.randn(input_dim, hidden_dim) * 0.1 self.b1 = np.zeros(hidden_dim) self.W2 = np.random.randn(hidden_dim, latent_dim) * 0.1 self.b2 = np.zeros(latent_dim) self.W3 = np.random.randn(latent_dim, hidden_dim) * 0.1 self.b3 = np.zeros(hidden_dim) self.W4 = np.random.randn(hidden_dim, input_dim) * 0.1 self.b4 = np.zeros(input_dim) def sigmoid(self, x): return 1 / (1 + np.exp(-np.clip(x, -500, 500))) def forward(self, x): # Encoder self.z1 = np.dot(x, self.W1) + self.b1 self.a1 = self.sigmoid(self.z1) self.z2 = np.dot(self.a1, self.W2) + self.b2 self.a2 = self.sigmoid(self.z2) # Latent representation # Decoder self.z3 = np.dot(self.a2, self.W3) + self.b3 self.a3 = self.sigmoid(self.z3) self.z4 = np.dot(self.a3, self.W4) + self.b4 self.a4 = self.z4 # Linear output return self.a4, self.a2 def compute_loss(self, y_true, y_pred): return np.mean((y_true - y_pred) ** 2) def train(self, X, epochs=1000, learning_rate=0.01): for epoch in range(epochs): # Forward pass output, _ = self.forward(X) loss = self.compute_loss(X, output) if epoch % 100 == 0: print(f"Epoch {epoch}, Loss: {loss:.4f}") # Compute gradients (simplified) # In practice, you would implement proper backpropagation if epoch % 200 == 0: # Simple weight update for demonstration self.W1 -= learning_rate * 0.01 * np.random.randn(*self.W1.shape) self.W2 -= learning_rate * 0.01 * np.random.randn(*self.W2.shape) self.W3 -= learning_rate * 0.01 * np.random.randn(*self.W3.shape) self.W4 -= learning_rate * 0.01 * np.random.randn(*self.W4.shape) # Train autoencoder autoencoder = SimpleAutoencoder(input_dim=2, hidden_dim=8, latent_dim=2) print("Training autoencoder for anomaly detection...") autoencoder.train(X_train_scaled, epochs=500, learning_rate=0.01) # Compute reconstruction errors def compute_reconstruction_errors(model, X): reconstructed, _ = model.forward(X) return np.mean((X - reconstructed) ** 2, axis=1) train_errors = compute_reconstruction_errors(autoencoder, X_train_scaled) test_errors = compute_reconstruction_errors(autoencoder, X_test_scaled) # Set threshold for anomaly detection (95th percentile of training errors) threshold = np.percentile(train_errors, 95) print(f"\nAnomaly detection threshold: {threshold:.4f}") # Detect anomalies y_pred = (test_errors > threshold).astype(int) # Calculate accuracy accuracy = np.mean(y_pred == y_test[len(X_test_scaled):len(y_pred)+len(X_test_scaled)] if len(y_pred) <= len(y_test) else y_test) print(f"Anomaly detection accuracy: {accuracy:.2%}" if len(y_pred) <= len(y_test) else "Anomaly detection completed") # Visualize results plt.figure(figsize=(15, 5)) # Plot 1: Original data plt.subplot(1, 3, 1) normal_idx = y_test == 0 anomaly_idx = y_test == 1 plt.scatter(X_test_scaled[normal_idx, 0], X_test_scaled[normal_idx, 1], c='blue', alpha=0.6, label='Normal') plt.scatter(X_test_scaled[anomaly_idx, 0], X_test_scaled[anomaly_idx, 1], c='red', alpha=0.6, label='Anomaly') plt.xlabel('Feature 1') plt.ylabel('Feature 2') plt.title('Original Data Distribution') plt.legend() plt.grid(True, alpha=0.3) # Plot 2: Reconstruction errors plt.subplot(1, 3, 2) plt.scatter(range(len(test_errors[normal_idx])), test_errors[normal_idx], c='blue', alpha=0.6, label='Normal') plt.scatter(range(len(test_errors[normal_idx]), len(test_errors)), test_errors[anomaly_idx], c='red', alpha=0.6, label='Anomaly') plt.axhline(y=threshold, color='black', linestyle='--', label=f'Threshold ({threshold:.3f})') plt.xlabel('Sample Index') plt.ylabel('Reconstruction Error') plt.title('Reconstruction Errors') plt.legend() plt.grid(True, alpha=0.3) # Plot 3: Detected anomalies plt.subplot(1, 3, 3) correct_normal = (y_pred == 0) & (y_test[:len(y_pred)] == 0) correct_anomaly = (y_pred == 1) & (y_test[:len(y_pred)] == 1) false_normal = (y_pred == 0) & (y_test[:len(y_pred)] == 1) false_anomaly = (y_pred == 1) & (y_test[:len(y_pred)] == 0) if np.any(correct_normal): plt.scatter(X_test_scaled[correct_normal, 0], X_test_scaled[correct_normal, 1], c='blue', alpha=0.6, label='True Normal') if np.any(correct_anomaly): plt.scatter(X_test_scaled[correct_anomaly, 0], X_test_scaled[correct_anomaly, 1], c='red', alpha=0.6, label='True Anomaly') if np.any(false_normal): plt.scatter(X_test_scaled[false_normal, 0], X_test_scaled[false_normal, 1], c='lightblue', marker='x', s=100, linewidth=3, label='False Normal') if np.any(false_anomaly): plt.scatter(X_test_scaled[false_anomaly, 0], X_test_scaled[false_anomaly, 1], c='orange', marker='x', s=100, linewidth=3, label='False Anomaly') plt.xlabel('Feature 1') plt.ylabel('Feature 2') plt.title('Anomaly Detection Results') plt.legend() plt.grid(True, alpha=0.3) plt.tight_layout() plt.show()

Test Your Knowledge

Answer these questions to test your understanding of autoencoder concepts.

Question 1: What is the primary purpose of an autoencoder?
A) To learn efficient representations of input data by copying its input to its output
B) To classify input data into predefined categories
C) To generate random data samples
D) To perform supervised regression tasks
Question 2: What is the role of the bottleneck layer in an autoencoder?
A) To increase the dimensionality of the data
B) To force the network to learn a compressed representation of the input
C) To add noise to the input data
D) To initialize the network weights
Question 3: How does a denoising autoencoder differ from a vanilla autoencoder?
A) It uses convolutional layers instead of fully connected layers
B) It has more hidden layers
C) It is trained to reconstruct clean input from corrupted versions
D) It uses a different activation function
Question 4: What makes variational autoencoders (VAEs) different from regular autoencoders?
A) They learn a probability distribution over the latent space instead of deterministic values
B) They always have more layers
C) They use different loss functions
D) They cannot be used for reconstruction
Question 5: In anomaly detection with autoencoders, what indicates a potential anomaly?
A) Low reconstruction error
B) High reconstruction error
C) High training accuracy
D) Low learning rate
Question 6: What is the main advantage of using autoencoders for dimensionality reduction compared to stat-card?
A) Autoencoders are faster to train
B) Autoencoders always produce better results
C) Autoencoders can learn non-linear mappings
D) Autoencoders require less data