---
title: Memorization-Informed Frechet Inception Distance (MiFID)
description: Calculate Memorization-Informed Frechet Inception Distance (MIFID).
canonical: 'https://lightning.ai/docs/torchmetrics/stable/image/mifid'
---
# Memorization-Informed Frechet Inception Distance (MiFID) {#memorization-informed-frechet-inception-distance-mifid}

## Module Interface {#module-interface}

### `class torchmetrics.image.mifid.MemorizationInformedFrechetInceptionDistance(feature=2048, reset_real_features=True, normalize=False, cosine_distance_eps=0.1, **kwargs)` {#torchmetrics.image.mifid.MemorizationInformedFrechetInceptionDistance}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/image/mifid.py#L67-L297)

Calculate Memorization-Informed Frechet Inception Distance ([MIFID](https://arxiv.org/abs/2106.03062)).

MIFID is a improved variation of the Frechet Inception Distance ([FID](https://en.wikipedia.org/wiki/Fr%C3%A9chet_inception_distance)) that penalizes memorization of the training set by the generator. It is calculated as

```math
MIFID = \frac{FID(F_{real}, F_{fake})}{M(F_{real}, F_{fake})}
```

where $`FID`$ is the normal FID score and $`M`$ is the memorization penalty. The memorization penalty essentially corresponds to the average minimum cosine distance between the features of the real and fake distribution.

Using the default feature extraction (Inception v3 using the original weights from [fid ref2](https://arxiv.org/abs/1706.08500)), the input is expected to be mini-batches of 3-channel RGB images of shape `(3 x H x W)`. If argument `normalize` is `True` images are expected to be dtype `float` and have values in the `[0, 1]` range, else if `normalize` is set to `False` images are expected to have dtype `uint8` and take values in the `[0, 255]` range. All images will be resized to 299 x 299 which is the size of the original training data. The boolian flag `real` determines if the images should update the statistics of the real distribution or the fake distribution.

Hint

Using this metrics requires you to have `scipy` install. Either install as `pip install torchmetrics[image]` or `pip install scipy`

Hint

Using this metric with the default feature extractor requires that `torch-fidelity` is installed. Either install as `pip install torchmetrics[image]` or `pip install torch-fidelity`

As input to `forward` and `update` the metric accepts the following input

*   `imgs` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): tensor with images feed to the feature extractor with
    
*   `real` ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")): bool indicating if `imgs` belong to the real or the fake distribution
    

As output of forward and compute the metric returns the following output

*   `mifid` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): float scalar tensor with mean MIFID value over samples
    

Parameters:

*   **feature** (`Union`\[[`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)"), [`Module`](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module "(in PyTorch v2.15)")\]) –
    
    Either an integer or `nn.Module`:
    
    *   an integer will indicate the inceptionv3 feature layer to choose. Can be one of the following: 64, 192, 768, 2048
        
    *   an `nn.Module` for using a custom feature extractor. Expects that its forward method returns an `(N,d)` matrix where `N` is the batch size and `d` is the feature size.
        
    
*   **reset\_real\_features** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – Whether to also reset the real features. Since in many cases the real dataset does not change, the features can be cached them to avoid recomputing them which is costly. Set this to `False` if your dataset does not change.
    
*   **normalize** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – Whether to normalize the input images. If `True` the input is expected to be in the range \[0, 1\] and converted to `uint8`. If `False` the input is expected to already be in the range \[0, 255\] and of type `uint8`. If a custom feature extractor is used, this argument is ignored.
    
*   **cosine\_distance\_eps** ([`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)")) – Epsilon value for the cosine distance. If the cosine distance is larger than this value it is set to 1 and thus ignored in the MIFID calculation.
    
*   **kwargs** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")) – Additional keyword arguments, see [Advanced metric settings](/docs/torchmetrics/1.9.0/user-guide/overview.md#metric-kwargs) for more info.
    

Raises:

*   [**RuntimeError**](https://docs.python.org/3/builtins/exceptions.html#RuntimeError "(in Python v3.15)") – If `torch` is version less than 1.10
    
*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `feature` is set to an `int` and `torch-fidelity` is not installed
    
*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `feature` is set to an `int` not in \[64, 192, 768, 2048\]
    
*   [**TypeError**](https://docs.python.org/3/builtins/exceptions.html#TypeError "(in Python v3.15)") – If `feature` is not an `str`, `int` or `torch.nn.Module`
    
*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `reset_real_features` is not an `bool`
    

Example::

```python
>>> from torch import randint
>>> from torchmetrics.image.mifid import MemorizationInformedFrechetInceptionDistance
>>> mifid = MemorizationInformedFrechetInceptionDistance(feature=64)
>>> # generate two slightly overlapping image intensity distributions
>>> imgs_dist1 = randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8)
>>> imgs_dist2 = randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8)
>>> mifid.update(imgs_dist1, real=True)
>>> mifid.update(imgs_dist2, real=False)
>>> mifid.compute()
tensor(3003.3691)
```

#### `plot(val=None, ax=None)` {#torchmetrics.image.mifid.MemorizationInformedFrechetInceptionDistance.plot}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/image/mifid.py#L249-L297)

Plot a single or multiple values from the metric.

Parameters:

*   **val** (`Union`\[[`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)"), [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence "(in Python v3.15)")\[[`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")\], [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – Either a single result from calling metric.forward or metric.compute or a list of these results. If no value is provided, will automatically call metric.compute and plot that result.
    
*   **ax** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Axes`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.html#matplotlib.axes.Axes "(in Matplotlib v3.11.2)")\]) – An matplotlib axis object. If provided will add plot to that axis
    

Return type:

[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple "(in Python v3.15)")\[[`Figure`](https://matplotlib.org/stable/api/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure "(in Matplotlib v3.11.2)"), `Union`\[[`Axes`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.html#matplotlib.axes.Axes "(in Matplotlib v3.11.2)"), [`ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray "(in NumPy v2.5)")\]\]

Returns:

Figure and Axes object

Raises:

[**ModuleNotFoundError**](https://docs.python.org/3/builtins/exceptions.html#ModuleNotFoundError "(in Python v3.15)") – If matplotlib is not installed

```python
>>> # Example plotting a single value
>>> import torch
>>> from torchmetrics.image.mifid import MemorizationInformedFrechetInceptionDistance
>>> 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)
>>> metric = MemorizationInformedFrechetInceptionDistance(feature=64)
>>> metric.update(imgs_dist1, real=True)
>>> metric.update(imgs_dist2, real=False)
>>> fig_, ax_ = metric.plot()
```

```python
>>> # Example plotting multiple values
>>> import torch
>>> from torchmetrics.image.mifid import MemorizationInformedFrechetInceptionDistance
>>> imgs_dist1 = lambda: torch.randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8)
>>> imgs_dist2 = lambda: torch.randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8)
>>> metric = MemorizationInformedFrechetInceptionDistance(feature=64)
>>> values = [ ]
>>> for _ in range(3):
...     metric.update(imgs_dist1(), real=True)
...     metric.update(imgs_dist2(), real=False)
...     values.append(metric.compute())
...     metric.reset()
>>> fig_, ax_ = metric.plot(values)
```

#### `reset()` {#torchmetrics.image.mifid.MemorizationInformedFrechetInceptionDistance.reset}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/image/mifid.py#L239-L247)

Reset metric states.

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

---

**Navigation**

- Parent: [Image](/docs/torchmetrics/1.9.0/image.md)
