DEV Community

zeromathai
zeromathai

Posted on Originally published at zeromathai.com

Encoder–Decoder and Autoencoder Fundamentals: Learning Representations Through Reconstruction

A 28×28 handwritten digit image contains 784 pixel values. But do you really need all 784 values to represent the shape of a digit?

Features such as stroke direction, thickness, and curvature can be encoded into a smaller representation that retains enough information to reconstruct an image resembling the original.

An autoencoder learns this representation directly from data. Instead of specifying which features matter, we train the model to reconstruct its input and let the reconstruction objective guide feature learning.

The Encoder–Decoder Architecture

An encoder–decoder architecture consists of two neural network components:

  • Encoder: Transforms input data into an internal representation suitable for a task.
  • Decoder: Uses that representation to produce the required output.

Given an input xx , an internal representation hh , and an output yy , information flows through the architecture as follows:

x→Encoderh→Decodery x \xrightarrow{\mathrm{Encoder}} h \xrightarrow{\mathrm{Decoder}} y

For example, an encoder can transform a 784-dimensional image into a 32-dimensional vector. Rather than selecting 32 original pixels, it combines information from multiple pixels into a learned representation called a latent code or latent representation.

An encoder does not necessarily reduce dimensionality, and a decoder does not necessarily reconstruct the original input. This flexibility makes the architecture useful across different deep learning tasks.

Architecture Encoder Decoder
U-Net Extracts image features Produces pixel-level segmentation results
Sequence-to-Sequence Represents an input sequence Generates an output sequence, such as a translation
Encoder–Decoder Transformer Represents input information using attention Generates an output sequence

U-Net also uses skip connections to pass intermediate encoder features directly to the decoder.

Depending on the characteristics of the data, encoders and decoders can be built using MLPs, CNNs, LSTMs, or attention mechanisms.

What Makes an Autoencoder Different?

An autoencoder is a specific application of the encoder–decoder architecture in which the input itself serves as the reconstruction target.

At the beginning of training, the encoder has not yet learned which information is useful. If the latent code fails to preserve information needed for reconstruction, the reconstruction error increases. Minimizing that error encourages the encoder to capture information that helps the decoder recover the original input.

Consider an autoencoder processing handwritten digit images:

Input image         Latent code         Reconstructed image
784 dimensions      32 dimensions       784 dimensions

x ── Encoder ──► h ── Decoder ──► x_reconstructed
│                                       │
└───────── Reconstruction Loss ─────────┘
Enter fullscreen mode Exit fullscreen mode

The encoder maps the image into a 32-dimensional latent code, and the decoder produces a 784-dimensional reconstruction. Both networks are trained together to reduce the reconstruction error.

Let fϕf_{\phi} represent the encoder and gθg_{\theta} represent the decoder, with trainable parameters ϕ\phi and θ\theta , respectively.

The encoder computes the latent code:

h=fϕ(x) h=f_{\phi}(x)

The decoder produces the reconstruction:

x~=gθ(h) \tilde{x}=g_{\theta}(h)

Combining these operations gives the complete autoencoder mapping:

x~=gθ(fϕ(x))≈x \tilde{x}=g_{\theta}(f_{\phi}(x))\approx x

The model does not need a label identifying which digit appears in the image because the input itself provides the training target.

Autoencoders are commonly classified as unsupervised learning models. They can also be understood from a self-supervised learning perspective because their training targets come directly from the input data.

Reconstruction Loss: How the Model Learns

Reconstruction loss measures the difference between the original input and its reconstruction. Early in training, reconstructed images may appear blurry or have shapes that differ from the originals. Minimizing reconstruction loss improves reconstruction accuracy.

For continuous numerical data, one possible reconstruction objective is mean squared error (MSE):

Lrecon(x,x~)1d∑i=1d(xi−x~i)2 \mathcal{L}_{\mathrm{recon}}(x,\tilde{x}) \frac{1}{d}\sum_{i=1}^{d}(x_i-\tilde{x}_i)^2

Here:

  • dd is the input dimensionality.
  • xix_i is the original value of the ii -th component.
  • x~i\tilde{x}_i is the corresponding reconstructed value.

Squaring the differences prevents positive and negative errors from canceling each other out and penalizes larger errors more heavily.

For example, consider a pixel with an original value of 0.9:

Original value Reconstructed value Squared error
0.9 0.5 0.16
0.9 0.8 0.01

For the handwritten digit image, MSE averages the squared errors across all 784 pixels. Other reconstruction loss functions may be appropriate depending on the characteristics of the data.

What Happens During Training?

The training loop can be expressed as framework-independent pseudocode:

repeat during training:
h = encoder(x)
x_reconstructed = decoder(h)

loss = reconstruction_loss(x, x_reconstructed)

compute gradients using backpropagation
update encoder parameters
update decoder parameters
Enter fullscreen mode Exit fullscreen mode

Backpropagation computes gradients of the reconstruction loss with respect to the trainable parameters of both networks.

Through repeated parameter updates, the encoder learns to preserve information useful for reconstruction, while the decoder learns to interpret that information and recover the original input more accurately.

Using the Encoder as a Feature Extractor

Once trained, the encoder can be used independently as a feature extractor. Instead of passing 784 raw pixel values to a classification model or clustering algorithm, you can pass the learned 32-dimensional latent representation.

Learning useful internal representations from data is known as representation learning. Reconstruction provides the training objective, but the usefulness of the resulting representation depends on more than reconstruction accuracy.

Undercomplete vs. Overcomplete Autoencoders

Suppose an encoder passes the input through unchanged and the decoder simply copies it. The reconstruction loss would be zero, but the model would not need to extract meaningful features.

To discourage trivial copying, autoencoders need constraints on their latent representations or training procedures. Two common configurations differ in how the dimensionality of the latent code relates to that of the input.

Undercomplete Autoencoder

An undercomplete autoencoder has a latent representation with fewer dimensions than the input:

dim⁡(x)>dim⁡(h)(Undercomplete) \dim(x)>\dim(h)\qquad\text{(Undercomplete)}

The smaller latent representation creates a bottleneck, restricting the space available for encoding information useful for reconstruction.

Overcomplete Autoencoder

An overcomplete autoencoder has a latent representation with more dimensions than the input:

dim⁡(h)>dim⁡(x)(Overcomplete) \dim(h)>\dim(x)\qquad\text{(Overcomplete)}

The larger latent space provides room for a wider variety of feature representations, but it also increases the risk of trivial input copying.

Additional training constraints are particularly important in this configuration. Common approaches include:

  • Sparsity constraints: Restrict the number of active components in the latent code.
  • Denoising: Train the model to reconstruct clean original data from noisy inputs.

The Bottleneck Trade-Off

Property Undercomplete Overcomplete
Latent dimensionality Smaller than the input Larger than the input
Example 784 → 32 → 784 784 → 1024 → 784
Main advantage Restricts the representation space Provides more room for feature representations
Potential risk Information loss or memorization Trivial input copying

A narrow bottleneck does not automatically guarantee useful feature learning. If the latent dimensionality is too small, important information may be lost. A sufficiently expressive network may also memorize training data despite having a restricted latent dimensionality.

When designing an autoencoder, consider latent dimensionality, model capacity, and training constraints together.

Deterministic vs. Stochastic Representations

The distinction between deterministic and stochastic representations comes down to what the encoder and decoder produce: fixed values or probability distributions over possible values.

Deterministic Encoding and Decoding

A conventional autoencoder typically uses deterministic encoding and decoding:

h=fϕ(x) h=f_{\phi}(x)
x~=gθ(h) \tilde{x}=g_{\theta}(h)

With fixed model parameters, the same input always produces the same latent code, and the same latent code produces the same reconstruction.

Input → Fixed latent code → Fixed reconstruction
Enter fullscreen mode Exit fullscreen mode

Stochastic Encoding and Decoding

Rather than directly computing a fixed latent code, a stochastic encoder defines a conditional probability distribution from which a latent code can be sampled:

h∼qenc,ϕ(h∣x) h\sim q_{\mathrm{enc},\phi}(h\mid x)

Similarly, a stochastic decoder defines a conditional probability distribution over possible reconstructed outputs:

x~∼pdec,θ(x~∣h) \tilde{x}\sim p_{\mathrm{dec},\theta}(\tilde{x}\mid h)

The notation describes two conditional relationships:

  • qenc,ϕ(h∣x)q_{\mathrm{enc},\phi}(h\mid x) is the encoder-defined distribution conditioned on the input xx .
  • pdec,θ(x~∣h)p_{\mathrm{dec},\theta}(\tilde{x}\mid h) is the decoder-defined distribution conditioned on the latent code hh .

The variable to the right of ∣\mid specifies the conditioning information, while ∼\sim indicates that a value is sampled from the specified distribution.

For example, instead of representing one latent component as the fixed value 0.8, a stochastic encoder could define a normal distribution with a mean of 0.8 and a standard deviation of 0.1. Sampling from that distribution could produce values such as 0.76 or 0.91.

A stochastic decoder works on the same principle: different outputs can be sampled from the distribution defined for a given latent code.

Input
↓
Encoder-defined distribution
↓ Sample
Latent code
↓
Decoder-defined distribution
↓ Sample
Reconstructed output
Enter fullscreen mode Exit fullscreen mode

Why Stochastic Encoding Alone Is Not Enough

Stochastic representations allow a model to capture different variations of data. However, randomness alone does not make an autoencoder a useful generative model. To generate meaningful data without an input, the model must learn a latent space from which suitable codes can be selected.

A Variational Autoencoder (VAE) addresses this problem by combining the autoencoder architecture with probabilistic latent variable modeling and variational inference.

Takeaway

Reconstruction is the direct training objective of an autoencoder, while learning useful representations is the desired outcome. Low reconstruction loss alone does not guarantee meaningful features, so latent dimensionality, model capacity, and training constraints must be considered together.

Originally published at zeromathai.com.

Original article: https://zeromathai.com/en/encoder-decoder-autoencoder-course-en/

Top comments (0)