Course contents 19 / 33

19 / 33 · Evaluation

LPIPS

Learned Perceptual Image Patch Similarity compares two images through normalised, learned-weighted differences of deep feature maps, so that the distance follows human perception rather than raw pixels.

On this page 10

LPIPS (Learned Perceptual Image Patch Similarity; Zhang et al., 2018) measures how different two images look. Inception Score and FID score a whole set of generated images. LPIPS instead compares a pair of images, usually a generated or distorted image x′x' and a reference xx.

The idea in one line: take outputs from several internal layers of a pretrained network, find the differences between the feature maps, then normalise, weigh and average.

Why not compare pixels?#

The obvious distance between two images is pixelwise: the L2L_2 distance or 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 .

For perception it is a bad distance, and it fails in both directions:

  • Shift the image and MSE becomes large. Moving the picture by one pixel changes almost nothing for a human. Every pixel on an edge, however, now meets a different value, so the error is large.
  • MSE considers blur to be fine. A blurred image replaces each pixel by an average of its neighbours. Each value moves only a little, so MSE stays small, even though the blur is clearly visible.

A small computed example makes this concrete. Take an 8×88\times 8 image of vertical stripes with a period of 4 pixels, so every row reads 0 0 1 1 0 0 1 1. Compare it with two copies:

  • shifted right by 1 px (wrapping around), so every row becomes 1 0 0 1 1 0 0 1;
  • blurred with the kernel 14[1  2  1]\tfrac14[1\;2\;1] (again wrapping around at the edges), so every row becomes .25 .25 .75 .75 .25 .25 .75 .75.
CopyPer-pixel squared errorMSETo a human
Shifted11 on half the pixels, 00 elsewhere0.50.5looks the same
Blurred0.252=0.06250.25^2 = 0.0625 on every pixel0.06250.0625looks worse

Pixel MSE calls the blurred copy 0.5/0.0625=80.5 / 0.0625 = 8 times closer to the original, which is the opposite of what we see.

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”
An 8 × 8 image of vertical stripes (period 4 pixels). Shifting it right by one pixel (wrapping around) leaves the picture looking the same, but half of the pixels flip, so MSE = 0.50. Blurring it with the kernel [1 2 1]/4 (also wrapping around) visibly washes out the stripes, yet every pixel moves by only 0.25, so MSE = 0.0625: pixel MSE calls the blurred copy 8 times closer. The error maps use a square-root colour scale so that the small errors stay visible.

A related effect explains why networks trained with a pure MSE loss tend to produce blurry outputs (Mathieu, Couprie and LeCun, 2016). The prediction that minimises the expected squared error is the conditional mean, so when several sharp answers are plausible, the best guess under MSE is their average, which is a blur. The same averaging is one cause of blurry VAE samples. A perceptual distance should instead be robust to small, imperceptible shifts and sensitive to the loss of structure. Deep features get much 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. Early layers still register the shift, so the features change less than raw pixels but are not invariant: LPIPS itself reacts to shifts too small for people to notice (Ghildyal and Liu, 2022).

The algorithm#

  1. Extract features φl(x)\varphi_l(x) and φl(x′)\varphi_l(x') at several layers l=1,…,Ll = 1,\dots,L of a pretrained network such as AlexNet (Krizhevsky, Sutskever and Hinton, 2012) or VGG (Simonyan and Zisserman, 2015). The same frozen network, with shared weights, processes both images.
  2. Normalise channel-wise. At every spatial position (h,w)(h, w), divide the feature vector by its length across the channels.
  3. Subtract the two normalised feature maps.
  4. Weigh the difference channel by channel with a vector wlw_l, take its squared length across the channels at each position and average spatially over all positions. This gives one number dld_l per layer.
  5. Sum over layers to get LPIPS.

The weights wlw_l are learned from human perceptual judgements while the network stays frozen (the lin configuration of Zhang et al., 2018, §3). They are fitted on the BAPPS dataset of two-alternative forced choices (2AFC), in which people saw a reference patch of 64×6464\times 64 pixels and two distorted versions and picked the one that looked closer (§2).

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 every chosen layer the two feature maps are compared (unit-normalised over channels, subtracted, weighted by the learned wₗ, squared and averaged over positions), which gives one number dₗ per layer. LPIPS is the sum of these numbers. The layer sizes are schematic: for AlexNet the five layers have Cₗ = 64, 192, 384, 256 and 256 channels, for VGG 64, 128, 256, 512 and 512.

The formula#

Notation: layer ll produces a feature map φl(x)∈RCl×Hl×Wl\varphi_l(x) \in \mathbb R^{C_l \times H_l \times W_l} with ClC_l channels on an Hl×WlH_l \times W_l grid. The feature vector at position (h,w)(h, w) is φl(x)hw∈RCl\varphi_l(x)_{hw} \in \mathbb R^{C_l}, and the hat marks 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} .

A post-ReLU feature vector can be zero. The reference implementation divides by ∥φl(x)hw∥2+ε\|\varphi_l(x)_{hw}\|_2 + \varepsilon with ε=10−10\varepsilon = 10^{-10}, so a zero vector stays zero (Zhang, 2021).

Layer ll, with a weight vector wl∈RClw_l \in \mathbb R^{C_l} and the difference Δl,hw\Delta_{l,hw} of the normalised features at each position (Zhang et al., 2018, §3, Eq. 1):

Δl,hw=φ^l(x)hw−φ^l(x′)hw,dl(x,x′)=1HlWl∑h,w∥ wl⊙Δl,hw∥22.\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 . \end{aligned}

Here ⊙\odot is the element-wise product, so wlw_l scales each channel of the difference. The reference lpips package (Zhang, 2021) instead applies weights vl,c≥0v_{l,c} \ge 0 to the squared channel differences, ∑cvl,c Δl,hw,c2\sum_c v_{l,c}\,\Delta_{l,hw,c}^2, where Δl,hw,c\Delta_{l,hw,c} is channel cc of Δl,hw\Delta_{l,hw}; the paper also restricts the weights to be non-negative (Zhang et al., 2018, Appendix A, Figure 10). Since ∥wl⊙Δl,hw∥22=∑cwl,c2 Δl,hw,c2\|w_l \odot \Delta_{l,hw}\|_2^2 = \sum_c w_{l,c}^2\,\Delta_{l,hw,c}^2, this is the formula above with wl,c=vl,cw_{l,c} = \sqrt{v_{l,c}}, so the two forms are equivalent.

Final:

LPIPS(x,x′)=∑ldl(x,x′).\mathrm{LPIPS}(x, x') = \sum_{l} d_l(x, x') .

Each piece has a job:

  • Normalisation removes the overall magnitude of the activations. Only the direction of the feature vector, meaning which channels respond and in what proportion, is compared. Layers or positions with large activations therefore do not dominate. Without the weights the term is a cosine distance in disguise: for unit vectors with angle θ\theta between them, ∥u^−v^∥22=∥u^∥22+∥v^∥22−2 u^⊤v^=2−2cos⁡θ\|\hat u - \hat v\|_2^2 = \|\hat u\|_2^2 + \|\hat v\|_2^2 - 2\,\hat u^\top\hat v = 2 - 2\cos\theta (Zhang et al., 2018, §3).
  • The weights wlw_l decide which channels matter for perception and turn down the ones that do not.
  • The spatial average 1HlWl∑h,w\frac{1}{H_l W_l}\sum_{h,w} makes layers with different grid sizes comparable. It also forgives a small local disagreement, provided the rest of the map agrees. Without the average, the terms ∥wl⊙Δl,hw∥22\|w_l \odot \Delta_{l,hw}\|_2^2 form a map that shows where two images differ. The reference package returns such a map, upsampled to the input resolution and summed over layers, when it is created with spatial=True (Zhang, 2021).

The toy layer below has Cl=2C_l = 2 channels on a 3×33 \times 3 grid, so each feature vector can be drawn as an arrow. The weights are wl=(1,0.6)w_l = (1, 0.6). Two positions show the effect of each step:

  • Bottom right. The feature vectors point along channel 1 and channel 2. They differ by 90∘90^\circ, the largest angle possible for features taken after a ReLU, as in the reference implementation (Zhang, 2021), since such features are non-negative. Unweighted, the term is 2−2cos⁡90∘=22 - 2\cos 90^\circ = 2. The difference is (1,−1)(1, -1), and the weights turn it into (1,−0.6)(1, -0.6), so the term is 1+0.36=1.361 + 0.36 = 1.36.
  • Centre. The directions differ by 40∘40^\circ. Unweighted, the term would be 2−2cos⁡40∘≈0.472 - 2\cos 40^\circ \approx 0.47. The weight 0.60.6 on channel 2 lowers it to 0.340.34.

All the other positions nearly agree. Averaging the nine terms gives dl≈0.20d_l \approx 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, so the feature vector at each position (h, w) is an arrow (red for x, blue for x′). Post-ReLU features are non-negative, so in the first two grids every arrow starts at the lower-left corner of its cell and points into the first quadrant. Normalisation keeps only the directions; the weighted difference is large only where the directions disagree; its squared length, averaged over the 9 positions, is dₗ = 0.20. All values are computed.

Interpretation#

  • Low LPIPS: the images look perceptually similar.
  • High LPIPS: the images differ in visible structure (edges, textures, shapes).

In a search through about 1000 randomly drawn FashionMNIST images, the nine nearest images to an ankle boot are all ankle boots. That search fed the network raw grayscale values 00–255255 instead of the [−1,1][-1, 1] range it expects, so it measured a mis-scaled variant, not LPIPS as defined. Rescaling the input changes the nonlinear features, and with them possibly the order of the neighbours. The result is a diagnostic of that setup, not evidence that LPIPS ranks this query by class; the claim needs a rerun with the reference preprocessing.

Pros and cons#

Pros

  • Better agreement with humans than pixelwise metrics and classic measures such as SSIM (Wang et al., 2004). Most of the gain comes from the deep features themselves. Unweighted, the features of supervised networks agree with human 2AFC judgements 67.0–68.9% of the time, against 63.2% for L2L_2 and 63.1% for SSIM, while a human scores 73.9% (Zhang et al., 2018, §4.1). The learned weights help most on distortion types like those they were trained on: for AlexNet they raise the score from 76.8% to 78.7% on those test sets, but only from 65.0% to 65.3% on the outputs of real algorithms (Appendix A, Table 5).
  • Less sensitive to small shifts than raw pixels: deeper features change little under them, although the metric is not shift-invariant (Ghildyal and Liu, 2022).

Cons

  • Depends on the backbone CNN. AlexNet and VGG give different values, so scores are comparable only when they use the same backbone and the same version of the learned weights (Zhang, 2021).
  • Slower than pixelwise metrics: every comparison needs a forward pass through a deep network.
  • Still not perfect. It is a learned approximation of human perception, fitted to judgements on small patches. Small adversarial perturbations of an image can make LPIPS contradict human judgement dramatically (Kettunen, Härkönen and Lehtinen, 2019).

Where it is used#

  • Comparing the outputs of GANs and diffusion models. It measures how close a generated image is to a reference. In conditional generation, the average LPIPS between pairs of outputs sampled for the same input serves as a measure of diversity (Zhu et al., 2017, §5.2, Figure 6).
  • Nearest-neighbour checks for memorisation. Searching the training set for the LPIPS-nearest images of each generated sample can surface candidate copies, which FID cannot see (FID drawbacks). It is a screening tool: a small distance is not proof of memorisation, and a search that finds nothing is not an exhaustive audit. Inspect the candidates and report which part of the training set was searched, the preprocessing and the threshold.
  • Evaluating image restoration and editing: super-resolution, inpainting and style transfer, where a pixel metric would reward blurry outputs.
  • As a “perceptual loss” in training networks. LPIPS is differentiable, so it can replace or complement MSE as a training loss, in the spirit of earlier feature-space losses (Johnson, Alahi and Fei-Fei, 2016). This targets exactly the blur problem above.

Compared with IS and FID#

This extends the IS-versus-FID table with a column for LPIPS.

Inception ScoreFIDLPIPS
Aimconfidence and diversity of generated imagescloseness of generated images to real onesperceptual similarity of two images
Data usedgenerated images onlyreal and generated imagesa pair of images, e.g. generated vs. reference
What is comparedeach p(y∣x)p(y \mid x) with the marginal p(y)p(y)Gaussian fit to real features vs. Gaussian fit to generated featuresnormalised deep features of the two images, position by position
DistanceKL divergencesquared Fréchet (2-Wasserstein) distancelearned, weighted squared L2L_2 distance in feature space
Better ishigherlowerlower (more similar)

Notebook#

The metrics notebook of the HSE-LAMBDA Deep Generative Models repository (pinned commit; cell numbers count every cell, markdown included, from 1) contains the hands-on part of the evaluation block.

  • Cell 7 gives the LPIPS formula, with the layer sum outside and the notation x^ijl\hat x^l_{ij}, y^ijl\hat y^l_{ij} for the normalized features.
  • Cells 10–13 load FashionMNIST, show the query image (index 0, an ankle boot) and compute LPIPS with lpips.LPIPS(net='alex') against 1000 indices drawn with replacement (np.random.seed(10)), after resizing each image to 512×512512\times512. Each image enters as a 512×512512\times512 grayscale tensor with values 00–255255. Broadcasting in the package’s input scaling layer turns it into a three-channel batch of one, without the rescaling to [−1,1][-1, 1] that the package expects (Zhang, 2021). The saved run is therefore an input-contract failure: its distances are not comparable with published LPIPS scores, and its ranking is not validated either, since correct scaling changes the nonlinear features and can reorder the neighbours. The numbers below are a diagnostic of this setup until they are recomputed with inputs in [−1,1][-1, 1] (for example normalize=True on images in [0,1][0, 1]). The query tensor is rebuilt in every iteration and gradients are tracked, which costs time but does not change the distances. When the model loads, the package prints spatial [off]: with the default spatial=False it returns one number per pair rather than the distance map described above.
  • Cells 14–15 plot a histogram of distances per class and show the nine closest images. In the saved run, with the unscaled inputs, the nine nearest distances are 0.168, 0.181, 0.183, 0.191, 0.213, 0.214, 0.215, 0.217 and 0.220, all ankle boots. All ankle boots in the sample lie at about 0.17–0.44. The closest images of other classes, a few sandals and sneakers, lie at about 0.25–0.28, and almost all other images lie above 0.3.
  • Cell 16 contains two automatic checks: the smallest distance must be below 0.2, and more than 90% of the nine nearest neighbours must share the query’s label, which with nine neighbours means all nine.

Next#

IS and FID judge sets of generated images, LPIPS judges pairs. None of them can say whether a model fails by producing implausible images or by leaving out part of the data. The next note separates the two with precision and recall.

References#