Autoencoders: compression, noise and the geometry of data
Extend the linear autoencoder (PCA) to nonlinear encoders and decoders and study why reconstruction alone is insufficient. Investigate the identity trap, contractive and sparse regularization, denoising autoencoders and their relation to the score of a smoothed density, and latent holes that motivate VAEs.
After this lesson you can
- Train MLP and convolutional autoencoders and diagnose transposed-convolution artifacts.
- Explain why an unregularized overcomplete autoencoder can learn the identity.
- Use a Taylor expansion to derive the small-noise score approximation for an optimal DAE.
- Implement a contractive penalty using random Jacobian-vector products.
- Investigate latent holes experimentally and explain their effect on sampling.
Before you start
- 19The generative modeling problemLow-dimensional supports and divergence degeneracy
- 12Linear autoencoder and principal subspacet-distributed stochastic neighbor embeddingUMAP objective
- 00Canonical training and evaluation loop
- 15Output layer and loss pairing
- 16Transposed convolutionU-Net and skip connections
- 03Multivariable Taylor theorem
Compression and generation
An autoencoder takes an image, compresses it and attempts to reconstruct it. If its representation has few coordinates, it may discover regularities that preserve the essentials. But the same loss allows solutions that do not resemble understanding: with sufficient capacity a network can copy its input. Convincing reconstruction of observed images does not determine what happens at an arbitrary latent coordinate.
Linear autoencoders and PCA provide a starting point: for centered data, squared loss and limited rank, the principal subspace provides an optimal linear reconstruction. That result depends on its assumptions; a nonlinear network does not automatically inherit a global-optimum guarantee or a unique representation. A nonlinear bottleneck can represent curved structure, but optimization difficulty and the evaluation set matter as much as dimension.
The figure uses a short reproducible run on a noiseless synthetic Swiss roll: PCA and networks with different bottlenecks were fitted on training data and evaluated on held-out points. The analytical model also shown knows the data parameterization and serves as a reference, not a learned result. The seed, samples and reconstructions are preserved alongside the figure code; a different run can change MLP errors.
A lower-dimensional latent is not by itself a complete measure of compression. Count the precision of every coordinate, shared decoder parameters and, when encoding a collection, how their cost is amortized. Evaluate error on held-out images at the application’s scale. The output and loss pairing matters: sigmoid output with Bernoulli loss and real-valued output with squared error model different assumptions.
When the identity appears
If and networks have sufficient capacity to represent and in the region of interest, the identity is a zero-squared-error solution. The optimizer is not guaranteed to find it, nor are all minima identical: it is an available solution that weakens the reconstruction task. Even a narrow bottleneck can memorize a finite dataset with sufficient capacity without learning a representation that generalizes.
A useful test combines training and evaluation error with perturbations: does reconstruction remove noise, retain semantic changes and respond reasonably outside observed examples? If the output reproduces noise too, low loss does not demonstrate stable learned structure. Adding a corruption task changes what must be predicted.
Learning to undo noise
The best reconstruction for each observed input is the conditional mean , provided the second moment exists. This follows by decomposing conditional error into variance plus . It is not necessarily projection onto the nearest point of a manifold: if several regions explain the noisy observation, the mean can fall between them. Iterating a learned reconstruction does not guarantee convergence or sampling from the data distribution.
The interactive trains a small network in the browser on an empirical spiral and compares its displacements with the optimal predictor for that same smoothed distribution. The reference is computed from posterior averages, not another network: it is a mathematical control rather than an independent measure of generalization. Evaluation corruptions are new, although applied to the same clean spiral points. The network can depart from the optimum, especially at low noise; that difference is part of the result.
The exact smoothed-score identity
Let be a distribution with finite first moment and . Its convolution with a Gaussian has a positive smooth density . Differentiating under the integral,
Dividing by turns the integral into a posterior expectation. Therefore, exactly for the optimal squared-error predictor,
The identity uses the smoothed score and remains meaningful if is an empirical measure or concentrated on a curve. The original measure may have no Lebesgue density, as in the support problem. A finite network trained for finite time approximates ; it does not equal it by definition.
To relate this to the score of an original density , assume is positive near , that and the necessary derivatives are continuous and that expansion terms can be integrated under a dominating bound. Write . A multivariable Taylor expansion, zero mean and give under sufficient regularity. Applying the same argument to yields . Since , the ratio converges to and
Alain and Bengio study the derivation and its limits. The result does not say every arrow of a trained model points perpendicular to a manifold or that small noise gives easy-to-learn gradients. The figure and lab compare model error with the score of a particular smoothed distribution.
Regularizing changes
Penalizing the encoder Jacobian differs from penalizing the Jacobian of the entire reconstruction . The former limits representation sensitivity, but the decoder can amplify changes. Total loss balances reconstruction and regularization: a constant encoder is highly contractive but usually reconstructs poorly. Sparse autoencoders reappear in interpretability, where a useful representation must also be distinguished from an identifiable explanation.
To estimate the norm without constructing the entire Jacobian, take with independent equally likely components. Since ,
The mean of several probes is unbiased under those assumptions but has variance. If the penalty participates in training, the Jacobian-vector product must retain the differentiation graph with respect to parameters. On a small network, compare with the explicit Jacobian before using an estimate on a large model.
Exploring a space without a prior
The figure uses weights and codes from an MLP trained in a short MNIST run. The reproducible data generator and training behind the PCA comparison are in this lesson’s widget folder. Distance to the nearest observed code helps locate sparsely represented regions, but is not a visual-quality metric and does not prove all empty points produce invalid images. The codes shown are a training sample, not the full dataset.
A deterministic decoder does define a generative distribution if a prior is chosen and is taken as a pushforward measure. Reconstruction alone does not specify that prior or ensure its samples land in regions the decoder learned to interpret. Fitting a Gaussian to the codes is one possible choice, not a guarantee of realism. Nearest-code distance or occupancy can diagnose unsupported regions; comparing an unpaired sample with an arbitrary image by MSE does not measure its generative quality.
VAEs introduce a latent distribution and an objective relating inference, prior and reconstruction. Before reaching them, measure what a deterministic autoencoder does, including failures, rather than declaring every intermediate point must resemble a valid image.
Architectures and artifacts
A convolutional decoder can increase resolution using a transposed convolution. With stride 2 and kernel 3, positions receive different numbers of contributions: in one dimension overlap alternates between one and two, and the two-dimensional product can amplify the imbalance. This encourages checkerboard patterns, although weights and architecture determine the outcome. Odena, Dumoulin and Olah analyze uneven overlap; choosing a kernel divisible by stride removes that particular geometric source but does not guarantee all artifacts disappear. Another option resizes first and then applies a convolution; compare images and spatial errors, not just a global mean.
Lab: a DAE with manual backward pass
Generate a clean two-dimensional spiral and split before training. The following MLP has one tanh hidden layer and predicts a displacement added to the noisy input. The identity connection can initially represent a reconstruction close to identity, but the objective remains predicting the clean point. Weights are fitted manually by gradient descent, without autograd. Each noise level gets a new network and reproducible sequence; evaluation data do not update it.
import numpy as np
def spiral(n, seed):
rng = np.random.default_rng(seed)
t = rng.uniform(0.5*np.pi, 4*np.pi, n)
return np.column_stack((t*np.cos(t), t*np.sin(t))) / (4*np.pi)
clean_train = spiral(800, 21)
clean_test = spiral(300, 22)
print('Formas de entrenamiento y evaluación:', clean_train.shape, clean_test.shape)With and , the derivative of mean loss per example with respect to the output is . The backward pass propagates through the second matrix and . The function returns both parameters and final observed batch loss: that loss measures training, not quality on new data.
def train_dae(clean, sigma, seed, steps=700, width=24, batch=64, lr=0.025):
rng = np.random.default_rng(seed)
w1 = rng.normal(0, 0.2, (2, width))
w2 = rng.normal(0, 0.02, (width, 2))
b1 = np.zeros(width)
b2 = np.zeros(2)
for step in range(steps):
target = clean[rng.integers(0, len(clean), batch)]
noisy = target + sigma*rng.normal(size=target.shape)
h = np.tanh(noisy @ w1 + b1)
reconstruction = noisy + h @ w2 + b2
error = reconstruction - target
delta = 2*error/batch
grad_w2 = h.T @ delta
grad_b2 = delta.sum(axis=0)
hidden_delta = (delta @ w2.T) * (1-h*h)
grad_w1 = noisy.T @ hidden_delta
grad_b1 = hidden_delta.sum(axis=0)
w1 -= lr*grad_w1
b1 -= lr*grad_b1
w2 -= lr*grad_w2
b2 -= lr*grad_b2
return (w1, b1, w2, b2), np.mean(np.sum(error*error, axis=1))
def reconstruct(y, parameters):
w1, b1, w2, b2 = parameters
return y + np.tanh(y @ w1 + b1) @ w2 + b2
models = {}
for sigma in (0.15, 0.3, 0.5):
models[sigma], last_loss = train_dae(clean_train, sigma, seed=31)
print('σ:', sigma, 'última pérdida de lote:', round(float(last_loss), 4))Gaussian KDE with training centers and bandwidth equal to defines an explicit density. Its score at is the weighted mean of , with weights proportional to each kernel. We calculate it with log-sum-exp; it is not a magical estimator of the unsmoothed score of a singular curve. The comparison uses noisy evaluation points and the smoothed empirical model built from training. Discrepancy may arise from capacity, optimization, finite samples or the KDE describing a different empirical distribution from the one generating test data.
def kde_score(points, centers, sigma):
delta = centers[None, :, :] - points[:, None, :]
log_weight = -np.sum(delta*delta, axis=2)/(2*sigma*sigma)
log_weight -= log_weight.max(axis=1, keepdims=True)
weights = np.exp(log_weight)
weights /= weights.sum(axis=1, keepdims=True)
return np.sum(weights[:, :, None]*delta, axis=1)/(sigma*sigma)
test_rng = np.random.default_rng(44)
for sigma in (0.15, 0.3, 0.5):
y = clean_test + sigma*test_rng.normal(size=clean_test.shape)
displacement = reconstruct(y, models[sigma]) - y
target_field = sigma*sigma*kde_score(y, clean_train, sigma)
error = np.mean(np.sum((displacement-target_field)**2, axis=1))
mse_noisy = np.mean(np.sum((y-clean_test)**2, axis=1))
mse_recon = np.mean(np.sum((reconstruct(y, models[sigma])-clean_test)**2, axis=1))
print('σ:', sigma, 'error de campo:', round(float(error), 4),
'MSE ruido:', round(float(mse_noisy), 4), 'MSE reconstrucción:', round(float(mse_recon), 4))Do not assume field error decreases monotonically as changes: the objective, displacement scale and optimization difficulty change too. To evaluate direction, compare dot products or angles only where both fields have appreciable norm; near zero, angles are unstable. The comparison above reports full squared error and reconstruction on separate data.
Local lab: convolutional autoencoders and latent holes
Train two autoencoders with the same architecture and official Fashion-MNIST split: one reconstructs clean images and the other reconstructs clean images from Gaussian noise clipped to . Compare reconstruction errors on clean test data and an independent reproducible corruption. Then fit a multivariate Gaussian to training codes and compare their distance to training codes with the distance of test codes. Euclidean distance measures occupancy in these coordinates, not realism or perceptual quality.
The full run uses 20 epochs per model. For a short check, set ORYON_QUICK=1 before starting Python: it uses fewer examples and one epoch, so it does not measure full-run quality. UMAP visualization requires umap-learn in the lab environment. If unavailable, or if ORYON_SKIP_UMAP=1 is set, PCA is shown as an identified alternative; PCA is not UMAP and can conceal or distort structure. Data download to ORYON_DATA_ROOT or ./data. Reconstructions and samples are generated in the run.
import os
from pathlib import Path
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, Subset
from torchvision import datasets, transforms
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
quick = os.environ.get('ORYON_QUICK') == '1'
root = Path(os.environ.get('ORYON_DATA_ROOT', './data'))
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
epochs = 1 if quick else 20
batch_size = 64 if quick else 128
latent_dim = 16
sigma = 0.3
seed = 91
torch.manual_seed(seed)
np.random.seed(seed)
if device.type == 'cuda':
torch.cuda.manual_seed_all(seed)
train_all = datasets.FashionMNIST(root, train=True, download=True,
transform=transforms.ToTensor())
test_all = datasets.FashionMNIST(root, train=False, download=True,
transform=transforms.ToTensor())
train = Subset(train_all, range(512)) if quick else train_all
test = Subset(test_all, range(256)) if quick else test_all
class ConvAE(nn.Module):
def __init__(self, latent):
super().__init__()
self.encoder_conv = nn.Sequential(
nn.Conv2d(1, 16, 4, stride=2, padding=1), nn.ReLU(),
nn.Conv2d(16, 32, 4, stride=2, padding=1), nn.ReLU(),
nn.Flatten(), nn.Linear(32*7*7, latent))
self.decoder_input = nn.Linear(latent, 32*7*7)
self.decoder_conv = nn.Sequential(
nn.ConvTranspose2d(32, 16, 4, stride=2, padding=1), nn.ReLU(),
nn.ConvTranspose2d(16, 1, 4, stride=2, padding=1), nn.Sigmoid())
def encode(self, x):
return self.encoder_conv(x)
def decode(self, z):
x = self.decoder_input(z).reshape(-1, 32, 7, 7)
return self.decoder_conv(x)
def forward(self, x):
return self.decode(self.encode(x))
def corrupt(x, generator):
noise = torch.randn(x.shape, generator=generator, dtype=x.dtype)
return (x + sigma*noise).clamp(0, 1)
def train_model(denoising):
torch.manual_seed(seed)
if device.type == 'cuda':
torch.cuda.manual_seed_all(seed)
model = ConvAE(latent_dim).to(device)
order_rng = torch.Generator().manual_seed(seed + 1)
noise_rng = torch.Generator().manual_seed(seed + 2)
loader = DataLoader(train, batch_size=batch_size, shuffle=True,
generator=order_rng, num_workers=0)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
model.train()
for epoch in range(epochs):
sum_error = count = 0
for images, _ in loader:
inputs = corrupt(images, noise_rng) if denoising else images
target = images.to(device)
optimizer.zero_grad(set_to_none=True)
reconstruction = model(inputs.to(device))
loss = (reconstruction - target).square().mean()
loss.backward()
optimizer.step()
sum_error += loss.item()*target.numel()
count += target.numel()
print('con ruido' if denoising else 'limpio', 'época', epoch + 1,
'MSE entrenamiento por píxel:', round(sum_error/count, 5))
return model
@torch.no_grad()
def evaluate(model):
model.eval()
noise_rng = torch.Generator().manual_seed(122)
clean_sum = noisy_sum = count = 0
for images, _ in DataLoader(test, batch_size=batch_size, shuffle=False, num_workers=0):
target = images.to(device)
clean_sum += (model(target) - target).square().sum().item()
noisy_sum += (model(corrupt(images, noise_rng).to(device)) - target).square().sum().item()
count += target.numel()
return clean_sum/count, noisy_sum/count
@torch.no_grad()
def collect_codes(model, data, maximum, sample_seed):
model.eval()
rng = torch.Generator().manual_seed(sample_seed)
indices = torch.randperm(len(data), generator=rng)[:min(maximum, len(data))].tolist()
loader = DataLoader(Subset(data, indices), batch_size=batch_size, shuffle=False, num_workers=0)
codes, labels = [], []
for x, y in loader:
codes.append(model.encode(x.to(device)).cpu())
labels.append(y)
return torch.cat(codes), torch.cat(labels)
print('Dispositivo:', device, '| prueba corta:', quick)
clean_model = train_model(False)
noise_model = train_model(True)
for name, model in [('limpio', clean_model), ('denoising', noise_model)]:
clean_mse, noisy_mse = evaluate(model)
print(name, 'test limpio MSE/píxel:', round(clean_mse, 5),
'| test con ruido MSE/píxel:', round(noisy_mse, 5))
# El ajuste y la comparación siguientes usan solo el autoencoder limpio.
codes, labels = collect_codes(clean_model, train, 4000, 10)
test_codes, test_labels = collect_codes(clean_model, test, 1000, 11)
mean = codes.mean(dim=0)
centered = codes - mean
covariance = centered.T @ centered / (len(codes)-1)
factor = torch.linalg.cholesky(covariance + 1e-5*torch.eye(latent_dim))
draw_rng = torch.Generator().manual_seed(12)
gaussian = mean + torch.randn(test_codes.shape, generator=draw_rng) @ factor.T
test_distance = torch.cdist(test_codes, codes).min(dim=1).values
gaussian_distance = torch.cdist(gaussian, codes).min(dim=1).values
print('Distancia latente al vecino de entrenamiento, mediana: test',
round(test_distance.median().item(), 4), '| gaussiana',
round(gaussian_distance.median().item(), 4))
# El ajuste se aprende solo con entrenamiento; transformamos test y la gaussiana.
if os.environ.get('ORYON_SKIP_UMAP') != '1':
try:
import umap
except ImportError:
umap = None
else:
umap = None
if umap is None:
projector = PCA(n_components=2).fit(codes.numpy())
projection_name = 'PCA (UMAP no disponible o desactivado)'
else:
projector = umap.UMAP(n_components=2, n_neighbors=15, random_state=17, n_jobs=1).fit(codes.numpy())
projection_name = 'UMAP'
print('Proyección:', projection_name)
train_2d = projector.transform(codes.numpy())
test_2d = projector.transform(test_codes.numpy())
gaussian_2d = projector.transform(gaussian.numpy())
fig, ax = plt.subplots(figsize=(6, 5))
classes = ax.scatter(train_2d[:, 0], train_2d[:, 1], c=labels.numpy(), s=4,
alpha=0.4, cmap='tab10', vmin=-0.5, vmax=9.5)
fig.colorbar(classes, ax=ax, ticks=np.arange(10), label='Clase')
ax.scatter(test_2d[:, 0], test_2d[:, 1], s=7, alpha=0.4, c='black', label='códigos test')
ax.scatter(gaussian_2d[:, 0], gaussian_2d[:, 1], s=7, alpha=0.4, c='red', label='gaussiana')
ax.set_title(projection_name + ': proyección ajustada en entrenamiento')
ax.legend()
plt.show()
# Interpolación de dos imágenes de test y decodificación de muestras gaussianas.
examples = torch.stack([test[i][0] for i in (0, 1)]).to(device)
with torch.no_grad():
z0, z1 = clean_model.encode(examples)
alpha = torch.linspace(0, 1, 8, device=device)[:, None]
interpolated = clean_model.decode((1-alpha)*z0 + alpha*z1).cpu()
random_images = clean_model.decode(gaussian[:8].to(device)).cpu()
n_compare = min(64, len(test_codes))
reference = torch.stack([train[i][0] for i in range(min(256, len(train)))]).flatten(1)
decoded_test = clean_model.decode(test_codes[:n_compare].to(device)).cpu().flatten(1)
decoded_gaussian = clean_model.decode(gaussian[:n_compare].to(device)).cpu().flatten(1)
test_nn = (torch.cdist(decoded_test, reference).min(dim=1).values / np.sqrt(784)).square()
gaussian_nn = (torch.cdist(decoded_gaussian, reference).min(dim=1).values / np.sqrt(784)).square()
print('MSE por píxel al vecino de referencia más próximo, mediana:')
print('test decodificado:', round(test_nn.median().item(), 5),
'| gaussiana decodificada:', round(gaussian_nn.median().item(), 5))
fig, axes = plt.subplots(2, 8, figsize=(12, 3))
for j in range(8):
axes[0, j].imshow(interpolated[j, 0], cmap='gray', vmin=0, vmax=1)
axes[1, j].imshow(random_images[j, 0], cmap='gray', vmin=0, vmax=1)
for row in range(2):
axes[row, j].axis('off')
fig.text(0.02, 0.73, 'Interpolación', rotation=90, va='center')
fig.text(0.02, 0.27, 'Gaussiana', rotation=90, va='center')
plt.show()
del clean_model, noise_model
if device.type == 'cuda':
torch.cuda.empty_cache()npm run lab and open the connection link.The neighbor comparison describes code geometry and depends on scale; a high value or isolated UMAP projection does not prove a decoded image is invalid. Pixel distance compares both decoded groups with the same training subset: it measures proximity to that reference, not reconstruction MSE or realism. A blurry image can have small distance. The images allow inspection of interpolation and the Gaussian, but judging generalization or realism requires further evaluation. There is no corresponding original for each Gaussian sample, so reconstruction MSE is not reported for them. Kernel 4 with stride 2 avoids uneven overlap due to kernel size; learned weights can still produce checkerboard artifacts.
Exercises
Step 1 of 3. Which function minimizes conditional squared error?
contractive_penalty(encoder, x, n_probes). x has shape (B, D) and the encoder acts independently per row. Use independent Rademacher probes of the same shape, Jacobian-vector products with torch.autograd.functional.jvp and create_graph=True; return the mean over probes and examples of the sum of squared outputs. Raise ValueError if n_probes is less than 1.import torch
def contractive_penalty(encoder, x, n_probes):
passReconstruction constrains the decoder only where encoded data exist. Under Gaussian noise and squared loss, the optimal DAE follows the score of the smoothed distribution; a trained network approximates it with measurable error. Generating from a latent also requires a distribution over it and an evaluation of its samples.