An autoencoder is a neural network trained to copy its input to its output through a narrow middle layer (the bottleneck). To succeed it must learn a compressed representation – useful for dimensionality reduction, denoising and anomaly detection.
What You Will Learn
- Encoder, bottleneck and decoder
- Build a simple autoencoder with scikit-learn
- Compare it with PCA
- Anomaly detection with reconstruction error
- Variants: denoising, convolutional, variational
Prerequisites
Architecture
Input (64 pixels) → encoder 32 → bottleneck 8 → decoder 32 → output (64 pixels). The loss is the reconstruction error between input and output, so no labels are needed (self-supervised).
Autoencoder on Handwritten Digits
import numpy as np
from sklearn.datasets import load_digits
from sklearn.preprocessing import MinMaxScaler
from sklearn.neural_network import MLPRegressor
from sklearn.decomposition import PCA
X = MinMaxScaler().fit_transform(load_digits().data) # 1797 images, 8x8 = 64 pixels
ae = MLPRegressor(hidden_layer_sizes=(32, 8, 32), activation="relu",
max_iter=500, random_state=0).fit(X, X) # target = input
rec = ae.predict(X)
print("autoencoder MSE", round(np.mean((X - rec) ** 2), 4))
pca = PCA(8).fit(X)
print("PCA (8) MSE ", round(np.mean((X - pca.inverse_transform(pca.transform(X))) ** 2), 4))
autoencoder MSE 0.0312 PCA (8) MSE 0.0247
Explanation: Both compress 64 pixels to 8 numbers. Honest result: on this tiny dataset with a small dense network, PCA reconstructs slightly better. Autoencoders win on larger, more complex data (faces, audio, logs) when they use convolutional layers and more capacity, because they can learn non-linear structure that PCA cannot.
Anomaly Detection
err = np.mean((X - rec) ** 2, axis=1) # per-image error
rng = np.random.default_rng(0)
noise = rng.random((5, 64)) # 5 random "images"
noise_err = np.mean((noise - ae.predict(noise)) ** 2, axis=1)
print(round(err.mean(), 4), round(np.percentile(err, 99), 4), noise_err.round(3))
0.0312 0.0698 [0.16 0.172 0.191 0.22 0.199]
Explanation: Real digits reconstruct with an average error of 0.031 (99% below 0.070). Random noise images give errors of 0.16–0.22, far above the threshold, so they are flagged as anomalies. The same idea detects fraud, faulty machines and network intrusions: train on normal data only, flag high reconstruction error.
Variants
| Type | Idea | Use |
|---|---|---|
| Denoising | Input is corrupted, target is clean | Removing noise from images/audio |
| Sparse | Penalty keeps few neurons active | Feature learning |
| Convolutional | Conv layers in encoder, transposed conv in decoder | Images |
| Variational (VAE) | Bottleneck is a probability distribution | Generating new samples – see GANs and Generative AI |
from tensorflow import keras
inp = keras.Input(shape=(784,))
code = keras.layers.Dense(32, activation="relu")(inp)
out = keras.layers.Dense(784, activation="sigmoid")(code)
autoencoder = keras.Model(inp, out)
autoencoder.compile(optimizer="adam", loss="binary_crossentropy")
# autoencoder.fit(x_train, x_train, epochs=20, batch_size=256)
Series
Deep learning series: Intro to DL · ANN · Activation Functions · Loss Functions · Backpropagation · Optimizers · Dropout & BatchNorm · CNN · RNN · LSTM & GRU · Transfer Learning · Autoencoders · GANs · PyTorch vs TensorFlow
Interview Questions
Q: What is an autoencoder?
A network that learns to reconstruct its input through a bottleneck, learning a compressed representation without labels.
Q: Autoencoder vs PCA?
PCA is linear; an autoencoder with non-linear activations can learn non-linear compressions (with one linear layer and MSE it learns the same subspace as PCA).
Q: How are autoencoders used for anomaly detection?
Train on normal data; inputs with high reconstruction error are anomalies.
Practice Exercises
- Change the bottleneck to 2 and plot the codes of all digits coloured by label.
- Build a denoising version by adding Gaussian noise to the inputs only.
Summary
Autoencoders compress and reconstruct data without labels. Use the bottleneck for features, the reconstruction error for anomalies and VAEs for generation; compare with PCA honestly.
Machine Learning Tutorials, Courses and Certifications