visualize.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. """Visualize individual feature channels and their combinations to explore the space of patterns learned by the neural network
  2. Based on http://nbviewer.jupyter.org/github/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/deepdream/deepdream.ipynb
  3. """
  4. # MIT License
  5. #
  6. # Copyright (c) 2016 David Sandberg
  7. #
  8. # Permission is hereby granted, free of charge, to any person obtaining a copy
  9. # of this software and associated documentation files (the "Software"), to deal
  10. # in the Software without restriction, including without limitation the rights
  11. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. # copies of the Software, and to permit persons to whom the Software is
  13. # furnished to do so, subject to the following conditions:
  14. #
  15. # The above copyright notice and this permission notice shall be included in all
  16. # copies or substantial portions of the Software.
  17. #
  18. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24. # SOFTWARE.
  25. from __future__ import absolute_import
  26. from __future__ import division
  27. from __future__ import print_function
  28. import os
  29. import numpy as np
  30. import sys
  31. import argparse
  32. import tensorflow as tf
  33. import importlib
  34. from scipy import misc
  35. def main(args):
  36. network = importlib.import_module(args.model_def, 'inference')
  37. # Start with a gray image with a little noise
  38. np.random.seed(seed=args.seed)
  39. img_noise = np.random.uniform(size=(args.image_size,args.image_size,3)) + 100.0
  40. sess = tf.Session()
  41. t_input = tf.placeholder(np.float32, shape=(args.image_size,args.image_size,3), name='input') # define the input tensor
  42. image_mean = 117.0
  43. t_preprocessed = tf.expand_dims(t_input-image_mean, 0)
  44. # Build the inference graph
  45. network.inference(t_preprocessed, 1.0,
  46. phase_train=True, weight_decay=0.0)
  47. # Create a saver for restoring variables
  48. saver = tf.train.Saver(tf.global_variables())
  49. # Restore the parameters
  50. saver.restore(sess, args.model_file)
  51. layers = [op.name for op in tf.get_default_graph().get_operations() if op.type=='Conv2D']
  52. feature_nums = {layer: int(T(layer).get_shape()[-1]) for layer in layers}
  53. print('Number of layers: %d' % len(layers))
  54. for layer in sorted(feature_nums.keys()):
  55. print('%s%d' % ((layer+': ').ljust(40), feature_nums[layer]))
  56. # Picking some internal layer. Note that we use outputs before applying the ReLU nonlinearity
  57. # to have non-zero gradients for features with negative initial activations.
  58. layer = 'InceptionResnetV1/Repeat_2/block8_3/Conv2d_1x1/Conv2D'
  59. #layer = 'incept4b/in4_conv1x1_31/Conv2D'
  60. result_dir = '../data/'
  61. print('Number of features in layer "%s": %d' % (layer, feature_nums[layer]))
  62. channels = range(feature_nums[layer])
  63. np.random.shuffle(channels)
  64. for i in range(32):
  65. print('Rendering feature %d' % channels[i])
  66. channel = channels[i]
  67. img = render_naive(sess, t_input, T(layer)[:,:,:,channel], img_noise)
  68. filename = '%s_%03d.png' % (layer.replace('/', '_'), channel)
  69. misc.imsave(os.path.join(result_dir, filename), img)
  70. def T(layer):
  71. '''Helper for getting layer output tensor'''
  72. return tf.get_default_graph().get_tensor_by_name('%s:0' % layer)
  73. def visstd(a, s=0.1):
  74. '''Normalize the image range for visualization'''
  75. return (a-a.mean())/max(a.std(), 1e-4)*s + 0.5
  76. def render_naive(sess, t_input, t_obj, img0, iter_n=20, step=1.0):
  77. t_score = tf.reduce_mean(t_obj) # defining the optimization objective
  78. t_grad = tf.gradients(t_score, t_input)[0] # behold the power of automatic differentiation!
  79. img = img0.copy()
  80. for _ in range(iter_n):
  81. g, _ = sess.run([t_grad, t_score], {t_input:img})
  82. # normalizing the gradient, so the same step size should work
  83. g /= g.std()+1e-8 # for different layers and networks
  84. img += g*step
  85. return visstd(img)
  86. def parse_arguments(argv):
  87. parser = argparse.ArgumentParser()
  88. parser.add_argument('model_file', type=str,
  89. help='Directory containing the graph definition and checkpoint files.')
  90. parser.add_argument('--model_def', type=str,
  91. help='Model definition. Points to a module containing the definition of the inference graph.',
  92. default='models.nn4')
  93. parser.add_argument('--image_size', type=int,
  94. help='Image size (height, width) in pixels.', default=96)
  95. parser.add_argument('--seed', type=int,
  96. help='Random seed.', default=666)
  97. return parser.parse_args(argv)
  98. if __name__ == '__main__':
  99. main(parse_arguments(sys.argv[1:]))