visualize_vggface.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import numpy as np
  2. import tensorflow as tf
  3. import matplotlib.pyplot as plt
  4. import tmp.vggface16
  5. def main():
  6. sess = tf.Session()
  7. t_input = tf.placeholder(np.float32, name='input') # define the input tensor
  8. image_mean = 117.0
  9. t_preprocessed = tf.expand_dims(t_input-image_mean, 0)
  10. # Build the inference graph
  11. nodes = tmp.vggface16.load('data/vgg_face.mat', t_preprocessed)
  12. img_noise = np.random.uniform(size=(224,224,3)) + 117.0
  13. # Picking some internal layer. Note that we use outputs before applying the ReLU nonlinearity
  14. # to have non-zero gradients for features with negative initial activations.
  15. layer = 'conv5_3'
  16. channel = 140 # picking some feature channel to visualize
  17. img = render_naive(sess, t_input, nodes[layer][:,:,:,channel], img_noise)
  18. showarray(img)
  19. def showarray(a):
  20. a = np.uint8(np.clip(a, 0, 1)*255)
  21. plt.imshow(a)
  22. plt.show()
  23. def visstd(a, s=0.1):
  24. '''Normalize the image range for visualization'''
  25. return (a-a.mean())/max(a.std(), 1e-4)*s + 0.5
  26. def render_naive(sess, t_input, t_obj, img0, iter_n=20, step=1.0):
  27. t_score = tf.reduce_mean(t_obj) # defining the optimization objective
  28. t_grad = tf.gradients(t_score, t_input)[0] # behold the power of automatic differentiation!
  29. img = img0.copy()
  30. for _ in range(iter_n):
  31. g, _ = sess.run([t_grad, t_score], {t_input:img})
  32. # normalizing the gradient, so the same step size should work
  33. g /= g.std()+1e-8 # for different layers and networks
  34. img += g*step
  35. return visstd(img)
  36. if __name__ == '__main__':
  37. main()