Kernel Inception Distance¶
Module Interface¶
- class torchmetrics.image.kid.KernelInceptionDistance(feature=2048, subsets=100, subset_size=1000, degree=3, gamma=None, coef=1.0, reset_real_features=True, **kwargs)[source]
Calculates Kernel Inception Distance (KID) which is used to access the quality of generated images. Given by

where
is the maximum mean discrepancy and
are extracted features
from real and fake images, see [1] for more details. In particular, calculating the MMD requires the
evaluation of a polynomial kernel function 

which controls the distance between two features. In practise the MMD is calculated over a number of subsets to be able to both get the mean and standard deviation of KID.
Using the default feature extraction (Inception v3 using the original weights from [2]), the input is expected to be mini-batches of 3-channel RGB images of shape (3 x H x W) with dtype uint8. All images will be resized to 299 x 299 which is the size of the original training data.
Note
using this metric with the default feature extractor requires that
torch-fidelityis installed. Either install aspip install torchmetrics[image]orpip install torch-fidelity- Parameters
feature¶ (
Union[str,int,Module]) –Either an str, integer or
nn.Module:an str or integer will indicate the inceptionv3 feature layer to choose. Can be one of the following: ‘logits_unbiased’, 64, 192, 768, 2048
an
nn.Modulefor using a custom feature extractor. Expects that its forward method returns an[N,d]matrix whereNis the batch size anddis the feature size.
subsets¶ (
int) – Number of subsets to calculate the mean and standard deviation scores oversubset_size¶ (
int) – Number of randomly picked samples in each subsetgamma¶ (
Optional[float]) – Scale-length of polynomial kernel. If set toNonewill be automatically set to the feature sizereset_real_features¶ (
bool) – Whether to also reset the real features. Since in many cases the real dataset does not change, the features can cached them to avoid recomputing them which is costly. Set this toFalseif your dataset does not change.kwargs¶ (
Dict[str,Any]) – Additional keyword arguments, see Advanced metric settings for more info.
References
[1] Demystifying MMD GANs Mikołaj Bińkowski, Danica J. Sutherland, Michael Arbel, Arthur Gretton https://arxiv.org/abs/1801.01401
[2] GANs Trained by a Two Time-Scale Update Rule Converge to a Local Nash Equilibrium, Martin Heusel, Hubert Ramsauer, Thomas Unterthiner, Bernhard Nessler, Sepp Hochreiter https://arxiv.org/abs/1706.08500
- Raises
ValueError – If
featureis set to anint(default settings) andtorch-fidelityis not installedValueError – If
featureis set to anintnot in[64, 192, 768, 2048]ValueError – If
subsetsis not an integer larger than 0ValueError – If
subset_sizeis not an integer larger than 0ValueError – If
degreeis not an integer larger than 0ValueError – If
gammais nietherNoneor a float larger than 0ValueError – If
coefis not an float larger than 0ValueError – If
reset_real_featuresis not anbool
Example
>>> import torch >>> _ = torch.manual_seed(123) >>> from torchmetrics.image.kid import KernelInceptionDistance >>> kid = KernelInceptionDistance(subset_size=50) >>> # generate two slightly overlapping image intensity distributions >>> imgs_dist1 = torch.randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8) >>> imgs_dist2 = torch.randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8) >>> kid.update(imgs_dist1, real=True) >>> kid.update(imgs_dist2, real=False) >>> kid_mean, kid_std = kid.compute() >>> print((kid_mean, kid_std)) (tensor(0.0337), tensor(0.0023))
Initializes internal Module state, shared by both nn.Module and ScriptModule.
- compute()[source]
Calculate KID score based on accumulated extracted features from the two distributions. Returns a tuple of mean and standard deviation of KID scores calculated on subsets of extracted features.
Implementation inspired by Fid Score
- reset()[source]
This method automatically resets the metric state variables to their default value.
- Return type