📚 The CoCalc Library - books, templates and other resources
cocalc-examples / stanford-tensorflow-tutorials / 2017 / examples / deepdream / deepdream_solution.py
132937 viewsLicense: OTHER
"""DeepDream.1"""2from __future__ import absolute_import3from __future__ import division4from __future__ import print_function56import os.path7import zipfile89import sys10sys.path.extend(['', '/Users/shlens/Desktop/Neural-Art/homebrew/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/Users/shlens/Desktop/Neural-Art/homebrew/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/Users/shlens/Desktop/Neural-Art/homebrew/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/Users/shlens/Desktop/Neural-Art/homebrew/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/Users/shlens/Desktop/Neural-Art/homebrew/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/shlens/Desktop/Neural-Art/homebrew/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/Users/shlens/Desktop/Neural-Art/homebrew/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/Users/shlens/Desktop/Neural-Art/homebrew/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/Users/shlens/Desktop/Neural-Art/homebrew/lib/python2.7/site-packages', '/Users/shlens/Desktop/Neural-Art/homebrew/lib/python2.7/site-packages/gtk-2.0', '/Users/shlens/Desktop/Neural-Art/homebrew/lib/python2.7/site-packages/gtk-2.0'])111213import numpy as np14import PIL.Image1516import tensorflow as tf1718FLAGS = tf.app.flags.FLAGS192021tf.app.flags.DEFINE_string('data_dir',22'/tmp/inception/',23'Directory for storing Inception network.')2425tf.app.flags.DEFINE_string('jpeg_file',26'output.jpg',27'Where to save the resulting JPEG.')282930def get_layer(layer):31"""Helper for getting layer output Tensor in model Graph.3233Args:34layer: string, layer name3536Returns:37Tensor for that layer.38"""39graph = tf.get_default_graph()40return graph.get_tensor_by_name('import/%s:0' % layer)414243def maybe_download(data_dir):44"""Maybe download pretrained Inception network.4546Args:47data_dir: string, path to data48"""49url = ('https://storage.googleapis.com/download.tensorflow.org/models/'50'inception5h.zip')51basename = 'inception5h.zip'52local_file = tf.contrib.learn.python.learn.datasets.base.maybe_download(53basename, data_dir, url)5455# Uncompress the pretrained Inception network.56print('Extracting', local_file)57zip_ref = zipfile.ZipFile(local_file, 'r')58zip_ref.extractall(FLAGS.data_dir)59zip_ref.close()606162def normalize_image(image):63"""Stretch the range and prepare the image for saving as a JPEG.6465Args:66image: numpy array6768Returns:69numpy array of image in uint870"""71# Clip to [0, 1] and then convert to uint8.72image = np.clip(image, 0, 1)73image = np.uint8(image * 255)74return image757677def save_jpeg(jpeg_file, image):78pil_image = PIL.Image.fromarray(image)79pil_image.save(jpeg_file)80print('Saved to file: ', jpeg_file)818283def main(unused_argv):84# Maybe download and uncompress pretrained Inception network.85maybe_download(FLAGS.data_dir)8687model_fn = os.path.join(FLAGS.data_dir, 'tensorflow_inception_graph.pb')8889# Load the pretrained Inception model as a GraphDef.90with tf.gfile.FastGFile(model_fn, 'rb') as f:91graph_def = tf.GraphDef()92graph_def.ParseFromString(f.read())9394with tf.Graph().as_default():95# Input for the network.96input_image = tf.placeholder(np.float32, name='input')97pixel_mean = 117.098input_preprocessed = tf.expand_dims(input_image - pixel_mean, 0)99tf.import_graph_def(graph_def, {'input': input_preprocessed})100101# Grab a list of the names of Tensor's that are the output of convolutions.102graph = tf.get_default_graph()103layers = [op.name for op in graph.get_operations()104if op.type == 'Conv2D' and 'import/' in op.name]105feature_nums = [int(graph.get_tensor_by_name(name+':0').get_shape()[-1])106for name in layers]107# print('Layers available: %s' % ','.join(layers))108print('Number of layers', len(layers))109print('Number of features:', sum(feature_nums))110111# Pick an internal layer and node to visualize.112# Note that we use outputs before applying the ReLU nonlinearity to113# have non-zero gradients for features with negative initial activations.114layer = 'mixed4d_3x3_bottleneck_pre_relu'115channel = 139116layer_channel = get_layer(layer)[:, :, :, channel]117print('layer %s, channel %d: %s' % (layer, channel, layer_channel))118119# Define the optimization as the average across all spatial locations.120score = tf.reduce_mean(layer_channel)121122# Automatic differentiation with TensorFlow. Magic!123input_gradient = tf.gradients(score, input_image)[0]124125# Employ random noise as a image.126noise_image = np.random.uniform(size=(224, 224, 3)) + 100.0127image = noise_image.copy()128129################################################################130### BEGIN SOLUTION #####131################################################################132step_scale = 1.0133num_iter = 20134with tf.Session() as sess:135for i in xrange(num_iter):136image_gradient, score_value = sess.run([input_gradient, score], {input_image:image})137# Normalize the gradient, so the same step size should work138image_gradient /= image_gradient.std() + 1e-8139image += image_gradient * step_scale140print('At step = %d, score = %.3f' % (i, score_value))141142# Save the image.143stddev = 0.1144image = (image - image.mean()) / max(image.std(), 1e-4) * stddev + 0.5145image = normalize_image(image)146save_jpeg(FLAGS.jpeg_file, image)147##################################################################148### END SOLUTION #####149##################################################################150151152if __name__ == '__main__':153tf.app.run()154155