You've trained a model to enlarge an image, and its prediction error is low, but the fur and edges in the output look blurred. Several detailed images could match the low-resolution input, so an average of them may score well while looking disappointing. Perceptual loss compares features of the images as well as their pixels. This changes what the model is encouraged to preserve.
Pixel MSE is minimised by the conditional mean. If several textures fit an input, that mean blends them into blur. We train a super-resolution model using feature loss, keeping a pixel term alongside it, so the objective also rewards the edges and textures represented by a pretrained network.
Both the generated image and target pass through a pretrained classifier, here VGG-16. Comparing early-layer features rewards similar edges and textures, while deeper layers describe larger structures. The classifier stays fixed during training; gradients through its features update the generator.
We build the loss and super-resolution model in PyTorch, train on Oxford-IIIT Pet images and compare the reconstructed details with pixel-loss output.
Let's Build It
Click the badge to run the full training pipeline on a free Colab GPU:
Here is the complete pipeline. We downsample pet images to create low-resolution inputs, then train a U-Net to reconstruct the originals using perceptual loss from a pretrained VGG-16 network.
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models import vgg16_bn, VGG16_BN_Weights
from torchvision import transforms
from torch.utils.data import Dataset, DataLoader
from pathlib import Path
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
import os, random
device = torch.device('cuda' if torch.cuda.is_available()
else 'mps' if torch.backends.mps.is_available()
else 'cpu')
# --- Dataset: crappify high-res images ---
def download_pets():
"""Download Oxford-IIIT Pet images."""
url = "https://www.robots.ox.ac.uk/~vgg/data/pets/data/images.tar.gz"
data_dir = Path("data/pets/images")
if data_dir.exists() and len(list(data_dir.glob("*.jpg"))) > 100:
return data_dir
os.makedirs("data/pets", exist_ok=True)
import urllib.request, tarfile
tar_path = "data/pets/images.tar.gz"
if not Path(tar_path).exists():
print("Downloading Oxford-IIIT Pet dataset...")
urllib.request.urlretrieve(url, tar_path)
with tarfile.open(tar_path) as tar:
tar.extractall("data/pets")
return data_dir
class SuperResDataset(Dataset):
"""Pairs of (low-res JPEG, high-res) images."""
def __init__(self, image_paths, hr_size=128, lr_size=64, quality=60):
self.paths = image_paths
self.hr_size = hr_size
self.lr_size = lr_size
self.quality = quality
self.to_tensor = transforms.ToTensor()
self.normalise = transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]
)
def __len__(self):
return len(self.paths)
def __getitem__(self, idx):
img = Image.open(self.paths[idx]).convert('RGB')
# High-res target: center-crop and resize
w, h = img.size
s = min(w, h)
img = img.crop(((w - s) // 2, (h - s) // 2,
(w + s) // 2, (h + s) // 2))
hr = img.resize((self.hr_size, self.hr_size), Image.LANCZOS)
# Low-res input: downsample + JPEG compression
lr = hr.resize((self.lr_size, self.lr_size), Image.BILINEAR)
lr = lr.resize((self.hr_size, self.hr_size), Image.BILINEAR)
hr_t = self.normalise(self.to_tensor(hr))
lr_t = self.normalise(self.to_tensor(lr))
return lr_t, hr_t
# --- Perceptual (Feature) Loss ---
class FeatureLoss(nn.Module):
"""Perceptual loss using VGG-16 features + Gram matrix style loss."""
def __init__(self):
super().__init__()
vgg = vgg16_bn(weights=VGG16_BN_Weights.DEFAULT).features
vgg.eval()
for p in vgg.parameters():
p.requires_grad = False
# Feature extraction points: just before each MaxPool
block_ends = [i - 1 for i, m in enumerate(vgg)
if isinstance(m, nn.MaxPool2d)]
# Use blocks 3, 4, 5 (indices 22, 32, 42)
self.ids = block_ends[2:5]
self.wts = [5.0, 15.0, 2.0]
# Build sequential sub-networks for each block
self.blocks = nn.ModuleList()
prev = 0
for idx in self.ids:
self.blocks.append(nn.Sequential(*list(vgg.children())[prev:idx + 1]))
prev = idx + 1
def get_features(self, x):
feats = []
for block in self.blocks:
x = block(x)
feats.append(x)
return feats
@staticmethod
def gram(x):
n, c, h, w = x.shape
x = x.view(n, c, -1)
return (x @ x.transpose(1, 2)) / (c * h * w)
def forward(self, pred, target):
loss = F.l1_loss(pred, target) # pixel loss
pred_f = self.get_features(pred)
with torch.no_grad():
targ_f = self.get_features(target)
for pf, tf, w in zip(pred_f, targ_f, self.wts):
loss += F.l1_loss(pf, tf) * w
loss += F.l1_loss(self.gram(pf), self.gram(tf)) * w ** 2 * 5e3
return loss
# --- U-Net with ResNet34 encoder ---
class UNetBlock(nn.Module):
def __init__(self, in_ch, out_ch):
super().__init__()
self.up = nn.Upsample(scale_factor=2, mode='bilinear',
align_corners=False)
self.conv = nn.Sequential(
nn.Conv2d(in_ch, out_ch, 3, padding=1, bias=False),
nn.BatchNorm2d(out_ch), nn.ReLU(inplace=True),
nn.Conv2d(out_ch, out_ch, 3, padding=1, bias=False),
nn.BatchNorm2d(out_ch), nn.ReLU(inplace=True),
)
def forward(self, x, skip):
x = self.up(x)
if x.shape != skip.shape:
x = F.interpolate(x, size=skip.shape[2:])
x = torch.cat([x, skip], dim=1)
return self.conv(x)
class SuperResUNet(nn.Module):
"""U-Net with a frozen ResNet34 encoder."""
def __init__(self):
super().__init__()
from torchvision.models import resnet34, ResNet34_Weights
enc = resnet34(weights=ResNet34_Weights.DEFAULT)
self.enc0 = nn.Sequential(enc.conv1, enc.bn1, enc.relu) # 64ch
self.enc1 = nn.Sequential(enc.maxpool, enc.layer1) # 64ch
self.enc2 = enc.layer2 # 128ch
self.enc3 = enc.layer3 # 256ch
self.enc4 = enc.layer4 # 512ch
self.dec4 = UNetBlock(512 + 256, 256)
self.dec3 = UNetBlock(256 + 128, 128)
self.dec2 = UNetBlock(128 + 64, 64)
self.dec1 = UNetBlock(64 + 64, 64)
self.final = nn.Sequential(
nn.Upsample(scale_factor=2, mode='bilinear',
align_corners=False),
nn.Conv2d(64, 3, 3, padding=1),
)
def forward(self, x):
e0 = self.enc0(x) # /2
e1 = self.enc1(e0) # /4
e2 = self.enc2(e1) # /8
e3 = self.enc3(e2) # /16
e4 = self.enc4(e3) # /32
d4 = self.dec4(e4, e3)
d3 = self.dec3(d4, e2)
d2 = self.dec2(d3, e1)
d1 = self.dec1(d2, e0)
return self.final(d1)
# --- Training ---
data_dir = download_pets()
all_imgs = sorted([p for p in data_dir.glob("*.jpg")])
random.seed(42)
random.shuffle(all_imgs)
split = int(0.9 * len(all_imgs))
train_ds = SuperResDataset(all_imgs[:split], hr_size=128, lr_size=64)
valid_ds = SuperResDataset(all_imgs[split:], hr_size=128, lr_size=64)
train_dl = DataLoader(train_ds, batch_size=16, shuffle=True, num_workers=2)
valid_dl = DataLoader(valid_ds, batch_size=16, num_workers=2)
model = SuperResUNet().to(device)
loss_fn = FeatureLoss().to(device)
opt = torch.optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-3)
scheduler = torch.optim.lr_scheduler.OneCycleLR(
opt, max_lr=1e-3, epochs=10, steps_per_epoch=len(train_dl))
for epoch in range(10):
model.train()
total = 0
for lr_img, hr_img in train_dl:
lr_img, hr_img = lr_img.to(device), hr_img.to(device)
pred = model(lr_img)
loss = loss_fn(pred, hr_img)
opt.zero_grad()
loss.backward()
opt.step()
scheduler.step()
total += loss.item()
print(f"Epoch {epoch+1:2d} | loss {total/len(train_dl):.4f}")

You just trained a super-resolution model that produces sharper images than pixel MSE alone could ever achieve. Now let's understand why.
What Just Happened?
The code above has three components that work together: a crappification pipeline, a U-Net generator, and a perceptual loss function. The loss function is the key innovation, so let's start there.
The crappification pipeline
We take high-resolution pet images and deliberately degrade them. Each image is centre-cropped to a square, resized to 128x128 (the target), then downsampled to 64x64 and bilinearly upsampled back to 128x128 (the input). The upsampled version is blurry and missing fine detail. The model's job is to recover that detail.
This approach comes from the fast.ai course, where Jeremy Howard called it "crappification." The idea is general: whatever degradation you want to reverse (noise, compression artefacts, low resolution), apply it to clean images and train a model to undo it.
The FeatureLoss class
This is where the magic happens. Instead of comparing output and target pixel by pixel, we pass both through a frozen VGG-16 network (pretrained on ImageNet) and compare their intermediate feature maps.
class FeatureLoss(nn.Module):
def __init__(self):
super().__init__()
vgg = vgg16_bn(weights=VGG16_BN_Weights.DEFAULT).features
vgg.eval()
for p in vgg.parameters():
p.requires_grad = False
block_ends = [i - 1 for i, m in enumerate(vgg)
if isinstance(m, nn.MaxPool2d)]
self.ids = block_ends[2:5] # layers 22, 32, 42
self.wts = [5.0, 15.0, 2.0] # weight each block differently
Why VGG-16? It was pretrained to classify 1,000 categories of objects, so its internal features know what "fur texture," "eye shape," and "nose" look like. We hook into the ReLU activations before the 3rd, 4th, and 5th max-pooling layers. These capture features at different scales:
- Block 3 (layer 22): edges, simple textures, colour gradients
- Block 4 (layer 32): complex textures, repeated patterns, object parts
- Block 5 (layer 42): high-level semantic content, object identity

The loss computation has three terms:
def forward(self, pred, target):
loss = F.l1_loss(pred, target) # pixel loss
pred_f = self.get_features(pred)
with torch.no_grad():
targ_f = self.get_features(target)
for pf, tf, w in zip(pred_f, targ_f, self.wts):
loss += F.l1_loss(pf, tf) * w # feature loss
loss += F.l1_loss(self.gram(pf),
self.gram(tf)) * w ** 2 * 5e3 # style loss
return loss
Pixel L1 loss: the baseline. Ensures broad colour agreement between output and target.
Feature L1 loss: compares activation maps at each VGG layer. If the target has a sharp edge at position (10, 15) in layer 32, the prediction must also produce a sharp edge there. This is weighted by
[5, 15, 2]because the middle layers (complex textures) matter most for visual quality.Gram matrix (style) loss: captures texture statistics independent of spatial position. The Gram matrix of a feature map is the inner product of its channels, measuring which features tend to activate together. Matching Gram matrices means "produce the same kind of texture" without requiring pixel-perfect alignment. The
w**2 * 5e3scaling makes this term significant despite Gram matrices being small numbers.
The Gram matrix
The Gram matrix of a feature map with channels and spatial dimensions is:
where is the feature map reshaped to . Each entry measures the correlation between channels and . If channels detecting "horizontal edges" and "orange colour" are correlated in the target, the model learns to produce images where orange things also have horizontal edges (like a tabby cat's stripes).
@staticmethod
def gram(x):
n, c, h, w = x.shape
x = x.view(n, c, -1)
return (x @ x.transpose(1, 2)) / (c * h * w)

The U-Net generator
The generator is a U-Net with a ResNet34 encoder. The encoder (the downsampling path) extracts features at 5 scales. The decoder upsamples back to the original resolution using bilinear interpolation and skip connections that concatenate encoder features with decoder features.
Skip connections are essential. Without them, the decoder would have to reconstruct fine spatial detail from a compressed bottleneck. With them, the decoder receives both high-level "what to generate" signals from the bottleneck and low-level "where to put it" signals from the encoder.
We use a pretrained ResNet34 encoder because it already knows how to extract useful features from images. Only the decoder is learned from scratch. This is the same transfer learning principle we applied to text: start with a model that understands the domain, then fine-tune for your specific task.
Going Deeper
Why pixel MSE produces blurry images
Consider a patch of fur that, depending on the exact lighting and angle, could look like any of several textures. The ground-truth pixel value at position (50, 50) might be 180 in one training image and 220 in another image of the same breed in the same pose. What value minimises the expected MSE? The mean: 200. And that mean is not any real texture. It is a blend, which our visual system perceives as blur.
Formally, MSE optimisation solves:
The optimal predictor under MSE is the conditional mean of the target distribution. When that distribution is multimodal (multiple plausible textures), the mean falls between the modes, producing an output that matches none of them.
Perceptual loss sidesteps this by operating in feature space. VGG features are more tolerant of small spatial shifts but less tolerant of wrong textures. A slightly shifted but sharp texture has low perceptual loss; a perfectly positioned but blurry smudge has high perceptual loss. This pushes the model toward sharp, realistic outputs even when the exact pixel alignment is imperfect.
The role of each loss term
The three loss terms serve complementary purposes:
| Term | What it measures | What it enforces | Typical magnitude |
|---|---|---|---|
| Pixel L1 | Per-pixel absolute difference | Correct colours, broad structure | 0.01 to 0.1 |
| Feature L1 | Activation difference at VGG layers | Correct edges, textures, semantics | 0.1 to 1.0 |
| Gram style | Texture statistics correlation | Realistic texture regardless of position | 0.001 to 0.01 |
The feature weights [5, 15, 2] and Gram scaling w**2 * 5e3 are from the fast.ai implementation by Jeremy Howard. The middle block (layer 32) gets the highest weight because it captures the "texture" level of abstraction, which is exactly what pixel MSE fails to preserve.
Connection to neural style transfer
Perceptual loss was introduced in the same 2016 moment as neural style transfer. Gatys et al. showed that you can transfer the "style" of a painting to a photograph by optimising an image to match the content features of the photo and the Gram matrix of the painting. Johnson et al. realised that instead of optimising per image (slow), you could train a feed-forward network with the same loss function (fast). The per-image optimisation takes minutes; the trained network runs in milliseconds.
Our super-resolution model uses exactly this insight. The "content" target is the high-res image (matched via feature L1). The "style" target is also the high-res image (matched via Gram matrices). The result is an upscaled image that has both the right content and the right texture statistics.
Hyperparameters from the original code
These values come from the fast.ai lesson 7 notebooks (Jeremy Howard's implementation):
- Encoder: ResNet34 pretrained on ImageNet
- VGG layers: blocks 3, 4, 5 (indices 22, 32, 42 in
vgg16_bn.features) - Feature weights:
[5.0, 15.0, 2.0] - Gram scaling:
weight**2 * 5e3 - Base loss: L1 (not MSE, because L1 is less sensitive to outliers)
- Learning rate: 1e-3 with one-cycle schedule
- Weight decay: 1e-3
- Batch size: 32 at 128px (we use 16 for broader GPU compatibility)
- Crappification: JPEG quality 60, bilinear downsampling to 96px (we simplify to 64px)
- Training: 10 epochs with
fit_one_cycle, then progressive resizing to 256px
The original fast.ai code uses progressive resizing: train at 128px first, then increase to 256px. This lets the model learn coarse structure quickly before refining fine detail. Our code implements the 128px stage; extend to 256px by changing hr_size=256 and lr_size=128 and training for another 10 epochs.
When not to use perceptual loss
Perceptual loss is not universally better than pixel loss. There are cases where pixel accuracy matters more than perceptual quality:
- Medical imaging: a radiologist needs pixel-accurate reconstructions, not "realistic-looking" ones that might hallucinate lesions
- Satellite imagery: small pixel-level details (rooftops, vehicles) are the signal, not the background texture
- Compression: if you need bit-exact reconstruction, any loss that operates in a different space introduces irreversible distortion
For these applications, pixel MSE (often combined with SSIM) remains the standard. Perceptual loss is best when human visual quality is the primary metric.
Where This Comes From
Perceptual loss for image transformation was introduced by Justin Johnson, Alexandre Alahi, and Li Fei-Fei in their 2016 paper "Perceptual Losses for Real-Time Style Transfer and Super-Resolution." The paper was a direct response to the observation that per-pixel losses produce blurry results, and the concurrent discovery by Gatys et al. that VGG features could capture perceptual similarity.
The key mathematical formulation defines the feature reconstruction loss as:
where is the activation of the -th layer of a pretrained network (VGG-16), and are the dimensions of that feature map. The style reconstruction loss uses Gram matrices:
where is the Gram matrix.
"We combine the benefits of both approaches, and propose the use of perceptual loss functions for training feed-forward transformation networks. We show that replacing per-pixel loss functions with perceptual loss functions... gives qualitatively better results." -- Johnson, Alahi, and Fei-Fei (2016)
The paper showed 4x super-resolution results that were dramatically sharper than SRCNN (Dong et al. 2014), which used pixel MSE. The improvement was so clear that perceptual loss quickly became the standard for image generation tasks.
The fast.ai implementation by Jeremy Howard (lesson 7 of Practical Deep Learning for Coders, 2019) extended Johnson's approach with several practical improvements: using VGG-16 with batch normalisation for more stable features, adding Gram matrix style loss for texture quality, using a U-Net architecture instead of the residual network in the original paper, and applying progressive resizing from low to high resolution.
Since 2016, perceptual loss has become a building block of modern generative models. SRGAN (Ledig et al. 2017) combined it with adversarial training for photo-realistic super-resolution. ESRGAN (Wang et al. 2018) refined the architecture and training. Even modern diffusion models like Stable Diffusion use perceptual loss as one component of their training objective.
Further reading
- The original paper: Johnson, Alahi, Fei-Fei (2016), "Perceptual Losses for Real-Time Style Transfer and Super-Resolution" (arXiv:1603.08155)
- Neural style transfer: Gatys, Ecker, Bethge (2015), "A Neural Algorithm of Artistic Style" (arXiv:1508.06576)
- SRGAN: Ledig et al. (2017), "Photo-Realistic Single Image Super-Resolution Using a Generative Adversarial Network" (arXiv:1609.04802)
- fast.ai course: Howard (2019), "Practical Deep Learning for Coders" Lesson 7: Super-resolution and image restoration
Interactive Tools
- 2D Convolution Visualizer: Watch the convolution operation powering VGG feature extraction, step by step with heatmap grids
- CNN Layer Visualizer: Includes
ConvTranspose2d, the upsampling layer in the U-Net decoder, and shows why its output size does not simply undo the strided convolution that shrank the image - Classification Metrics Calculator: Evaluate neural network predictions with confusion matrices and F1 scores
Related Posts
- Convolutional Neural Networks from Scratch: Builds the Conv2d operation we use inside both the U-Net encoder and the VGG feature extractor
- Batch Normalisation from Scratch: VGG-16 BN uses batch normalisation after every conv layer; this post explains why
- Optimisers: SGD, Momentum, and Adam from First Principles: We use Adam to train the U-Net; this post covers how it adapts per-parameter learning rates
- Learning Rate Scheduling: From Step Decay to One-Cycle: The one-cycle schedule we use during training and why it helps convergence
- Transfer Learning for Text: The same pretrained-encoder principle applied to NLP: start with a model that understands the domain, then fine-tune
- PCA and SVD: The Linear Algebra You Actually Need: The Gram matrix in our style loss is closely related to the covariance matrix in PCA
- Vision Transformers from Scratch in PyTorch: Transformer backbones for vision tasks, an alternative to the CNN encoders used here
- JEPA from Scratch: Predicting in Latent Space: Latent-space representation learning for vision, the self-supervised counterpart to our feature-space loss
- Channel Attention in PyTorch: Five Seeds, No Effect: Blocks that reweight a CNN's feature channels, tested on a small FashionMNIST network over five seeds









