fid_score.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. # Code adapted and modified from https://github.com/mseitzer/pytorch-fid. Licensing
  2. # and description duplicated below.
  3. #!/usr/bin/env python3
  4. """Calculates the Frechet Inception Distance (FID) to evalulate GANs
  5. The FID metric calculates the distance between two distributions of images.
  6. Typically, we have summary statistics (mean & covariance matrix) of one
  7. of these distributions, while the 2nd distribution is given by a GAN.
  8. When run as a stand-alone program, it compares the distribution of
  9. images that are stored as PNG/JPEG at a specified location with a
  10. distribution given by summary statistics (in pickle format).
  11. The FID is calculated by assuming that X_1 and X_2 are the activations of
  12. the pool_3 layer of the inception net for generated samples and real world
  13. samples respectively.
  14. See --help to see further details.
  15. Code apapted from https://github.com/bioinf-jku/TTUR to use PyTorch instead
  16. of Tensorflow
  17. Copyright 2018 Institute of Bioinformatics, JKU Linz
  18. Licensed under the Apache License, Version 2.0 (the "License");
  19. you may not use this file except in compliance with the License.
  20. You may obtain a copy of the License at
  21. http://www.apache.org/licenses/LICENSE-2.0
  22. Unless required by applicable law or agreed to in writing, software
  23. distributed under the License is distributed on an "AS IS" BASIS,
  24. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  25. See the License for the specific language governing permissions and
  26. limitations under the License.
  27. """
  28. import os
  29. import pathlib
  30. from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
  31. import numpy as np
  32. import torch
  33. from scipy import linalg
  34. from torch.nn.functional import adaptive_avg_pool2d
  35. import cv2
  36. import imageio
  37. try:
  38. from tqdm import tqdm
  39. except ImportError:
  40. # If not tqdm is not available, provide a mock version of it
  41. def tqdm(x):
  42. return x
  43. from .inception import InceptionV3
  44. parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
  45. parser.add_argument(
  46. 'path',
  47. type=str,
  48. nargs=2,
  49. help=('Path to the generated images or ' 'to .npz statistic files'),
  50. )
  51. parser.add_argument('--batch-size', type=int, default=50, help='Batch size to use')
  52. parser.add_argument(
  53. '--dims',
  54. type=int,
  55. default=2048,
  56. choices=list(InceptionV3.BLOCK_INDEX_BY_DIM),
  57. help=(
  58. 'Dimensionality of Inception features to use. '
  59. 'By default, uses pool3 features'
  60. ),
  61. )
  62. parser.add_argument(
  63. '-c', '--gpu', default='', type=str, help='GPU to use (leave blank for CPU only)'
  64. )
  65. def load_image_resized(fn, sz):
  66. return cv2.resize(
  67. imageio.imread(str(fn)), dsize=(sz, sz), interpolation=cv2.INTER_CUBIC
  68. ).astype(np.float32)
  69. def get_activations(
  70. files,
  71. model,
  72. batch_size=50,
  73. dims=2048,
  74. cuda=False,
  75. verbose=False,
  76. eval_size: int = 299,
  77. ):
  78. """Calculates the activations of the pool_3 layer for all images.
  79. Params:
  80. -- files : List of image files paths
  81. -- model : Instance of inception model
  82. -- batch_size : Batch size of images for the model to process at once.
  83. Make sure that the number of samples is a multiple of
  84. the batch size, otherwise some samples are ignored. This
  85. behavior is retained to match the original FID score
  86. implementation.
  87. -- dims : Dimensionality of features returned by Inception
  88. -- cuda : If set to True, use GPU
  89. -- verbose : If set to True and parameter out_step is given, the number
  90. of calculated batches is reported.
  91. Returns:
  92. -- A numpy array of dimension (num images, dims) that contains the
  93. activations of the given tensor when feeding inception with the
  94. query tensor.
  95. """
  96. model.eval()
  97. if len(files) % batch_size != 0:
  98. print(
  99. (
  100. 'Warning: number of images is not a multiple of the '
  101. 'batch size. Some samples are going to be ignored.'
  102. )
  103. )
  104. if batch_size > len(files):
  105. print(
  106. (
  107. 'Warning: batch size is bigger than the data size. '
  108. 'Setting batch size to data size'
  109. )
  110. )
  111. batch_size = len(files)
  112. n_batches = len(files) // batch_size
  113. n_used_imgs = n_batches * batch_size
  114. pred_arr = np.empty((n_used_imgs, dims))
  115. for i in tqdm(range(n_batches)):
  116. if verbose:
  117. print('\rPropagating batch %d/%d' % (i + 1, n_batches), end='', flush=True)
  118. start = i * batch_size
  119. end = start + batch_size
  120. images = np.array(
  121. [load_image_resized(fn, eval_size) for fn in files[start:end]]
  122. )
  123. # images = np.array([imageio.imread(str(f)).astype(np.float32)
  124. # for f in files[start:end]])
  125. # Reshape to (n_images, 3, height, width)
  126. images = images.transpose((0, 3, 1, 2))
  127. images /= 255
  128. batch = torch.from_numpy(images).type(torch.FloatTensor)
  129. if cuda:
  130. batch = batch.cuda()
  131. pred = model(batch)[0]
  132. # If model output is not scalar, apply global spatial average pooling.
  133. # This happens if you choose a dimensionality not equal 2048.
  134. if pred.shape[2] != 1 or pred.shape[3] != 1:
  135. pred = adaptive_avg_pool2d(pred, output_size=(1, 1))
  136. pred_arr[start:end] = pred.cpu().data.numpy().reshape(batch_size, -1)
  137. if verbose:
  138. print(' done')
  139. return pred_arr
  140. def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):
  141. """Numpy implementation of the Frechet Distance.
  142. The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)
  143. and X_2 ~ N(mu_2, C_2) is
  144. d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).
  145. Stable version by Dougal J. Sutherland.
  146. Params:
  147. -- mu1 : Numpy array containing the activations of a layer of the
  148. inception net (like returned by the function 'get_predictions')
  149. for generated samples.
  150. -- mu2 : The sample mean over activations, precalculated on an
  151. representative data set.
  152. -- sigma1: The covariance matrix over activations for generated samples.
  153. -- sigma2: The covariance matrix over activations, precalculated on an
  154. representative data set.
  155. Returns:
  156. -- : The Frechet Distance.
  157. """
  158. mu1 = np.atleast_1d(mu1)
  159. mu2 = np.atleast_1d(mu2)
  160. sigma1 = np.atleast_2d(sigma1)
  161. sigma2 = np.atleast_2d(sigma2)
  162. assert (
  163. mu1.shape == mu2.shape
  164. ), 'Training and test mean vectors have different lengths'
  165. assert (
  166. sigma1.shape == sigma2.shape
  167. ), 'Training and test covariances have different dimensions'
  168. diff = mu1 - mu2
  169. # Product might be almost singular
  170. covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)
  171. if not np.isfinite(covmean).all():
  172. msg = (
  173. 'fid calculation produces singular product; '
  174. 'adding %s to diagonal of cov estimates'
  175. ) % eps
  176. print(msg)
  177. offset = np.eye(sigma1.shape[0]) * eps
  178. covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))
  179. # Numerical error might give slight imaginary component
  180. if np.iscomplexobj(covmean):
  181. if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):
  182. m = np.max(np.abs(covmean.imag))
  183. raise ValueError('Imaginary component {}'.format(m))
  184. covmean = covmean.real
  185. tr_covmean = np.trace(covmean)
  186. return diff.dot(diff) + np.trace(sigma1) + np.trace(sigma2) - 2 * tr_covmean
  187. def calculate_activation_statistics(
  188. files, model, batch_size=50, dims=2048, cuda=False, verbose=False
  189. ):
  190. """Calculation of the statistics used by the FID.
  191. Params:
  192. -- files : List of image files paths
  193. -- model : Instance of inception model
  194. -- batch_size : The images numpy array is split into batches with
  195. batch size batch_size. A reasonable batch size
  196. depends on the hardware.
  197. -- dims : Dimensionality of features returned by Inception
  198. -- cuda : If set to True, use GPU
  199. -- verbose : If set to True and parameter out_step is given, the
  200. number of calculated batches is reported.
  201. Returns:
  202. -- mu : The mean over samples of the activations of the pool_3 layer of
  203. the inception model.
  204. -- sigma : The covariance matrix of the activations of the pool_3 layer of
  205. the inception model.
  206. """
  207. act = get_activations(files, model, batch_size, dims, cuda, verbose)
  208. mu = np.mean(act, axis=0)
  209. sigma = np.cov(act, rowvar=False)
  210. return mu, sigma
  211. def _compute_statistics_of_path(path, model, batch_size, dims, cuda):
  212. if path.endswith('.npz'):
  213. f = np.load(path)
  214. m, s = f['mu'][:], f['sigma'][:]
  215. f.close()
  216. else:
  217. path = pathlib.Path(path)
  218. files = list(path.glob('*.jpg')) + list(path.glob('*.png'))
  219. m, s = calculate_activation_statistics(files, model, batch_size, dims, cuda)
  220. return m, s
  221. def calculate_fid_given_paths(paths, batch_size, cuda, dims):
  222. """Calculates the FID of two paths"""
  223. for p in paths:
  224. if not os.path.exists(p):
  225. raise RuntimeError('Invalid path: %s' % p)
  226. block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[dims]
  227. model = InceptionV3([block_idx])
  228. if cuda:
  229. model.cuda()
  230. m1, s1 = _compute_statistics_of_path(paths[0], model, batch_size, dims, cuda)
  231. m2, s2 = _compute_statistics_of_path(paths[1], model, batch_size, dims, cuda)
  232. fid_value = calculate_frechet_distance(m1, s1, m2, s2)
  233. return fid_value
  234. if __name__ == '__main__':
  235. args = parser.parse_args()
  236. os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu
  237. fid_value = calculate_fid_given_paths(
  238. args.path, args.batch_size, args.gpu != '', args.dims
  239. )
  240. print('FID: ', fid_value)