Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132937 views
License: OTHER
1
"""DeepDream.
2
"""
3
from __future__ import absolute_import
4
from __future__ import division
5
from __future__ import print_function
6
7
import os.path
8
import zipfile
9
10
import sys
11
sys.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'])
12
13
14
import numpy as np
15
import PIL.Image
16
17
import tensorflow as tf
18
19
FLAGS = tf.app.flags.FLAGS
20
21
22
tf.app.flags.DEFINE_string('data_dir',
23
'/tmp/inception/',
24
'Directory for storing Inception network.')
25
26
tf.app.flags.DEFINE_string('jpeg_file',
27
'output.jpg',
28
'Where to save the resulting JPEG.')
29
30
31
def get_layer(layer):
32
"""Helper for getting layer output Tensor in model Graph.
33
34
Args:
35
layer: string, layer name
36
37
Returns:
38
Tensor for that layer.
39
"""
40
graph = tf.get_default_graph()
41
return graph.get_tensor_by_name('import/%s:0' % layer)
42
43
44
def maybe_download(data_dir):
45
"""Maybe download pretrained Inception network.
46
47
Args:
48
data_dir: string, path to data
49
"""
50
url = ('https://storage.googleapis.com/download.tensorflow.org/models/'
51
'inception5h.zip')
52
basename = 'inception5h.zip'
53
local_file = tf.contrib.learn.python.learn.datasets.base.maybe_download(
54
basename, data_dir, url)
55
56
# Uncompress the pretrained Inception network.
57
print('Extracting', local_file)
58
zip_ref = zipfile.ZipFile(local_file, 'r')
59
zip_ref.extractall(FLAGS.data_dir)
60
zip_ref.close()
61
62
63
def normalize_image(image):
64
"""Stretch the range and prepare the image for saving as a JPEG.
65
66
Args:
67
image: numpy array
68
69
Returns:
70
numpy array of image in uint8
71
"""
72
# Clip to [0, 1] and then convert to uint8.
73
image = np.clip(image, 0, 1)
74
image = np.uint8(image * 255)
75
return image
76
77
78
def save_jpeg(jpeg_file, image):
79
pil_image = PIL.Image.fromarray(image)
80
pil_image.save(jpeg_file)
81
print('Saved to file: ', jpeg_file)
82
83
84
def main(unused_argv):
85
# Maybe download and uncompress pretrained Inception network.
86
maybe_download(FLAGS.data_dir)
87
88
model_fn = os.path.join(FLAGS.data_dir, 'tensorflow_inception_graph.pb')
89
90
# Load the pretrained Inception model as a GraphDef.
91
with tf.gfile.FastGFile(model_fn, 'rb') as f:
92
graph_def = tf.GraphDef()
93
graph_def.ParseFromString(f.read())
94
95
with tf.Graph().as_default():
96
# Input for the network.
97
input_image = tf.placeholder(np.float32, name='input')
98
pixel_mean = 117.0
99
input_preprocessed = tf.expand_dims(input_image - pixel_mean, 0)
100
tf.import_graph_def(graph_def, {'input': input_preprocessed})
101
102
# Grab a list of the names of Tensor's that are the output of convolutions.
103
graph = tf.get_default_graph()
104
layers = [op.name for op in graph.get_operations()
105
if op.type == 'Conv2D' and 'import/' in op.name]
106
feature_nums = [int(graph.get_tensor_by_name(name+':0').get_shape()[-1])
107
for name in layers]
108
# print('Layers available: %s' % ','.join(layers))
109
print('Number of layers', len(layers))
110
print('Number of features:', sum(feature_nums))
111
112
# Pick an internal layer and node to visualize.
113
# Note that we use outputs before applying the ReLU nonlinearity to
114
# have non-zero gradients for features with negative initial activations.
115
layer = 'mixed4d_3x3_bottleneck_pre_relu'
116
channel = 139
117
layer_channel = get_layer(layer)[:, :, :, channel]
118
print('layer %s, channel %d: %s' % (layer, channel, layer_channel))
119
120
# Define the optimization as the average across all spatial locations.
121
score = tf.reduce_mean(layer_channel)
122
123
# Automatic differentiation with TensorFlow. Magic!
124
input_gradient = tf.gradients(score, input_image)[0]
125
126
# Employ random noise as a image.
127
noise_image = np.random.uniform(size=(224, 224, 3)) + 100.0
128
image = noise_image.copy()
129
130
################################################################
131
### BEGIN SOLUTION #####
132
################################################################
133
step_scale = 1.0
134
num_iter = 20
135
with tf.Session() as sess:
136
for i in xrange(num_iter):
137
image_gradient, score_value = sess.run([input_gradient, score], {input_image:image})
138
# Normalize the gradient, so the same step size should work
139
image_gradient /= image_gradient.std() + 1e-8
140
image += image_gradient * step_scale
141
print('At step = %d, score = %.3f' % (i, score_value))
142
143
# Save the image.
144
stddev = 0.1
145
image = (image - image.mean()) / max(image.std(), 1e-4) * stddev + 0.5
146
image = normalize_image(image)
147
save_jpeg(FLAGS.jpeg_file, image)
148
##################################################################
149
### END SOLUTION #####
150
##################################################################
151
152
153
if __name__ == '__main__':
154
tf.app.run()
155