Module contents
Lesson 4 of 28Core 85 min

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

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.

InteractivePCA and an MLP autoencoder on the Swiss roll

Gray points are test data; overlaid reconstructions use the same rotation and scale. Each segment connects a point to its reconstruction.

  • Test point
  • Reconstruction: autoencoder MLP
Mean squared error per coordinate on test
  • PCA
  • Autoencoder MLP
  • Autoencoder analítico

Noiseless Swiss roll with seed 19: 720 training points and 180 test points, centered and scaled using training statistics. PCA is fitted on those data. Each MLP is trained for 2500 Adam steps, with batches of 192; this comparison is a short run, not a guarantee across architectures or seeds. The analytic reference knows the parameterization: it encodes radius and, with dimension 2, height too; the decoder reconstructs the spiral with sine and cosine. With dimension 1 it fixes mean height, and with dimension 3 it uses identity. We draw 72 test points; error uses all 180. Segments join all three measured dimensions.

2
Reconstruction
25°
PCA: test error
0.2632
MLP autoencoder: test error
0.0831
Analytic autoencoder: test error
0.0000
Compare latent dimensions and reconstructions in a short run with independent evaluation. The analytical solution that knows the parameterization is only a reference.

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 d≥Dd\ge D and networks have sufficient capacity to represent f(x)=xf(x)=x and g(z)=zg(z)=z 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 r∗(y)=E[X∣Y=y]r^*(y)=\E[X\mid Y=y], provided the second moment exists. This follows by decomposing conditional error into variance plus ∥r(y)−E[X∣Y=y]∥2\|r(y)-\E[X\mid Y=y]\|^2. 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.

InteractiveA reconstruction field
  • Spiral data
  • 0.35 × displacement
  • Iterations
  • Starting point

The neural DAE is a residual 2 → 64 → 2 network with tanh activation, trained here with a fixed seed, fresh noise per batch and backpropagation. Changing σ restarts training, split into chunks to keep the interface interactive. Time depends on device. Arrows show 0.35 times the displacement; the orange point shows repeated application.

The optimal control is the exact posterior mean of the 100 empirical points under that noise: its displacement is exactly σ² times the score of the smoothed Gaussian mixture. The network is an approximation and may fail, especially far from data or with little noise. Validation uses 400 fresh corruptions of the same points, not held-out clean data. Iterating the network does not guarantee projection or sampling from the distribution.

Field
0.30
4
Browser training0 / 6000 steps
Selected field displacementtraining
Exact smoothed score norm8.113
Change the noise level and observe reconstruction displacements. The figure identifies its model and distribution; compare its field with the smoothed score.

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 PXP_X be a distribution with finite first moment and σ>0\sigma>0. Its convolution with a Gaussian has a positive smooth density pσ(y)=∫φσ(y−x) dPX(x)p_\sigma(y)=\int\varphi_\sigma(y-x)\,dP_X(x). Differentiating under the integral,

∇ypσ(y)=∫−y−xσ2φσ(y−x) dPX(x).\nabla_y p_\sigma(y)=\int -\frac{y-x}{\sigma^2}\varphi_\sigma(y-x)\,dP_X(x).

Dividing by pσ(y)p_\sigma(y) turns the integral into a posterior expectation. Therefore, exactly for the optimal squared-error predictor,

r∗(y)−y=σ2∇ylog⁡pσ(y).r^*(y)-y=\sigma^2\nabla_y\log p_\sigma(y).

The identity uses the smoothed score and remains meaningful if PXP_X 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 r∗r^*; it does not equal it by definition.

To relate this to the score of an original density pp, assume pp is positive near yy, that pp and the necessary derivatives are continuous and that expansion terms can be integrated under a dominating bound. Write pσ(y)=E[p(y−σε)]p_\sigma(y)=\E[p(y-\sigma\varepsilon)]. A multivariable Taylor expansion, zero mean and E[εεT]=I\E[\varepsilon\varepsilon^\mathsf T]=I give pσ(y)=p(y)+(σ2/2)Δp(y)+o(σ2)p_\sigma(y)=p(y)+(\sigma^2/2)\Delta p(y)+o(\sigma^2) under sufficient regularity. Applying the same argument to ∇p\nabla p yields ∇pσ(y)→∇p(y)\nabla p_\sigma(y)\to\nabla p(y). Since p(y)>0p(y)>0, the ratio converges to ∇log⁡p(y)\nabla\log p(y) and

r∗(y)−y=σ2∇log⁡p(y)+o(σ2).r^*(y)-y=\sigma^2\nabla\log p(y)+o(\sigma^2).

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 g∘fg\circ f. 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 v∈{−1,1}Dv\in\{-1,1\}^D with independent equally likely components. Since E[vvT]=I\E[vv^\mathsf T]=I,

Ev∥Jf(x)v∥2=tr⁡(JfTJf)=∥Jf(x)∥F2.\E_v\|J_f(x)v\|^2=\operatorname{tr}(J_f^\mathsf T J_f)=\|J_f(x)\|_F^2.

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

InteractiveExploring the latent space
  • 0
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
Decoding at current position

Points and weights come from a short 2D-bottleneck autoencoder run on MNIST. The plot shows 1000 codes from 6000 training examples, not the full distribution. The image uses 256 intensity levels. Distance is to those codes, not an image quality measure or proof that a point is impossible.

Latent coordinates(9.25, 7.02)
Distance to nearest displayed code0.00
Label of that code7
Compare code occupancy with decoded images in different regions. A straight-line interpolation can pass through regions unconstrained by training.

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 ZZ is chosen and g(Z)g(Z) 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.

[ ]Spiral dataBrowser
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 h=tanh⁡(yW1+b1)h=\tanh(yW_1+b_1) and r(y)=y+hW2+b2r(y)=y+hW_2+b_2, the derivative of mean loss per example with respect to the output is 2(r−x)/B2(r-x)/B. The backward pass propagates through the second matrix and 1−h21-h^2. The function returns both parameters and final observed batch loss: that loss measures training, not quality on new data.

[ ]MLP and manual backpropagationBrowser
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 σ\sigma defines an explicit density. Its score at yy is the weighted mean of (xi−y)/σ2(x_i-y)/\sigma^2, 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.

[ ]Compare the field with the KDE scoreBrowser
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 σ\sigma 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 [0,1][0,1]. 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.

[ ]Convolutional autoencoder, denoising and latent spaceLocal GPU
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()
This cell needs the local lab (PyTorch with your GPU). Start it with 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

ProofFrom denoising to the score
Prove: Under the regularity and positivity assumptions of this lesson, prove the small-noise limit for the optimal DAE.
0
Let Y = X + σε, where ε is independent standard normal and pσ is the density of Y.

Step 1 of 3. Which function minimizes conditional squared error?

NumericCounting bits
A 28×28 image uses 8 bits per pixel and its code contains 32 float16 values. Ignoring decoder and metadata costs, what is the ratio of image bits to code bits?
QuizA perfect reconstruction
An overcomplete autoencoder obtains nearly zero training reconstruction error. Which diagnosis is justified?
CodeJacobian probes
Implement 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):
  pass
Shift+Enter to run
Key idea

Reconstruction 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.