Autoencoders: what does reconstruction teach the code?
自编码器
Train a rank-one encoder and decoder, compare with the PCA optimum and expose latent-scale ambiguity and off-subspace failure.
autoencodersStart with the problem
An autoencoder learns to reconstruct its input through an intermediate code. The copied output is usually a means to shape that code. If the model can simply implement the identity, perfect reconstruction may teach little about useful compression or downstream prediction.
Hinton and Salakhutdinov study deep nonlinear dimensionality reduction. Deep Learning Chapter 14 distinguishes undercomplete and regularized autoencoders. We start with the smallest trainable linear bottleneck: two input coordinates, one latent scalar, and two reconstructed coordinates. Its optimum can be checked by singular values.
Definitions and derivation
Use centered input rows so no bias is needed. The encoder vector a maps x to a scalar, and the decoder vector b maps the scalar back to the input space:
The factor 1/(2n) means half the mean squared Euclidean reconstruction error per example. It is not the mean per coordinate. The encoder and decoder are untied: both learn independently. For residual eᵢ=bzᵢ−xᵢ, the chain rule gives:
The program updates a and b simultaneously using gradients at the old parameter values. Updating a first and recomputing the decoder gradient with the new encoder would define a different optimization step. There are four trainable parameters and no hidden training framework.
All reconstructions lie in the one-dimensional span of b. For a centered data matrix X, the best rank-one reconstruction retains its leading singular direction. The encoder–decoder product can realize this projection, so the singular-value residual gives the optimum:
The same equation highlights a non-uniqueness: scale the latent code by any nonzero λ and inversely scale the decoder, and reconstruction is identical. Thus recovering a good reconstruction subspace does not identify a unique code scale or a unique human-readable coordinate. A sign flip is another member of this family. Nonlinear models have additional ambiguities.
Our six centered points mostly lie on the line x₂=x₁, with two small points on the perpendicular line. Their squared singular values are 20 and 0.16, giving optimal loss 0.16/12=0.013333333…. This is an exact finite-data certificate for this linear rank-one problem. Nonlinear encoders and decoders can represent curved manifolds, but their optimum is not generally PCA, and training need not find a global solution.
Run the calculation
Complete Python 3.12 / NumPy 1.26.4 program:
import numpy as np
def data():return np.array([[-2.,-2],[-1,-1],[1,1],[2,2],[-.2,.2],[.2,-.2]])
def loss_grad(x,encoder,decoder):
x,a,b=[np.asarray(v,dtype=float) for v in (x,encoder,decoder)]
if x.ndim!=2 or len(x)==0 or a.shape!=(x.shape[1],) or b.shape!=a.shape or not all(np.isfinite(v).all() for v in (x,a,b)):raise ValueError('Use finite rows and matching rank-one encoder/decoder vectors.')
z=x@a;error=np.outer(z,b)-x;loss=float(np.sum(error**2)/(2*len(x)))
return loss,x.T@(error@b)/len(x),error.T@z/len(x)
def train(steps=1200):
x=data();a=np.array([.4,.1]);b=np.array([.2,.3]);start=loss_grad(x,a,b)[0]
for _ in range(steps):loss,ga,gb=loss_grad(x,a,b);a-=.1*ga;b-=.1*gb
return a,b,start,loss_grad(x,a,b)[0]
if __name__ == '__main__':
x=data();a,b,start,end=train();_,singular,vt=np.linalg.svd(x,full_matrices=False);optimal=singular[1]**2/(2*len(x));print('training loss',round(start,9),round(end,9),'PCA lower bound',round(float(optimal),9));print('encoder / decoder',a.round(9).tolist(),b.round(9).tolist())
original=np.outer(x@a,b);changed=np.outer(x@(10*a),b/10);print('latent scale ratio',10,'reconstruction discrepancy',float(np.max(np.abs(original-changed))))
held=np.array([[1.,-1]]);error=np.linalg.norm(np.outer(held@a,b)-held)**2;print('unseen orthogonal point squared error',round(float(error),9),'identity-map training loss',0.)
Actual output:
training loss 1.290894667 0.013334462 PCA lower bound 0.013333333
encoder / decoder [0.720621949, 0.707431392] [0.70030585, 0.700201565]
latent scale ratio 10 reconstruction discrepancy 2.220446049250313e-16
unseen orthogonal point squared error 2.000167883 identity-map training loss 0.0
After 1,200 gradient steps, loss falls from 1.290894667 to 0.013334462, close to but above the certified optimum. The encoder is not exactly aligned yet, so do not round this into a claim of an exact optimum. Scaling the encoder by ten and dividing the decoder by ten preserves reconstruction within floating-point error.
For the unseen point (1,−1), squared reconstruction error is about 2.000167883: its direction was weakly represented in training and mostly discarded by the rank-one projection. This is a deliberately chosen diagnostic point, not an independent statistical test set. An identity map has zero training reconstruction loss but uses no bottleneck at all. Neither observation establishes downstream classification quality.
For n examples in d dimensions and a rank-k linear code, dense full-batch work is O(ndk), with O(dk) parameters; storing codes costs O(nk). The example uses k=1. A higher-capacity nonlinear model may memorize a finite training set even through a narrow code, so bottleneck dimension alone is not a complete capacity control.
When the method fails
A useful reconstruction objective needs a suitable input metric. Squared error emphasizes large-amplitude directions, as this example shows. Centering, feature scaling and the relative weight of different modalities affect what the code preserves.
Denoising, sparsity and contractive penalties impose different constraints and deserve separate treatment. A variational autoencoder adds a probabilistic latent-variable objective; an ordinary deterministic autoencoder is not automatically a normalized generative model. To claim anomaly detection or useful embeddings, evaluate those tasks directly with appropriate splits and baselines rather than using training reconstruction alone.
Exercises with answers
- What is the exact rank-one lower bound here?
Answer 1: The discarded squared singular value divided by 2n: 0.16/12.
- Does the trained program attain it exactly?
Answer 2: No. The reported loss remains slightly above the bound after 1,200 updates.
- Why does multiplying the encoder by ten preserve reconstruction after compensation?
Answer 3: The decoder is divided by ten, leaving their product and every reconstructed point unchanged.
- Why is zero identity-map loss not sufficient evidence of useful compression?
Answer 4: The identity map passes all input coordinates directly and has no compressed bottleneck.
Sources and next steps
Deep Learning Chapter 14 opening and Section 14.1, printed pages 499–501, define encoding/decoding, undercomplete reconstruction, the PCA connection and capacity caveats. Hinton–Salakhutdinov’s physical page 1, printed page 504, introduces deep nonlinear dimensionality reduction; the downloaded journal page also contains an unrelated neighboring article, which is not used. Our linear gradients and singular-value certificate are original worked calculations. Continue with representation learning and denoising autoencoders.
Make a prediction, then check
What remains unchanged under reciprocal encoder/decoder scaling?
Learning objectives
- Derive and test both encoder and decoder gradients.
- Compare training with the rank-one optimum without assuming unique latent coordinates.
Prerequisites & connections
Explore related knowledge →References
- Deep Learning — Chapter 14: Autoencoders
Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016 - Reducing the Dimensionality of Data with Neural Networks
Geoffrey E. Hinton; Ruslan R. Salakhutdinov · 2006
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.
- Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
- Four focused CPython 3.12.4 tests passed per chapter, including independent finite differences, literal calculations, recurrence and convolution comparisons, permutation symmetry, closed-form limits and expressive counterexamples. All eight programs use NumPy 1.26.4. CPU teaching calculations, not framework or GPU benchmarks.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Deep Learning — Chapter 14: Autoencoders · Chapter 14 opening and Section 14.1, printed pages 499–501: reconstruction, undercomplete code, linear/PCA relationship and capacity warning.
- Reducing the Dimensionality of Data with Neural Networks · Physical page 1, printed Science page 504: Hinton–Salakhutdinov article title, authors and nonlinear encoder introduction; unrelated neighboring article excluded.
Related topics