Course contents 11 / 34

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 C×H×WC \times H \times W values:

MSE(x,x′)=1CHW∑c,h,w(xchw−xchw′)2.\mathrm{MSE}(x, x') = \frac{1}{CHW} \sum_{c, h, w} \big(x_{chw} - x'_{chw}\big)^2 .

Make the opening example concrete with an 8×88 \times 8 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 14[1  2  1]\frac14 [1\;2\;1], also wrapping around, every row becomes .25 .25 .75 .75 .25 .25 .75 .75.

CopySquared error per pixelMSETo a person
shifted1 on half the pixels, 0 elsewhere0.50.5the same picture
blurred0.252=0.06250.25^2 = 0.0625 on every pixel0.06250.0625visibly worse

MSE calls the blurred copy 0.5/0.0625=80.5 / 0.0625 = 8 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.

Figure

Pixel MSE punishes a shift and forgives a blur

Shifted versus blurred stripes under pixel MSEIn the middle, an 8 by 8 pixel image of vertical stripes, two columns of value 0 then two columns of value 1, repeated. On the left, the same image shifted right by one pixel: it looks the same, but its squared-error map against the original has half of the pixels at error 1, so the pixel MSE is 0.50, large. On the right, the image blurred with kernel 1 2 1 over 4: it looks worse, with grey values 0.25 and 0.75, but every pixel has squared error 0.0625, so the pixel MSE is 0.0625, small. Pixel MSE therefore ranks the blurred copy 8 times closer.shifted copyoriginal xblurred copyshift right 1 pxblur [1 2 1]/4looks the samelooks worsesquared error (x − x′)²squared error (x − x′)²MSE = 0.50large: half the pixels flipMSE = 0.0625small: each pixel off by 0.25error scale (√)01pixel MSE: blur is8× “closer”a perceptual metric should rank them the other wayShifted versus blurred stripes under pixel MSE (stacked)At the top, an 8 by 8 pixel image of vertical stripes. Below it, the image shifted right by one pixel next to its squared-error map: it looks the same but half the pixels have error 1, MSE 0.50. At the bottom, the blurred image next to its error map: it looks worse but every pixel has error 0.0625, MSE 0.0625. Pixel MSE ranks the blurred copy 8 times closer.original xshift right 1 pxblur [1 2 1]/4shifted copy(x − x′)²looks the sameMSE = 0.50largeblurred copy(x − x′)²looks worseMSE = 0.0625small: 0.0625 everywherepixel MSE: blur is 8× “closer”
Vertical stripes of period 4 on an 8 × 8 grid, a copy shifted one pixel right and a copy blurred with [1 2 1]/4, both wrapping around. The shift flips half the pixels, MSE = 0.50; the blur moves each by 0.25, MSE = 0.0625, 8 times less. Error maps use a square-root colour scale.

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 cc, adding and subtracting the mean mm of the plausible answers yy gives E(y−c)2=Var⁡y+(m−c)2\mathbb E (y - c)^2 = \operatorname{Var} y + (m - c)^2, smallest at c=mc = m. 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#

  1. Pass both images through the same frozen, pretrained convolutional network, AlexNet or VGG, and take the feature maps of several layers.
  2. At every spatial position of every layer, divide the feature vector by its length across the channels.
  3. Subtract the two normalised maps, scale each channel of the difference by a learned weight, square, and average over positions: one number per layer.
  4. Sum over the layers.
Figure

How LPIPS compares two images

LPIPS pipelineImage x at the top left and image x prime at the bottom left each enter a copy of the same frozen convolutional network, AlexNet or VGG, drawn as five layers. The two copies share weights. From each layer l the feature maps phi l of x and of x prime go to a comparison node d l between the two strips. The nodes d1 plus d2 plus d3 plus d4 plus d5 are added, which equals LPIPS of x and x prime. An inset below shows the steps inside every node d l: the feature maps of size C l by H l by W l are unit-normalised over channels, subtracted, multiplied channel-wise by the weights w l, which are learned from human perceptual judgements, squared and averaged over positions h, w, giving d l. Low LPIPS means the images look similar; high means the images differ in visible structure.frozen pretrained CNN (AlexNet / VGG), layers l = 1 … Lxx′sharedweightsconv1conv5conv1conv5feature maps φl of size Cl × Hl × Wl (deeper layers: coarser grids)d₁d₂d₃d₄d₅++++φ₁(x)φ₁(x′)=LPIPS(x, x′)low → looks similarhigh → differentvisible structuresum over layers Σlinside every node dl:φl(x), φl(x′)Cl × Hl × Wlunit-normaliseover channelssubtractφ̂l(x) − φ̂l(x′)⊙ wlweigh channelssquare ‖ · ‖²₂mean over (h, w)dllearned from human perceptual judgementsLPIPS pipeline (stacked)Image x on the left and image x prime on the right each go down through a copy of the same frozen convolutional network with five layers; the copies share weights. At every layer the feature maps of both images go to a comparison node d l in the middle. The nodes d1 to d5 are added, which equals LPIPS of x and x prime. A boxed inset at the bottom shows the steps inside every node d l: unit-normalise over channels, subtract, multiply channel-wise by w l (learned from human perceptual judgements), square, and average over positions h, w. Low LPIPS means the images look similar; high means the images differ in visible structure.xx′same frozen CNN(AlexNet / VGG)shared weightsd₁d₂d₃d₄d₅++++conv1conv1conv5conv5=LPIPS(x, x′)low → looks similarhigh → different visible structureinside every node dl:φl(x), φl(x′)Cl × Hl × Wlunit-normaliseover channelssubtractφ̂l(x) − φ̂l(x′)⊙ wlweigh channelssquare ‖ · ‖²₂mean over (h, w)dlwl learned from human perceptual judgements
Both images pass through the same frozen network. At each chosen layer the two feature maps are unit-normalised over channels, subtracted, weighted by the learned wₗ, squared and averaged over positions, giving one number dₗ; LPIPS sums them. Layer sizes are schematic: AlexNet's five layers have 64, 192, 384, 256 and 256 channels.

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 64×6464 \times 64 pixels and two distorted versions of it, and picked the one that looked closer.

The formula#

Layer ll produces a feature map φl(x)\varphi_l(x) with ClC_l channels on an Hl×WlH_l \times W_l grid. Write φl(x)hw∈RCl\varphi_l(x)_{hw} \in \mathbb R^{C_l} for the feature vector at position (h,w)(h, w) and a hat for its unit-normalised version:

φ^l(x)hw=φl(x)hw∥φl(x)hw∥2.\hat\varphi_l(x)_{hw} = \frac{\varphi_l(x)_{hw}}{\big\|\varphi_l(x)_{hw}\big\|_2} .

The reference implementation adds ε=10−10\varepsilon = 10^{-10} 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 wl∈RClw_l \in \mathbb R^{C_l},

Δl,hw=φ^l(x)hw−φ^l(x′)hw,dl(x,x′)=1HlWl∑h,w∥wl⊙Δl,hw∥22,LPIPS(x,x′)=∑ldl(x,x′),\begin{aligned} \Delta_{l, hw} &= \hat\varphi_l(x)_{hw} - \hat\varphi_l(x')_{hw} , \\ d_l(x, x') &= \frac{1}{H_l W_l} \sum_{h, w} \big\| w_l \odot \Delta_{l, hw} \big\|_2^2 , \\ \mathrm{LPIPS}(x, x') &= \sum_l d_l(x, x') , \end{aligned}

where ⊙\odot multiplies element by element (Zhang et al., 2018, Eq. 1). The package stores non-negative weights vl,cv_{l,c} on the squared channel differences, ∑cvl,cΔl,hw,c2\sum_c v_{l,c} \Delta_{l,hw,c}^2; this is the same formula with wl,c=vl,cw_{l,c} = \sqrt{v_{l,c}}.

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 θ\theta,

∥u^−v^∥22=∥u^∥22+∥v^∥22−2 u^⊤v^=2−2cos⁡θ.\begin{aligned} \|\hat u - \hat v\|_2^2 &= \|\hat u\|_2^2 + \|\hat v\|_2^2 - 2\,\hat u^\top \hat v \\ &= 2 - 2\cos\theta . \end{aligned}

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 Cl=2C_l = 2 channels on a 3×33 \times 3 grid, so each feature vector is an arrow, and weights wl=(1,0.6)w_l = (1, 0.6). 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 90°90° is the largest possible angle, and unweighted the term is 2−2cos⁡90°=22 - 2\cos 90° = 2. The difference of the unit vectors is (1,−1)(1, -1); the weights make it (1,−0.6)(1, -0.6), and the term is 1+0.36=1.361 + 0.36 = 1.36. In the centre the directions differ by 40°40°: unweighted the term would be 2−2cos⁡40°=0.472 - 2\cos 40° = 0.47, and the weight 0.60.6 on channel 2 lowers it to 0.340.34. The other seven positions nearly agree, and the average of the nine terms is dl=0.20d_l = 0.20.

Figure

Inside one layer: from two feature maps to the number dₗ

The four steps of one LPIPS layer distanceFour 3 by 3 grids connected by arrows. First: at every position a red feature vector of x and a blue feature vector of x prime, of different lengths. Second: both vectors normalised to unit length, reaching a quarter circle. Third: the difference of the unit vectors multiplied channel-wise by w_l = (1.0, 0.6); it is tiny almost everywhere, larger at the centre, and largest at the bottom-right position where the two directions differ by 90 degrees. Fourth: the squared lengths as a heat map with numbers, from 0.00 to 1.36. Their average over the nine positions is d_l = 0.20.featuresφl(x), φl(x′)unit-normaliseφ̂l(x), φ̂l(x′)subtract, weighwl ⊙ (φ̂ − φ̂′)square‖ · ‖²2 at each (h, w)0.000.020.000.030.340.010.000.001.36different lengthsonly directions leftwl = (1.0, 0.6)big where directions differmean of the 9 valuesdl = 0.20The four steps of one LPIPS layer distance (stacked)Four 3 by 3 grids in two rows. Top left: red feature vectors of x and blue feature vectors of x prime, of different lengths. Top right: both normalised to unit length. Bottom left: the difference of the unit vectors multiplied channel-wise by w_l = (1.0, 0.6), large only where the directions differ. Bottom right: the squared lengths as a heat map with numbers from 0.00 to 1.36; their average over the nine positions is d_l = 0.20.1. featuresdifferent lengths2. unit-normaliseonly directions left3. subtract, ⊙ wlwl = (1.0, 0.6)4. square ‖ · ‖²0.000.020.000.030.340.010.000.001.36big where directions differaverage over the 9 positions:dl = 0.20red: x, blue: x′
A toy layer with C = 2 channels on a 3 × 3 grid; each feature vector is an arrow, red for x and blue for x′, non-negative after the ReLU. Normalisation keeps only directions; the weighted difference is large only where they disagree. Its squared length averaged over the 9 positions is dₗ = 0.20.

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.

MetricAgreement with people
L2L_2 on pixels63.2%
SSIM63.1%
unweighted features of supervised networks67.0–68.9%
one person73.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, [−1,1][-1, 1] for the reference package. It was fitted on 64×6464 \times 64 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.
  • LPIPS=∑l1HlWl∑h,w∥wl⊙(φ^l(x)hw−φ^l(x′)hw)∥22\mathrm{LPIPS} = \sum_l \frac{1}{H_l W_l} \sum_{h, w} \|w_l \odot (\hat\varphi_l(x)_{hw} - \hat\varphi_l(x')_{hw})\|_2^2, with features unit-normalised over channels.
  • Without weights each term is 2−2cos⁡θ2 - 2\cos\theta; 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 under np.random.seed(10), each resized to 512×512512 \times 512. 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 [−1,1][-1, 1] (for example normalize=True on images in [0,1][0, 1]), 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#