11 / 34 · Evaluation
LPIPS
A distance between two images that follows what people see. LPIPS compares unit-normalised deep features layer by layer, with channel weights fitted to human judgements, so a small shift counts little and blur a lot.
On this page 8
Take a photo and make two copies. Shift the first one pixel to the right; blur the second slightly. To a person the shifted copy is the same picture and the blurred one is visibly worse. The mean squared error between pixels says the opposite.
IS and FID score whole sets of images. Many questions are about one pair: how close is a super-resolved image to the original, a VAE reconstruction to its input, a generated sample to its nearest training image? For those we need a distance between two images that agrees with people. LPIPS, Learned Perceptual Image Patch Similarity (Zhang et al., 2018), is the standard one.
Why not compare pixels?#
The obvious distance is pixelwise, the mean squared error over all values:
Make the opening example concrete with an image of vertical stripes of period 4, so every row reads 0 0 1 1 0 0 1 1. Shifted right by one pixel, wrapping around, every row becomes 1 0 0 1 1 0 0 1. Blurred with the kernel , also wrapping around, every row becomes .25 .25 .75 .75 .25 .25 .75 .75.
| Copy | Squared error per pixel | MSE | To a person |
|---|---|---|---|
| shifted | 1 on half the pixels, 0 elsewhere | the same picture | |
| blurred | on every pixel | visibly worse |
MSE calls the blurred copy times closer to the original. A shift moves every edge pixel to a different value; a blur moves every pixel a little and none a lot.
Pixel MSE punishes a shift and forgives a blur
The same arithmetic explains why networks trained with an MSE loss produce blurry outputs (Mathieu, Couprie and LeCun, 2016). The prediction that minimises the expected squared error is the conditional mean: for a fixed input and any guess , adding and subtracting the mean of the plausible answers gives , smallest at . So when several sharp answers are plausible, the best guess under MSE is their average, a blur. It is one cause of the blurry VAE samples.
A perceptual distance should forgive small shifts and punish lost structure. Deep features come closer to this. A convolutional network responds to edges, textures and parts, and its deeper layers summarise each neighbourhood on a coarse grid, so a one-pixel shift moves their responses only slightly, while blur removes the edges they respond to.
The algorithm#
- Pass both images through the same frozen, pretrained convolutional network, AlexNet or VGG, and take the feature maps of several layers.
- At every spatial position of every layer, divide the feature vector by its length across the channels.
- Subtract the two normalised maps, scale each channel of the difference by a learned weight, square, and average over positions: one number per layer.
- Sum over the layers.
How LPIPS compares two images
The weights are the only learned part. The network stays frozen, and only one non-negative weight per channel is fitted to human judgements; Zhang et al. call this the lin configuration. The judgements come from their BAPPS dataset of two-alternative forced choices: people saw a reference patch of pixels and two distorted versions of it, and picked the one that looked closer.
The formula#
Layer produces a feature map with channels on an grid. Write for the feature vector at position and a hat for its unit-normalised version:
The reference implementation adds to the norm, so a zero vector after a ReLU stays zero (Zhang, 2021). With the difference of the normalised features at each position and a weight vector ,
where multiplies element by element (Zhang et al., 2018, Eq. 1). The package stores non-negative weights on the squared channel differences, ; this is the same formula with .
Each piece has a job. Normalisation removes the overall size of the activations, so only the direction of the feature vector is compared: which channels respond, and in what proportion. Without the weights the term is a cosine distance in disguise. For unit vectors at angle ,
The weights then turn up the channels that matter for perception and turn down the rest. The spatial average makes layers with different grid sizes comparable. Skipping it leaves a map of where two images differ, which the package returns when created with spatial=True.
A toy layer#
The toy layer below has channels on a grid, so each feature vector is an arrow, and weights . Two positions carry almost all of the distance.
At the bottom right the two vectors point along channel 1 and channel 2. Post-ReLU features are non-negative, so the dot product of two of them is a sum of non-negative products, the cosine is at least 0, and is the largest possible angle, and unweighted the term is . The difference of the unit vectors is ; the weights make it , and the term is . In the centre the directions differ by : unweighted the term would be , and the weight on channel 2 lowers it to . The other seven positions nearly agree, and the average of the nine terms is .
Inside one layer: from two feature maps to the number dₗ
Does it agree with people?#
The test is the held-out part of BAPPS: for each triplet, does the metric pick the same distorted patch as most people? A perfect metric cannot reach 100%, because people disagree among themselves; averaged over all six test sets, a single person agrees with the majority 73.9% of the time (Zhang et al., 2018, Section 4.1). Every row of the table is the same six-set average.
| Metric | Agreement with people |
|---|---|
| on pixels | 63.2% |
| SSIM | 63.1% |
| unweighted features of supervised networks | 67.0–68.9% |
| one person | 73.9% |
Most of the gain comes from the deep features themselves, before any weight is learned; the paper’s title calls it their unreasonable effectiveness. The learned weights add little on top, and mostly on the kind of distortions they were trained on. Over all six sets they take AlexNet from 68.9% to 69.8%. Split by subset, they raise it from 76.8% to 78.7% on the two sets of the distortion types they were trained on, and only from 65.0% to 65.3% on the four sets of outputs of real algorithms (Appendix A, Table 5). These subset numbers are not comparable with the 73.9% of the table: on the same subsets a single person reaches 82.6% and 69.5%.
Where it is used#
LPIPS compares a generated or restored image with its reference: super-resolution, inpainting, editing, and reconstructions of autoencoders. In each case a pixel metric would reward the blurry average.
It measures diversity. For a conditional generator, the average LPIPS between pairs of outputs sampled for the same input says how different the outputs are (Zhu et al., 2017). Zhu et al. calibrate it against random pairs of real images, about 0.26 in their map-to-satellite task, and warn that a high score can also mean meaningless variation from unnatural images.
It screens for copies. Searching the training set for the LPIPS-nearest neighbours of each generated sample surfaces candidate copies that FID cannot see. A small distance is not proof of copying, and a search that finds nothing is not an audit: inspect the candidates, and report which part of the training set was searched and the threshold.
It is a training loss. LPIPS is differentiable, so it can replace or complement MSE in training, in the spirit of earlier feature-space losses (Johnson, Alahi and Fei-Fei, 2016). The autoencoders of VQGAN and latent diffusion, later in the course, train with a perceptual loss of this kind to keep reconstructions sharp.
Where it breaks#
LPIPS is a network, and it inherits the weaknesses of networks. Small adversarial perturbations of an image, invisible to people, can make its LPIPS scores contradict human judgement dramatically (Kettunen, Härkönen and Lehtinen, 2019). Anything optimised against LPIPS, such as a generator trained with it as a loss, can drift toward such perturbations; a second, independent metric or a look at the images catches it.
The shift tolerance is partial. Early layers still see the pixel grid, so LPIPS reacts to misalignments too small for people to notice (Ghildyal and Liu, 2022). Two images that differ by a sub-pixel shift are not at distance 0.
Its scale is a convention. AlexNet and VGG backbones give different values, so scores are comparable only with the same backbone, the same version of the learned weights and the same input range, for the reference package. It was fitted on patches, so on whole images it averages local judgements and knows nothing about global composition. And every comparison costs a forward pass through a deep network.
What you should remember#
- Pixel MSE calls a one-pixel shift worse than a blur; the stripe example gives a factor of 8.
- , with features unit-normalised over channels.
- Without weights each term is ; the weights are the only part fitted to people.
- Deep features alone lift agreement with people from 63% to about 68%, against 74% for a person.
- IS and FID judge sets; LPIPS judges pairs: references, copies, diversity, and as a loss.
- It is fooled by adversarial perturbations and depends on the backbone and the input range.
Code#
The stripe example and the toy layer, in NumPy. layer_distance is the formula for one layer.
import numpy as np
row = np.array([0, 0, 1, 1, 0, 0, 1, 1], float)
img = np.tile(row, (8, 1))
shifted = np.roll(img, 1, axis=1)
blurred = (np.roll(img, 1, axis=1) + 2 * img + np.roll(img, -1, axis=1)) / 4
print('MSE shifted', ((img - shifted) ** 2).mean(), ' MSE blurred', ((img - blurred) ** 2).mean())
def layer_distance(fx, fy, w): # fx, fy: [H, W, C] feature maps; w: [C]
nx = fx / (np.linalg.norm(fx, axis=-1, keepdims=True) + 1e-10)
ny = fy / (np.linalg.norm(fy, axis=-1, keepdims=True) + 1e-10)
return float((((nx - ny) * w) ** 2).sum(-1).mean())
polar = lambda deg: np.stack([np.cos(np.radians(deg)), np.sin(np.radians(deg))], -1)
angle = np.array([[20, 35, 50], [10, 30, 60], [0, 25, 0]]) # direction of phi(x) per position
turn = np.array([[5, -10, 0], [15, 40, 5], [0, -5, 90]]) # how far phi(x') turns away
print('d_l =', round(layer_distance(polar(angle), 1.7 * polar(angle + turn), np.array([1, 0.6])), 2))
MSE shifted 0.5 MSE blurred 0.0625
d_l = 0.2
The factor 1.7 rescales one map and changes nothing, because the features are normalised before they are compared.
Notebook#
The metrics notebook of the HSE-LAMBDA Deep Generative Models course holds the hands-on part of the evaluation block. Cell numbers count every cell, markdown included, from 1; quoted numbers come from the run saved with the course.
- The formula (cell 7) is written as above, with the layer sum outside.
- A nearest-neighbour search (cells 10–15) takes the first FashionMNIST image, an ankle boot, and computes
lpips.LPIPS(net='alex')to 1,000 images drawn with replacement undernp.random.seed(10), each resized to . In the saved run the nine nearest images are all ankle boots, at distances from 0.168 to 0.220, with a per-class histogram of distances beside them. - The inputs break the package’s contract. Each image enters as a grayscale tensor with values 0–255 instead of (for example
normalize=Trueon images in ), so the distances are not comparable with published LPIPS values, and the ranking is unvalidated until rerun with correct scaling. - Two automatic checks (cell 16) require the smallest distance to be below 0.2 and more than 90% of the nine nearest images to share the query’s label, which means all nine.
Next#
IS, FID and LPIPS give one number each. None of them says whether a model fails by producing implausible images or by leaving out part of the data, and FID mixes the two. The next note separates them with precision and recall.
References#
- R. Zhang, P. Isola, A. A. Efros, E. Shechtman, O. Wang. The unreasonable effectiveness of deep features as a perceptual metric. CVPR, 2018. Section 2: the BAPPS dataset; Section 3 and Eq. (1): the metric and the lin configuration; Section 4.1: agreement with people; Appendix A, Table 5: full results.
- R. Zhang. PerceptualSimilarity, reference implementation of LPIPS (
lpipspackage v0.1.4, weights v0.1), 2021. Input range , , weights on squared channel differences,spatial=True. - M. Mathieu, C. Couprie, Y. LeCun. Deep multi-scale video prediction beyond mean square error. ICLR, 2016. Blurry predictions under an MSE loss.
- J.-Y. Zhu, R. Zhang, D. Pathak, T. Darrell, A. A. Efros, O. Wang, E. Shechtman. Toward multimodal image-to-image translation. NeurIPS, 2017. Section 5: average pairwise LPIPS as a diversity score.
- J. Johnson, A. Alahi, L. Fei-Fei. Perceptual losses for real-time style transfer and super-resolution. ECCV, 2016.
- M. Kettunen, E. Härkönen, J. Lehtinen. E-LPIPS: robust perceptual image similarity via random transformation ensembles. arXiv, 2019. Adversarial attacks on LPIPS.
- A. Ghildyal, F. Liu. Shift-tolerant perceptual similarity metric. ECCV, 2022.
- HSE-LAMBDA, Deep Generative Models course repository:
metrics.ipynb.