Lesson 3.1 — Representation & Autoencoders
Representation learning · data and internal features
A representation expresses data in some space; a feature is a usable attribute within it; an embedding typically maps discrete or structured objects into vectors. A latent variable is an unobserved generating factor, whereas a latent code is the internal coordinate learned by a model—the two need not coincide.
01 · Feature Representation Explorer
Compressing observations is not the same as identifying a minimal state realization. Low reconstruction error does not guarantee observability, Markovianity, or task-relevant control information.
Latent space · intrinsic dimension and manifolds
For example, points on a circle live in ambient space ℝ² and are generated by a
single angle t ∈ [0, 2π), yet the full circle cannot be covered globally and
continuously by one real coordinate without a seam. Low-dimensional manifolds are useful geometric
hypotheses, not universal theorems. Without extra constraints, latent coordinates can be rotated,
scaled, or nonlinearly reparameterized while keeping reconstruction identical.
PCA · projection, covariance & SVD
Suppose two joint sensors usually rise and fall together, and you can transmit just one number per reading. Choose a line through the mean of the training readings. The encoder sends the signed distance along that line to the projected point. The decoder uses that distance to place the point back in the two-sensor plane.

Each dark dot is an original reading. Each open circle is what the decoder reconstructs. The orange segment joins the two. On the left the code retains only sensor 1. On the right it combines both sensors, using the same one-number budget. Points that project to the same circle become indistinguishable to the decoder.
For a reading , training mean and unit direction , the encoder and decoder are
The projection makes a right triangle. Its hypotenuse is the centered reading, one leg has length , and the other is the orange reconstruction gap. The squared hypotenuse stays fixed as the line rotates. Keeping more squared length along the line therefore leaves less squared error perpendicular to it.
The leading eigenvector of maximizes the retained variance . Equivalently, take the leading right singular vector of the centered matrix with one sample per row. Its sign can flip: the encoder then sends , and the decoder still reconstructs exactly the same point. If the largest eigenvalue is repeated, several directions are equally good.
Rotate the reconstruction line and compare it with the fitted direction
02 · PCA Projection & Reconstruction
03 · Eigenvalue & Explained Variance Inspector
The squared distances use the units of the chosen coordinates. Standardizing sensors before PCA changes how errors in each sensor are weighted. Fit the centering and any scaling on training data and reuse them at inference. Computing the SVD directly avoids forming a covariance matrix, which squares the condition number on the nonzero spectrum.
Encoder–decoder · network and tensor shapes
Nonlinear hidden layers can learn curved reconstruction manifolds. A bottleneck
k < D constrains capacity, though noise or sparsity constraints also work. The
final decoder layer uses a linear output because standardized sensor values can be positive or
negative without fixed bounds.
04 · Encoder–Decoder Forward Player (2 → 2 → 1 → 2)
Autoencoder objective · bottleneck and reconstruction error
If the decoder and encoder are linear (no activations) on centered data under squared error with
k < D at the global optimum, the optimal reconstruction subspace matches PCA,
though the learned weights need not be orthogonal eigenvectors. Note that 6:k is a
coordinate-count ratio, not a byte-level compression ratio.
05 · Bottleneck Dimension Explorer (Illustrative 6D Spectrum)
Latent space geometry · interpolation and distance
Latent distance does not equal original-space distance. Interpolation does not guarantee physical feasibility or high training-data density, and a plain autoencoder has no explicit prior distribution from which to sample new realistic data (VAEs are covered in Lesson 5.1).
06 · Latent Space Interpolation
Denoising autoencoder · robust reconstruction
Under squared error, the optimal predictor given a noisy input is the conditional expectation
E[x | x̃] (connecting directly to Lesson 2.5). Denoising performance depends on the
noise assumption—real robot sensors exhibit correlated temporal drift, bias, and occlusion.
07 · Denoising Autoencoder Training Targets
Engineering Lab · Robot Sensor Compression
Default PyTorch single-configuration result (k=2, seed=3, 200 Adam
updates): PCA validation reconstruction MSE is 0.386719 vs. AE
0.042538, whereas frozen linear-probe state prediction MSE is
0.037368 for PCA vs. 0.095527 for AE. Lower reconstruction error does
not automatically mean better downstream task prediction.
08 · Live Autoencoder Training (6 → 10 → k → 10 → 6)
Complete PyTorch implementation (robot_sensor_autoencoder.py)
import math
import torch
from torch import nn
torch.set_default_dtype(torch.float64)
torch.set_num_threads(1)
def rng(seed):
x = seed & 0xffffffff
def rand():
nonlocal x
x = (1664525 * x + 1013904223) & 0xffffffff
return x / 4294967296
return rand
def dataset(n, seed):
r = rng(seed)
rows, labels = [], []
for _ in range(n):
x, u = 4 * r() - 2, 2 * r() - 1
rows.append([x, math.sin(2 * x), math.cos(2 * x), x * x / 2, u, math.sin(x + u)])
labels.append(0.65 * x + 0.5 * math.sin(2 * x) + 0.35 * u)
return torch.tensor(rows), torch.tensor(labels)
def add_noise(x, noise, seed):
r = rng(seed)
eps = [math.sqrt(-2 * math.log(max(r(), 1e-15))) * math.cos(2 * math.pi * r()) for _ in range(x.numel())]
return x + noise * torch.tensor(eps).reshape_as(x)
class AE(nn.Module):
def __init__(self, k, seed):
super().__init__()
self.encoder = nn.Sequential(nn.Linear(6, 10), nn.Tanh(), nn.Linear(10, k))
self.decoder = nn.Sequential(nn.Linear(k, 10), nn.Tanh(), nn.Linear(10, 6))
r = rng(seed + 2000)
with torch.no_grad():
for layer in [self.encoder[0], self.encoder[2], self.decoder[0], self.decoder[2]]:
layer.weight.copy_(torch.tensor([0.8 * (r() - 0.5) for _ in range(layer.weight.numel())]).reshape_as(layer.weight))
layer.bias.zero_()
def forward(self, x):
return self.decoder(self.encoder(x))
def probe(z, y, zv, yv):
z = torch.cat([torch.ones(len(z), 1), z], 1)
zv = torch.cat([torch.ones(len(zv), 1), zv], 1)
reg = 0.01 * torch.eye(z.shape[1])
reg[0, 0] = 0
w = torch.linalg.solve(z.T @ z + reg, z.T @ y)
return ((zv @ w - yv) ** 2).mean().item()
def run(seed=3, k=2, noise=0.0, lr=0.02, epochs=200):
x, y = dataset(120, seed)
xv, yv = dataset(60, seed + 1000)
mu, sd = x.mean(0), x.std(0, correction=0) + 1e-8
x, xv = (x - mu) / sd, (xv - mu) / sd
center = x.mean(0)
xc = x - center
_, s, vh = torch.linalg.svd(xc, full_matrices=False)
W = vh[:k].T
zp, zpv = xc @ W, (xv - center) @ W
pca_mse = ((zpv @ W.T + center - xv) ** 2).mean().item()
pca_probe = probe(zp, y, zpv, yv)
xt, xvt = add_noise(x, noise, seed + 3000), add_noise(xv, noise, seed + 4000)
model = AE(k, seed)
opt = torch.optim.Adam(model.parameters(), lr=lr)
hist = []
for t in range(epochs + 1):
if t % 10 == 0 or t == epochs:
with torch.no_grad():
hist.append(dict(t=t, tr=((model(xt) - x) ** 2).mean().item(), va=((model(xvt) - xv) ** 2).mean().item()))
if t == epochs:
break
opt.zero_grad()
loss = nn.functional.mse_loss(model(xt), x)
loss.backward()
opt.step()
with torch.no_grad():
ae_probe = probe(model.encoder(x), y, model.encoder(xv), yv)
return model, hist, dict(pca_mse=pca_mse, pca_probe=pca_probe, ae_probe=ae_probe, raw_probe=probe(x, y, xv, yv), ae_mse=hist[-1]["va"])
if __name__ == "__main__":
for noise in [0.0, 0.35]:
_, hist, metrics = run(noise=noise)
print("noise", noise, "initial", hist[0]["tr"], "final", hist[-1]["tr"], metrics)