6.VAEs For Anomaly Detection in Datasets
6.VAEs For Anomaly Detection in Datasets
import tensorflow as tf
from tensorflow.keras.layers import Input, Dense, Lambda, Flatten, Reshape, Layer
from tensorflow.keras.models import Model
from tensorflow.keras.losses import binary_crossentropy
from tensorflow.keras import backend as K
import numpy as np
import matplotlib.pyplot as plt
latent_inputs = Input(shape=(2,))
decoder = Model(latent_inputs, Reshape((28, 28, 1))(Dense(784,
activation='sigmoid')(Dense(128, activation='relu')(latent_inputs))))
# Visualize results
flags, errors, threshold = detect_anomalies(anomaly_data)
plt.hist(errors, bins=50, color='blue', alpha=0.7)
plt.axvline(threshold, color='red', linestyle='dashed', linewidth=2)
plt.title('Reconstruction Error Distribution')
plt.xlabel('Reconstruction Error'); plt.ylabel('Frequency'); plt.show()
plt.figure(figsize=(15, 6))
for i in range(10):
plt.subplot(2, 10, i + 1)
plt.imshow(normal_data[i].reshape(28, 28), cmap='gray')
plt.title('Normal'); plt.axis('off')
plt.subplot(2, 10, i + 11)
plt.imshow(anomaly_data[i].reshape(28, 28), cmap='gray')
plt.title('Anomaly' if flags[i] else 'Normal'); plt.axis('off')
plt.tight_layout(); plt.show()
OUTPUT :