What is an Autoencoder?
An autoencoder is a network that learns to copy its input to its output, but it must squeeze the data through a narrow middle layer called the bottleneck. To rebuild the input from so little information, the network must learn the most important features.
| Part | Job |
| Encoder | Compresses the input into a small code |
| Bottleneck | The compressed representation (for example 32 numbers) |
| Decoder | Rebuilds the input from the code |
Simple example: Describing a face in 32 numbers (age, hair color, smile and so on) and asking an artist to redraw the face from only those numbers. The numbers must capture the key details.
Dense Autoencoder
python
import keras
from keras import layers
import numpy as np
(x_train, _), (x_test, _) = keras.datasets.mnist.load_data()
x_train = x_train.reshape(-1, 784).astype("float32") / 255.0
x_test = x_test.reshape(-1, 784).astype("float32") / 255.0
inputs = keras.Input(shape=(784,))
encoded = layers.Dense(128, activation="relu")(inputs)
encoded = layers.Dense(32, activation="relu")(encoded) # bottleneck
decoded = layers.Dense(128, activation="relu")(encoded)
outputs = layers.Dense(784, activation="sigmoid")(decoded)
autoencoder = keras.Model(inputs, outputs)
autoencoder.compile(optimizer="adam", loss="mse")
# Input and target are the same data
autoencoder.fit(x_train, x_train, epochs=10, batch_size=256,
validation_data=(x_test, x_test))
See the Reconstructions
python
import matplotlib.pyplot as plt
recon = autoencoder.predict(x_test[:8])
plt.figure(figsize=(12, 3))
for i in range(8):
plt.subplot(2, 8, i + 1); plt.imshow(x_test[i].reshape(28, 28), cmap="gray"); plt.axis("off")
plt.subplot(2, 8, i + 9); plt.imshow(recon[i].reshape(28, 28), cmap="gray"); plt.axis("off")
plt.show()
The top row shows the originals and the bottom row shows the rebuilt images. They look similar even though they went through only 32 numbers.
Denoising Autoencoder
Give the network noisy images as input and clean images as the target. It learns to remove noise.
python
oise = 0.3
x_train_noisy = np.clip(x_train + noise * np.random.randn(*x_train.shape), 0, 1)
x_test_noisy = np.clip(x_test + noise * np.random.randn(*x_test.shape), 0, 1)
autoencoder.fit(x_train_noisy, x_train, epochs=10, batch_size=256,
validation_data=(x_test_noisy, x_test))
Convolutional Autoencoder
python
inputs = keras.Input(shape=(28, 28, 1))
x = layers.Conv2D(16, 3, activation="relu", padding="same")(inputs)
x = layers.MaxPooling2D(2, padding="same")(x)
x = layers.Conv2D(8, 3, activation="relu", padding="same")(x)
encoded = layers.MaxPooling2D(2, padding="same")(x) # (7, 7, 8)
x = layers.Conv2D(8, 3, activation="relu", padding="same")(encoded)
x = layers.UpSampling2D(2)(x)
x = layers.Conv2D(16, 3, activation="relu", padding="same")(x)
x = layers.UpSampling2D(2)(x)
outputs = layers.Conv2D(1, 3, activation="sigmoid", padding="same")(x)
conv_ae = keras.Model(inputs, outputs)
conv_ae.compile(optimizer="adam", loss="binary_crossentropy")
Use Case: Anomaly Detection
Train the autoencoder only on normal data. Normal samples are rebuilt well and abnormal ones are rebuilt badly, so a high reconstruction error signals an anomaly.
python
recon = autoencoder.predict(x_test)
errors = np.mean((x_test - recon) ** 2, axis=1)
threshold = np.percentile(errors, 99)
anomalies = errors > threshold
Conclusion
Autoencoders learn compact representations without labels. They are useful for noise removal, compression and anomaly detection.
Quick Summary: Encoder squeezes, decoder rebuilds. Train with the input as target. Add noise to the input for a denoising autoencoder.