├── .gitignore ├── LICENSE.md ├── README.md └── inception_score.py /.gitignore: -------------------------------------------------------------------------------- 1 | data/ 2 | 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | *$py.class 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | .hypothesis/ 50 | 51 | # Translations 52 | *.mo 53 | *.pot 54 | 55 | # Django stuff: 56 | *.log 57 | .static_storage/ 58 | .media/ 59 | local_settings.py 60 | 61 | # Flask stuff: 62 | instance/ 63 | .webassets-cache 64 | 65 | # Scrapy stuff: 66 | .scrapy 67 | 68 | # Sphinx documentation 69 | docs/_build/ 70 | 71 | # PyBuilder 72 | target/ 73 | 74 | # Jupyter Notebook 75 | .ipynb_checkpoints 76 | 77 | # pyenv 78 | .python-version 79 | 80 | # celery beat schedule file 81 | celerybeat-schedule 82 | 83 | # SageMath parsed files 84 | *.sage.py 85 | 86 | # Environments 87 | .env 88 | .venv 89 | env/ 90 | venv/ 91 | ENV/ 92 | env.bak/ 93 | venv.bak/ 94 | 95 | # Spyder project settings 96 | .spyderproject 97 | .spyproject 98 | 99 | # Rope project settings 100 | .ropeproject 101 | 102 | # mkdocs documentation 103 | /site 104 | 105 | # mypy 106 | .mypy_cache/ 107 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Copyright 2017 Shane T. Barratt 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Inception Score Pytorch 2 | 3 | Pytorch was lacking code to calculate the Inception Score for GANs. This repository fills this gap. 4 | However, we do not recommend using the Inception Score to evaluate generative models, see [our note](https://arxiv.org/abs/1801.01973) for why. 5 | 6 | ## Getting Started 7 | 8 | Clone the repository and navigate to it: 9 | ``` 10 | $ git clone git@github.com:sbarratt/inception-score-pytorch.git 11 | $ cd inception-score-pytorch 12 | ``` 13 | 14 | To generate random 64x64 images and calculate the inception score, do the following: 15 | ``` 16 | $ python inception_score.py 17 | ``` 18 | 19 | The only function is `inception_score`. It takes a list of numpy images normalized to the range [0,1] and a set of arguments and then calculates the inception score. Please assure your images are 3x299x299 and if not (e.g. your GAN was trained on CIFAR), pass `resize=True` to the function to have it automatically resize using bilinear interpolation before passing the images to the inception network. 20 | 21 | ```python 22 | def inception_score(imgs, cuda=True, batch_size=32, resize=False, splits=1): 23 | """Computes the inception score of the generated images imgs 24 | imgs -- Torch dataset of (3xHxW) numpy images normalized in the range [-1, 1] 25 | cuda -- whether or not to run on GPU 26 | batch_size -- batch size for feeding into Inception v3 27 | splits -- number of splits 28 | """ 29 | ``` 30 | 31 | ### Prerequisites 32 | 33 | You will need [torch](http://pytorch.org/), [torchvision](https://github.com/pytorch/vision), [numpy/scipy](https://scipy.org/). 34 | 35 | ## License 36 | 37 | This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details 38 | 39 | ## Acknowledgments 40 | 41 | * Inception Score from [Improved Techniques for Training GANs](https://arxiv.org/abs/1606.03498) 42 | -------------------------------------------------------------------------------- /inception_score.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from torch.autograd import Variable 4 | from torch.nn import functional as F 5 | import torch.utils.data 6 | 7 | from torchvision.models.inception import inception_v3 8 | 9 | import numpy as np 10 | from scipy.stats import entropy 11 | 12 | def inception_score(imgs, cuda=True, batch_size=32, resize=False, splits=1): 13 | """Computes the inception score of the generated images imgs 14 | 15 | imgs -- Torch dataset of (3xHxW) numpy images normalized in the range [-1, 1] 16 | cuda -- whether or not to run on GPU 17 | batch_size -- batch size for feeding into Inception v3 18 | splits -- number of splits 19 | """ 20 | N = len(imgs) 21 | 22 | assert batch_size > 0 23 | assert N > batch_size 24 | 25 | # Set up dtype 26 | if cuda: 27 | dtype = torch.cuda.FloatTensor 28 | else: 29 | if torch.cuda.is_available(): 30 | print("WARNING: You have a CUDA device, so you should probably set cuda=True") 31 | dtype = torch.FloatTensor 32 | 33 | # Set up dataloader 34 | dataloader = torch.utils.data.DataLoader(imgs, batch_size=batch_size) 35 | 36 | # Load inception model 37 | inception_model = inception_v3(pretrained=True, transform_input=False).type(dtype) 38 | inception_model.eval(); 39 | up = nn.Upsample(size=(299, 299), mode='bilinear').type(dtype) 40 | def get_pred(x): 41 | if resize: 42 | x = up(x) 43 | x = inception_model(x) 44 | return F.softmax(x).data.cpu().numpy() 45 | 46 | # Get predictions 47 | preds = np.zeros((N, 1000)) 48 | 49 | for i, batch in enumerate(dataloader, 0): 50 | batch = batch.type(dtype) 51 | batchv = Variable(batch) 52 | batch_size_i = batch.size()[0] 53 | 54 | preds[i*batch_size:i*batch_size + batch_size_i] = get_pred(batchv) 55 | 56 | # Now compute the mean kl-div 57 | split_scores = [] 58 | 59 | for k in range(splits): 60 | part = preds[k * (N // splits): (k+1) * (N // splits), :] 61 | py = np.mean(part, axis=0) 62 | scores = [] 63 | for i in range(part.shape[0]): 64 | pyx = part[i, :] 65 | scores.append(entropy(pyx, py)) 66 | split_scores.append(np.exp(np.mean(scores))) 67 | 68 | return np.mean(split_scores), np.std(split_scores) 69 | 70 | if __name__ == '__main__': 71 | class IgnoreLabelDataset(torch.utils.data.Dataset): 72 | def __init__(self, orig): 73 | self.orig = orig 74 | 75 | def __getitem__(self, index): 76 | return self.orig[index][0] 77 | 78 | def __len__(self): 79 | return len(self.orig) 80 | 81 | import torchvision.datasets as dset 82 | import torchvision.transforms as transforms 83 | 84 | cifar = dset.CIFAR10(root='data/', download=True, 85 | transform=transforms.Compose([ 86 | transforms.Scale(32), 87 | transforms.ToTensor(), 88 | transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) 89 | ]) 90 | ) 91 | 92 | IgnoreLabelDataset(cifar) 93 | 94 | print ("Calculating Inception Score...") 95 | print (inception_score(IgnoreLabelDataset(cifar), cuda=True, batch_size=32, resize=True, splits=10)) 96 | --------------------------------------------------------------------------------