Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 49

Autoencoders

Train a network to compress a row and rebuild it, so the narrow middle layer keeps what reconstruction needs. One example is on this page.

Intermediate12 min
Autoencoders MahiDev

What You Will Learn

  • Idea
  • Example
  • When to use it

Idea

An autoencoder learns to copy its input. A narrow hidden layer forces the copy to pass through a bottleneck. If the rebuilt row is close to the original, that bottleneck stored the useful part. Nonlinear layers can keep structure that a straight PCA axis would miss.

Example

python
import numpy as np
from sklearn.neural_network import MLPRegressor

rng = np.random.default_rng(0)
X = rng.normal(size=(40, 4))
model = MLPRegressor(hidden_layer_sizes=(2,), max_iter=800, random_state=0)
error = np.mean((X - model.fit(X, X).predict(X)) ** 2)
print(f"reconstruction error: {error:.3f}")

Output:

text
reconstruction error: 0.608

When to use it

  • Use it when a linear compression leaves too much reconstruction error.
  • The loss compares each row with its own reconstruction. There is no class label.
  • A tiny bottleneck underfits. A wide one memorizes and stops being a compression.

Loading playground…