AI Logic

Evaluation Metrics

Fréchet Inception Distance (FID)

Updated:

Computing FID. Left: real and generated images are passed through the same Inception-v3 to extract 2048-dimensional features, and the Fréchet distance is computed from their means and covariances. Right: an example with 2-dimensional features, showing clouds of real and generated points with their 1σ ellipses; the mean difference 2.22 plus the spread difference 0.27 gives an FID of 2.49

Background and overview

FID (Fréchet Inception Distance) is an evaluation metric that compares a set of real images and a set of generated images using the features of a pretrained image recognition model, and measures how far apart the two distributions are. It is non-negative, and smaller values mean the distribution of generated images is closer to the real one.

FID=∥m−mw∥22+Tr(C+Cw−2(CCw)1/2)\mathrm{FID} = \lVert m - m_w \rVert_2^2 + \mathrm{Tr}\left( C + C_w - 2\left( C C_w \right)^{1/2} \right)

mm and CC are the mean and covariance of the features of the generated images, and mwm_w and CwC_w are those of the real images. The features are the outputs of the last pooling layer of Inception-v3 (the successor of GoogLeNet (Inception)) trained on ImageNet. The first term measures the shift between the centers of the distributions, and the second term measures the difference in their spread.

FID was introduced in 2017 by Heusel et al. to evaluate GANs, in the paper that proposed a training method for GANs (TTUR). The previously common Inception Score is computed from generated images alone, so it had the drawback of not comparing against the statistics of real images. FID addresses this by comparing directly with the feature distribution of real images.

Definition and computation

FID is computed in the following steps.

  1. Pass the real images (all training images in the paper) through Inception-v3 trained on ImageNet, and take the output of the last pooling layer (2048 dimensions) as the features.
  2. Compute the mean mwm_w and covariance matrix CwC_w of those features.
  3. Pass the generated images (50,000 in the paper) through Inception-v3 in the same way, and compute the mean mm and covariance matrix CC of their features.
  4. Treat each feature distribution as a multivariate normal distribution with that mean and covariance, and compute the squared Fréchet distance between them (also called the 2-Wasserstein distance) with the formula above.

According to the paper, two distributions are equal when the expected values of all functions agree. The paper chose to compare only the first two moments (mean and covariance). Among distributions with a given mean and covariance, the normal distribution has the maximum entropy, so the features are treated as normally distributed.

The right side of the figure at the top shows an example with 2-dimensional features. The cloud of generated points is shifted from the real one (mean difference 2.22) and narrower (spread difference 0.27), giving an FID of 2.49. The actual FID performs the same computation in 2048 dimensions.

The second term also captures a lack of diversity in the generated images. When a GAN generates only similar images (mode collapse), the covariance CC of the generated features becomes small, and the difference from the real covariance CwC_w increases FID. A key feature of FID is that it evaluates not only the quality of individual images but also the diversity of the set as a whole.

What it measures and its limitations

FID measures whether the set of generated images looks like the set of real images, as seen by an image recognition model. Features from the deep layers of Inception-v3 represent visual meaning such as object categories and shapes rather than raw pixel values, so the comparison is closer to human visual judgment. The paper applied six kinds of disturbance at varying strengths to CelebA face images: Gaussian noise, blur, black rectangles, swirl distortion, salt-and-pepper noise, and contamination with ImageNet images. It showed that FID increases as the disturbance gets stronger, tracking the disturbance strength better than the Inception Score.

FID also has the following limitations.

  • The value depends on the number of images: FID is estimated from a finite number of images, so it is biased. Chong and Forsyth (2020) showed that this bias differs across the models being evaluated, so even with a fixed number of images, the ranking of models can flip.
  • The value depends on preprocessing: Parmar et al. (2022) showed that low-level processing such as how images are resized (different interpolation in different libraries, aliasing) and JPEG compression can change FID substantially.
  • It depends on how Inception-v3 sees images: the features were trained for ImageNet classification. For images that differ from ImageNet, such as faces or medical images, FID does not necessarily agree with human judgment.
  • The Gaussian assumption: the feature distribution is represented only by its mean and covariance, so differences in distribution shape beyond these cannot be measured.
  • It says nothing about individual images: it compares set statistics, so it does not show which image is bad.

FID values are comparable only when computed with the same implementation, the same set of real images, the same number of generated images and the same preprocessing. Besides the paper's 50,000 images (FID50k), 10,000 and other counts are used, and fewer images tend to give larger values. According to the pytorch-fid documentation, at least 2048 images are needed to compute a 2048-dimensional covariance. The original TensorFlow implementation and its PyTorch port also give slightly different values because of differences in image interpolation, so state the implementation used when comparing precisely with published results.

Validation in the original paper

The paper used FID to compare the proposed training method TTUR (separate learning rates for the discriminator and generator) with conventional training (a single learning rate). The table shows the best FID reached during training.

ModelDatasetTTURConventional training
DCGANCelebA12.521.4
DCGANCIFAR-1036.937.7
DCGANSVHN12.521.4
DCGANLSUN Bedrooms57.570.4
WGAN-GPCIFAR-1024.829.3
WGAN-GPLSUN Bedrooms9.520.5

TTUR has the lower FID in every combination, and the paper concludes that TTUR consistently outperforms conventional training and trains more stably. FID values differ greatly across datasets, so they can only be compared within the same dataset.

The paper's appendix shows sample images from a DCGAN trained on CelebA at FIDs of 500, 300, 133, 100, 45 and 13, and from WGAN-GP when it reached an FID of 3, confirming that images look more realistic as FID decreases.

Where it is used

FID is mainly used in the following settings.

  • Comparing image generation models: it is the most common metric for comparing image generation models of different kinds, such as GAN, StyleGAN, VAE, DDPM and Latent Diffusion, on the same scale.
  • Monitoring training progress: as in the paper, FID is computed at regular intervals during training to stop training when it no longer decreases or to choose learning rates.
  • Applying it to other kinds of data: the same idea with audio features instead of image features gives metrics such as Fréchet Audio Distance (FAD).

Comparison with similar metrics

The table compares FID with other metrics used to evaluate generative models from the same viewpoints.

MetricCompares with real images?What it measuresDirectionMain constraints
FIDYes (mean and covariance of features)Distance between the distributions of generated and real imagesLower is betterDepends on the number of images and preprocessing
Inception ScoreNoClass confidence per image and class diversity overallHigher is betterUses no real-image statistics. Ignores within-class diversity
FADYes (audio features)Distance between the distributions of generated and real audioLower is betterDepends on the feature extraction model
Human evaluationJudged by peopleVisual naturalness and preferenceDepends on the evaluation designTakes time and money

Rough guidelines for choosing:

  • Comparing with prior work in image generation: compute FID with the same implementation, the same number of images and the same real images as prior work.
  • Evaluating the diversity of generated images as well: FID, which compares with the real distribution, is suitable. The Inception Score does not look at diversity within a class.
  • Images that look very different from ImageNet (such as medical images): Inception-v3 features may not fit, so also use human evaluation or evaluation with features suited to the target data.
  • Audio generation: use FAD, which uses audio features instead of image features.

PyTorch example

Show code
python
import numpy as np
from scipy import linalg


def frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):
  """Eq. (6) of Heusel et al. (2017): ||mu1 - mu2||^2 + Tr(sigma1 + sigma2 - 2 (sigma1 sigma2)^(1/2)).
  mu and sigma are the mean and covariance of the 2048-dimensional Inception-v3 features."""
  diff = mu1 - mu2
  covmean, _ = linalg.sqrtm(sigma1 @ sigma2, disp=False)
  if not np.isfinite(covmean).all():  # when the covariance is nearly singular (e.g. too few images), add a small value to the diagonal
    offset = np.eye(sigma1.shape[0]) * eps
    covmean = linalg.sqrtm((sigma1 + offset) @ (sigma2 + offset))
  covmean = covmean.real  # drop the small imaginary part caused by numerical error
  return diff @ diff + np.trace(sigma1) + np.trace(sigma2) - 2 * np.trace(covmean)


def stats(features):
  """features: features of shape (num_images, 2048). Returns the mean and covariance."""
  return features.mean(axis=0), np.cov(features, rowvar=False)


# With torchmetrics (requires torch-fidelity). The default uses 2048-dimensional features;
# with normalize=False it takes uint8 images in [0, 255] and resizes them to 299 × 299 internally
import torch
from torchmetrics.image.fid import FrechetInceptionDistance

fid = FrechetInceptionDistance(feature=2048, normalize=False)
generator.eval()
with torch.no_grad():
  for real_images in real_loader:          # (B, 3, H, W), uint8
    fid.update(real_images, real=True)     # accumulate statistics of real images
  for _ in range(num_batches):             # 50,000 generated images in the paper
    z = torch.randn(batch_size, latent_dim)
    fake = generator(z)                    # e.g. float in [-1, 1]
    fake = ((fake + 1) * 127.5).clamp(0, 255).to(torch.uint8)
    fid.update(fake, real=False)
print(fid.compute())

FAQ

Q. What FID value counts as good?
A.

There is no fixed threshold, because the value changes greatly with the dataset, the number of generated images, the implementation and preprocessing. Even the paper's DCGAN scored 12.5 on CelebA and 57.5 on LSUN Bedrooms. Judge a value by comparing it with existing models computed under the same conditions.

Q. How many generated images should be used?
A.

The paper used 50,000 images. At least 2048 images are needed to compute a 2048-dimensional covariance, and fewer images tend to give larger values. When comparing with prior work, use the same number of images as that paper and state the number explicitly.

Q. How do FID and the Inception Score differ?
A.

The Inception Score is computed from generated images alone and does not compare against real-image statistics. FID compares directly with the feature distribution of real images, so it also reflects cases where the model generates images unlike the real ones or lacks diversity. In the paper's experiments, FID also tracked the strength of disturbances added to images better.

References

  1. Heusel, M., Ramsauer, H., Unterthiner, T., Nessler, B., & Hochreiter, S. (2017). GANs Trained by a Two Time-Scale Update Rule Converge to a Local Nash Equilibrium. NeurIPS 2017. arXiv:1706.08500.
  2. Chong, M. J., & Forsyth, D. (2020). Effectively Unbiased FID and Inception Score and where to find them. CVPR 2020. arXiv:1911.07023.
  3. Parmar, G., Zhang, R., & Zhu, J.-Y. (2022). On Aliased Resizing and Surprising Subtleties in GAN Evaluation. CVPR 2022. arXiv:2104.11222.
  4. Seitzer, M. pytorch-fid: FID Score for PyTorch (GitHub repository).
  5. Lightning AI. torchmetrics.image.FrechetInceptionDistance (API reference).