inception.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. # Copyright The Lightning team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from collections.abc import Sequence
  15. from typing import Any, Optional, Union
  16. import torch
  17. from torch import Tensor
  18. from torch.nn import Module
  19. from torchmetrics.image.fid import NoTrainInceptionV3
  20. from torchmetrics.metric import Metric
  21. from torchmetrics.utilities import rank_zero_warn
  22. from torchmetrics.utilities.data import dim_zero_cat
  23. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE, _TORCH_FIDELITY_AVAILABLE
  24. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  25. if not _MATPLOTLIB_AVAILABLE:
  26. __doctest_skip__ = ["InceptionScore.plot"]
  27. __doctest_requires__ = {("InceptionScore", "InceptionScore.plot"): ["torch_fidelity"]}
  28. class InceptionScore(Metric):
  29. r"""Calculate the Inception Score (IS) which is used to access how realistic generated images are.
  30. .. math::
  31. IS = exp(\mathbb{E}_x KL(p(y | x ) || p(y)))
  32. where :math:`KL(p(y | x) || p(y))` is the KL divergence between the conditional distribution :math:`p(y|x)`
  33. and the marginal distribution :math:`p(y)`. Both the conditional and marginal distribution is calculated
  34. from features extracted from the images. The score is calculated on random splits of the images such that
  35. both a mean and standard deviation of the score are returned. The metric was originally proposed in
  36. `inception ref1`_.
  37. Using the default feature extraction (Inception v3 using the original weights from `inception ref2`_), the input
  38. is expected to be mini-batches of 3-channel RGB images of shape ``(3xHxW)``. If argument ``normalize``
  39. is ``True`` images are expected to be dtype ``float`` and have values in the ``[0,1]`` range, else if
  40. ``normalize`` is set to ``False`` images are expected to have dtype uint8 and take values in the ``[0, 255]``
  41. range. All images will be resized to 299 x 299 which is the size of the original training data.
  42. .. hint::
  43. Using this metric with the default feature extractor requires that ``torch-fidelity``
  44. is installed. Either install as ``pip install torchmetrics[image]`` or
  45. ``pip install torch-fidelity``
  46. As input to ``forward`` and ``update`` the metric accepts the following input
  47. - ``imgs`` (:class:`~torch.Tensor`): tensor with images feed to the feature extractor
  48. As output of `forward` and `compute` the metric returns the following output
  49. - ``inception_mean`` (:class:`~torch.Tensor`): float scalar tensor with mean inception score over subsets
  50. - ``inception_std`` (:class:`~torch.Tensor`): float scalar tensor with standard deviation of inception score
  51. over subsets
  52. Args:
  53. feature:
  54. Either an str, integer or ``nn.Module``:
  55. - an str or integer will indicate the inceptionv3 feature layer to choose. Can be one of the following:
  56. 'logits_unbiased', 64, 192, 768, 2048
  57. - an ``nn.Module`` for using a custom feature extractor. Expects that its forward method returns
  58. an ``(N,d)`` matrix where ``N`` is the batch size and ``d`` is the feature size.
  59. splits: integer determining how many splits the inception score calculation should be split among
  60. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  61. Raises:
  62. ValueError:
  63. If ``feature`` is set to an ``str`` or ``int`` and ``torch-fidelity`` is not installed
  64. ValueError:
  65. If ``feature`` is set to an ``str`` or ``int`` and not one of ``('logits_unbiased', 64, 192, 768, 2048)``
  66. TypeError:
  67. If ``feature`` is not an ``str``, ``int`` or ``torch.nn.Module``
  68. Example:
  69. >>> from torch import rand
  70. >>> from torchmetrics.image.inception import InceptionScore
  71. >>> inception = InceptionScore()
  72. >>> # generate some images
  73. >>> imgs = torch.randint(0, 255, (100, 3, 299, 299), dtype=torch.uint8)
  74. >>> inception.update(imgs)
  75. >>> inception.compute()
  76. (tensor(1.0549), tensor(0.0121))
  77. """
  78. is_differentiable: bool = False
  79. higher_is_better: bool = True
  80. full_state_update: bool = False
  81. plot_lower_bound: float = 0.0
  82. features: list
  83. inception: Module
  84. feature_network: str = "inception"
  85. def __init__(
  86. self,
  87. feature: Union[str, int, Module] = "logits_unbiased",
  88. splits: int = 10,
  89. normalize: bool = False,
  90. **kwargs: Any,
  91. ) -> None:
  92. super().__init__(**kwargs)
  93. rank_zero_warn(
  94. "Metric `InceptionScore` will save all extracted features in buffer."
  95. " For large datasets this may lead to large memory footprint.",
  96. UserWarning,
  97. )
  98. if isinstance(feature, (str, int)):
  99. if not _TORCH_FIDELITY_AVAILABLE:
  100. raise ModuleNotFoundError(
  101. "InceptionScore metric requires that `Torch-fidelity` is installed."
  102. " Either install as `pip install torchmetrics[image]` or `pip install torch-fidelity`."
  103. )
  104. valid_int_input = ("logits_unbiased", 64, 192, 768, 2048)
  105. if feature not in valid_int_input:
  106. raise ValueError(
  107. f"Integer input to argument `feature` must be one of {valid_int_input}, but got {feature}."
  108. )
  109. self.inception = NoTrainInceptionV3(name="inception-v3-compat", features_list=[str(feature)])
  110. elif isinstance(feature, Module):
  111. self.inception = feature
  112. else:
  113. raise TypeError("Got unknown input to argument `feature`")
  114. if not isinstance(normalize, bool):
  115. raise ValueError("Argument `normalize` expected to be a bool")
  116. self.normalize = normalize
  117. self.splits = splits
  118. self.add_state("features", [], dist_reduce_fx=None)
  119. def update(self, imgs: Tensor) -> None:
  120. """Update the state with extracted features."""
  121. imgs = (imgs * 255).byte() if self.normalize else imgs
  122. features = self.inception(imgs)
  123. self.features.append(features)
  124. def compute(self) -> tuple[Tensor, Tensor]:
  125. """Compute metric."""
  126. features = dim_zero_cat(self.features)
  127. # random permute the features
  128. idx = torch.randperm(features.shape[0])
  129. features = features[idx]
  130. # calculate probs and logits
  131. prob = features.softmax(dim=1)
  132. log_prob = features.log_softmax(dim=1)
  133. # split into groups
  134. prob = prob.chunk(self.splits, dim=0)
  135. log_prob = log_prob.chunk(self.splits, dim=0)
  136. # calculate score per split
  137. mean_prob = [p.mean(dim=0, keepdim=True) for p in prob]
  138. kl_ = [p * (log_p - m_p.log()) for p, log_p, m_p in zip(prob, log_prob, mean_prob)]
  139. kl_ = [k.sum(dim=1).mean().exp() for k in kl_]
  140. kl = torch.stack(kl_)
  141. # return mean and std
  142. return kl.mean(), kl.std()
  143. def plot(
  144. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  145. ) -> _PLOT_OUT_TYPE:
  146. """Plot a single or multiple values from the metric.
  147. Args:
  148. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  149. If no value is provided, will automatically call `metric.compute` and plot that result.
  150. ax: An matplotlib axis object. If provided will add plot to that axis
  151. Returns:
  152. Figure and Axes object
  153. Raises:
  154. ModuleNotFoundError:
  155. If `matplotlib` is not installed
  156. .. plot::
  157. :scale: 75
  158. >>> # Example plotting a single value
  159. >>> import torch
  160. >>> from torchmetrics.image.inception import InceptionScore
  161. >>> metric = InceptionScore()
  162. >>> metric.update(torch.randint(0, 255, (50, 3, 299, 299), dtype=torch.uint8))
  163. >>> fig_, ax_ = metric.plot() # the returned plot only shows the mean value by default
  164. .. plot::
  165. :scale: 75
  166. >>> # Example plotting multiple values
  167. >>> import torch
  168. >>> from torchmetrics.image.inception import InceptionScore
  169. >>> metric = InceptionScore()
  170. >>> values = [ ]
  171. >>> for _ in range(3):
  172. ... # we index by 0 such that only the mean value is plotted
  173. ... values.append(metric(torch.randint(0, 255, (50, 3, 299, 299), dtype=torch.uint8))[0])
  174. >>> fig_, ax_ = metric.plot(values)
  175. """
  176. val = val or self.compute()[0] # by default we select the mean to plot
  177. return self._plot(val, ax)