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
np.random.seed(42)
X_train = np.random.randn(1000, 20)
X_test = np.random.randn(200, 20)
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
self.encoder = keras.Sequential([
layers.Dense(64, activation='relu', input_shape=(input_dim,)),
layers.Dense(32, activation='relu'),
layers.Dense(latent_dim, activation='linear')
])
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
input_dim = 20
latent_dim = 2
autoencoder = Autoencoder(input_dim, latent_dim)
autoencoder.compile(optimizer='adam', loss='mse')
history = autoencoder.fit(X_train, X_train,
epochs=100,
batch_size=32,
validation_data=(X_test, X_test),
verbose=0)
reconstructed = autoencoder.predict(X_test)
reconstruction_error = np.mean(np.square(X_test - reconstructed))
print(f"Reconstruction error: {reconstruction_error:.4f}")
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()
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__()
self.encoder = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, latent_dim),
nn.ReLU()
)
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
torch.manual_seed(42)
input_dim = 20
hidden_dim = 64
latent_dim = 4
n_samples = 1000
X_clean = torch.randn(n_samples, input_dim) * 0.5
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)
X_train = X_clean[:800]
X_test = X_clean[800:]
X_train_noisy = add_noise(X_train, noise_factor=0.2)
X_test_noisy = add_noise(X_test, noise_factor=0.2)
model = DenoisingAutoencoder(input_dim, hidden_dim, latent_dim)
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
num_epochs = 100
for epoch in range(num_epochs):
model.train()
optimizer.zero_grad()
outputs = model(X_train_noisy)
loss = criterion(outputs, X_train)
loss.backward()
optimizer.step()
if (epoch+1) % 20 == 0:
print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}')
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}')
with torch.no_grad():
fig, axes = plt.subplots(3, 5, figsize=(15, 8))
for i in range(5):
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])
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])
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
np.random.seed(42)
normal_data = np.random.multivariate_normal(
mean=[0, 0],
cov=[[1, 0.5], [0.5, 1]],
size=800
)
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)
X = np.concatenate([normal_data, anomaly_data])
y = np.concatenate([np.zeros(len(normal_data)), np.ones(len(anomaly_data))])
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42, stratify=y)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
class SimpleAutoencoder:
def __init__(self, input_dim, hidden_dim, latent_dim):
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):
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)
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
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):
output, _ = self.forward(X)
loss = self.compute_loss(X, output)
if epoch % 100 == 0:
print(f"Epoch {epoch}, Loss: {loss:.4f}")
if epoch % 200 == 0:
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)
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)
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)
threshold = np.percentile(train_errors, 95)
print(f"\nAnomaly detection threshold: {threshold:.4f}")
y_pred = (test_errors > threshold).astype(int)
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")
plt.figure(figsize=(15, 5))
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)
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)
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()