Path: blob/master/src/metrics/ins_tf13.py
809 views
''' Tensorflow inception score code1Derived from https://github.com/openai/improved-gan2Code derived from tensorflow/tensorflow/models/image/imagenet/classify_image.py3THIS CODE REQUIRES TENSORFLOW 1.3 or EARLIER to run in PARALLEL BATCH MODE4To use this code, run sample.py on your model with --sample_npz, and then5pass the experiment name in the --experiment_name.6This code also saves pool3 stats to an npz file for FID calculation7'''89from __future__ import absolute_import10from __future__ import division11from __future__ import print_function1213import os.path14import sys15import tarfile16import math17from argparse import ArgumentParser1819from six.moves import urllib20from tqdm import tqdm, trange21import tensorflow as tf22import numpy as np2324MODEL_DIR = './inception_model'25DATA_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'26softmax = None272829def prepare_parser():30usage = 'Parser for TF1.3- Inception Score scripts.'31parser = ArgumentParser(description=usage)32parser.add_argument('--run_name',33type=str,34default='',35help='Which experiment'36's samples.npz file to pull and evaluate')37parser.add_argument('--type', type=str, default='', help='[real, fake]')38parser.add_argument('--batch_size', type=int, default=500, help='Default overall batchsize (default: %(default)s)')39return parser404142def run(config):43# Inception with TF1.3 or earlier.44# Call this function with list of images. Each of elements should be a45# numpy array with values ranging from 0 to 255.46def get_inception_score(images, splits=10):47assert (type(images) == list)48assert (type(images[0]) == np.ndarray)49assert (len(images[0].shape) == 3)50assert (np.max(images[0]) > 10)51assert (np.min(images[0]) >= 0.0)52inps = []53for img in images:54img = img.astype(np.float32)55inps.append(np.expand_dims(img, 0))56bs = config['batch_size']57with tf.Session() as sess:58preds, pools = [], []59n_batches = int(math.ceil(float(len(inps)) / float(bs)))60for i in trange(n_batches):61inp = inps[(i * bs):min((i + 1) * bs, len(inps))]62inp = np.concatenate(inp, 0)63pred, pool = sess.run([softmax, pool3], {'ExpandDims:0': inp})64preds.append(pred)65pools.append(pool)66preds = np.concatenate(preds, 0)67scores = []68for i in range(splits):69part = preds[(i * preds.shape[0] // splits):((i + 1) * preds.shape[0] // splits), :]70kl = part * (np.log(part) - np.log(np.expand_dims(np.mean(part, 0), 0)))71kl = np.mean(np.sum(kl, 1))72scores.append(np.exp(kl))73return np.mean(scores), np.std(scores), np.squeeze(np.concatenate(pools, 0))7475# Init inception76def _init_inception():77global softmax, pool378if not os.path.exists(MODEL_DIR):79os.makedirs(MODEL_DIR)80filename = DATA_URL.split('/')[-1]81filepath = os.path.join(MODEL_DIR, filename)82if not os.path.exists(filepath):8384def _progress(count, block_size, total_size):85sys.stdout.write('\r>> Downloading %s %.1f%%' %86(filename, float(count * block_size) / float(total_size) * 100.0))87sys.stdout.flush()8889filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)90print()91statinfo = os.stat(filepath)92print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.')93tarfile.open(filepath, 'r:gz').extractall(MODEL_DIR)94with tf.gfile.FastGFile(os.path.join(MODEL_DIR, 'classify_image_graph_def.pb'), 'rb') as f:95graph_def = tf.GraphDef()96graph_def.ParseFromString(f.read())97_ = tf.import_graph_def(graph_def, name='')98# Works with an arbitrary minibatch size.99with tf.Session() as sess:100pool3 = sess.graph.get_tensor_by_name('pool_3:0')101ops = pool3.graph.get_operations()102for op_idx, op in enumerate(ops):103for o in op.outputs:104shape = o.get_shape()105shape = [s.value for s in shape]106new_shape = []107for j, s in enumerate(shape):108if s == 1 and j == 0:109new_shape.append(None)110else:111new_shape.append(s)112o._shape = tf.TensorShape(new_shape)113w = sess.graph.get_operation_by_name("softmax/logits/MatMul").inputs[1]114logits = tf.matmul(tf.squeeze(pool3), w)115softmax = tf.nn.softmax(logits)116117# if softmax is None: # No need to functionalize like this.118_init_inception()119120fname = '%s/%s/%s/%s/samples.npz' % ("samples", config['run_name'], config['type'], "npz")121print('loading %s ...' % fname)122ims = np.load(fname)['x']123import time124t0 = time.time()125inc_mean, inc_std, pool_activations = get_inception_score(list(ims.swapaxes(1, 2).swapaxes(2, 3)), splits=1)126t1 = time.time()127print('Inception took %3f seconds, score of %3f +/- %3f.' % (t1 - t0, inc_mean, inc_std))128129130def main():131# parse command line and run132parser = prepare_parser()133config = vars(parser.parse_args())134print(config)135run(config)136137138if __name__ == '__main__':139main()140141142