Documentos de Académico
Documentos de Profesional
Documentos de Cultura
https://medium.com/tensorflow/neural-style-transfer-creating-art-with-deep-learning-using-tf-keras-and-eager-execution-7d541ac31398 1/21
19/3/2019 Transferencia de estilo neuronal: crear arte con aprendizaje profundo usando tf.keras y una ejecución impecable
Is this magic or just deep learning? Fortunately, this doesn’t involve any
magic: style transfer is a fun and interesting technique that showcases
the capabilities and internal representations of neural networks.
In summary, we’ll take the base input image, a content image that we
want to match, and the style image that we want to match. We’ll
transform the base input image by minimizing the content and style
https://medium.com/tensorflow/neural-style-transfer-creating-art-with-deep-learning-using-tf-keras-and-eager-execution-7d541ac31398 2/21
19/3/2019 Transferencia de estilo neuronal: crear arte con aprendizaje profundo usando tf.keras y una ejecución impecable
4. Create model
https://medium.com/tensorflow/neural-style-transfer-creating-art-with-deep-learning-using-tf-keras-and-eager-execution-7d541ac31398 3/21
19/3/2019 Transferencia de estilo neuronal: crear arte con aprendizaje profundo usando tf.keras y una ejecución impecable
• Read Gatys’ paper — we’ll explain along the way, but the paper will
provide a more thorough understanding of the task
Code:
You can nd the complete code for this article at this link. If you’d like to
step through this example, you can nd the colab here.
Implementation
We’ll begin by enabling eager execution. Eager execution allows us to
work through this technique in the clearest and most readable way.
1 tf.enable_eager_execution ()
2 imprimir ( " Ejecución impaciente: {} " .format (tf.exec
3
4 Aquí están las imágenes de contenido y estilo que usarem
5 plt.figure ( figsize = ( 10 , 10 ))
6
7 content = load_img(content_path).astype('uint8')
8 style = load_img(style_path)
9
10 plt.subplot(1, 2, 1)
11 i h ( t t 'C t t I ')
Image of Green Sea Tu rtle -By P .Lindgren from Wikimedia Commons and Image of The Great
Wave O Kanagawa from by Katsu shika Hoku sai Pu blic Domain
https://medium.com/tensorflow/neural-style-transfer-creating-art-with-deep-learning-using-tf-keras-and-eager-execution-7d541ac31398 4/21
19/3/2019 Transferencia de estilo neuronal: crear arte con aprendizaje profundo usando tf.keras y una ejecución impecable
Speci cally we’ll pull out these intermediate layers from our network:
https://medium.com/tensorflow/neural-style-transfer-creating-art-with-deep-learning-using-tf-keras-and-eager-execution-7d541ac31398 5/21
19/3/2019 Transferencia de estilo neuronal: crear arte con aprendizaje profundo usando tf.keras y una ejecución impecable
Model
In this case, we load VGG19, and feed in our input tensor to the model.
This will allow us to extract the feature maps (and subsequently the
content and style representations) of the content, style, and generated
images.
With the Functional API, de ning a model simply involves de ning the
input and output: model = Model(inputs, outputs) .
https://medium.com/tensorflow/neural-style-transfer-creating-art-with-deep-learning-using-tf-keras-and-eager-execution-7d541ac31398 6/21
19/3/2019 Transferencia de estilo neuronal: crear arte con aprendizaje profundo usando tf.keras y una ejecución impecable
1 def get_model():
2 """ Creates our model with access to intermediate laye
3
4 This function will load the VGG19 model and access the
5 These layers will then be used to create a new model t
6 and return the outputs from these intermediate layers
7
8 Returns:
9 returns a keras model that takes image inputs and ou
10 content intermediate layers.
11 """
12 # Load our model. We load pretrained VGG, trained on i
13 vgg = tf.keras.applications.vgg19.VGG19(include_top=Fa
14 vgg trainable = False
In the above code snippet, we’ll load our pretrained image classi cation
network. Then we grab the layers of interest as we de ned earlier. Then
we de ne a Model by setting the model’s inputs to an image and the
outputs to the outputs of the style and content layers. In other words,
we created a model that will take an input image and output the content
and style intermediate layers!
https://medium.com/tensorflow/neural-style-transfer-creating-art-with-deep-learning-using-tf-keras-and-eager-execution-7d541ac31398 7/21
19/3/2019 Transferencia de estilo neuronal: crear arte con aprendizaje profundo usando tf.keras y una ejecución impecable
This can be implemented quite simply. Again it will take as input the
feature maps at a layer L in a network fed by x, our input image, and p,
our content image, and return the content distance.
Style Loss:
Computing style loss is a bit more involved, but follows the same
principle, this time feeding our network the base input image and the
style image. However, instead of comparing the raw intermediate
outputs of the base input image and the style image, we instead
compare the Gram matrices of the two outputs.
https://medium.com/tensorflow/neural-style-transfer-creating-art-with-deep-learning-using-tf-keras-and-eager-execution-7d541ac31398 8/21
19/3/2019 Transferencia de estilo neuronal: crear arte con aprendizaje profundo usando tf.keras y una ejecución impecable
where Gˡᵢⱼ and Aˡᵢⱼ are the respective style representation in layer l of
input image x and style image a. Nl describes the number of feature
maps, each of size Ml=height∗width. Thus, the total style loss across
each layer is
where we weight the contribution of each layer’s loss by some factor wl.
In our case, we weight each layer equally:
1 def gram_matrix(input_tensor):
2 # We make the image channels first
3 channels = int(input_tensor.shape[-1])
4 a = tf.reshape(input_tensor, [-1, channels])
5 n = tf.shape(a)[0]
6 gram = tf.matmul(a, a, transpose_a=True)
7 return gram / tf.cast(n, tf.float32)
8
9 def get_style_loss(base_style, gram_target):
10 """Expects two images of dimension h, w, c"""
11 # h i ht idth filt f h l
In this case, we use the Adam optimizer in order to minimize our loss.
We iteratively update our output image such that it minimizes our loss:
https://medium.com/tensorflow/neural-style-transfer-creating-art-with-deep-learning-using-tf-keras-and-eager-execution-7d541ac31398 9/21
19/3/2019 Transferencia de estilo neuronal: crear arte con aprendizaje profundo usando tf.keras y una ejecución impecable
we don’t update the weights associated with our network, but instead
we train our input image to minimize loss. In order to do this, we must
know how we calculate our loss and gradients. Note that the L-BFGS
optimizer, which if you are familiar with this algorithm is
recommended, but isn’t used in this tutorial because a primary
motivation behind this tutorial was to illustrate best practices with
eager execution. By using Adam, we can demonstrate the
autograd/gradient tape functionality with custom training loops.
https://medium.com/tensorflow/neural-style-transfer-creating-art-with-deep-learning-using-tf-keras-and-eager-execution-7d541ac31398 10/21
19/3/2019 Transferencia de estilo neuronal: crear arte con aprendizaje profundo usando tf.keras y una ejecución impecable
1 def compute_grads(cfg):
2 with tf.GradientTape() as tape:
3 all_loss = compute_loss(**cfg)
4 # Compute gradients wrt input image
5 total_loss = all_loss[0]
https://medium.com/tensorflow/neural-style-transfer-creating-art-with-deep-learning-using-tf-keras-and-eager-execution-7d541ac31398 11/21
19/3/2019 Transferencia de estilo neuronal: crear arte con aprendizaje profundo usando tf.keras y una ejecución impecable
https://medium.com/tensorflow/neural-style-transfer-creating-art-with-deep-learning-using-tf-keras-and-eager-execution-7d541ac31398 12/21
19/3/2019 Transferencia de estilo neuronal: crear arte con aprendizaje profundo usando tf.keras y una ejecución impecable
1 def run_style_transfer(content_path,
2 style_path,
3 num_iterations=1000,
4 content_weight=1e3,
5 style_weight = 1e-2):
6 display_num = 100
7 # We don't need to (or want to) train any layers of ou
8 # to false.
9 model = get_model()
10 for layer in model.layers:
11 layer.trainable = False
12
13 # Get the style and content feature representations (f
14 style_features, content_features = get_feature_represe
15 gram_style_features = [gram_matrix(style_feature) for
16
17 # Set initial image
18 init_image = load_and_process_img(content_path)
19 init_image = tfe.Variable(init_image, dtype=tf.float32
20 # Create our optimizer
21 opt = tf.train.AdamOptimizer(learning_rate=10.0)
22
23 # For displaying intermediate images
24 iter_count = 1
25
26 # Store our best result
27 best_loss, best_img = float('inf'), None
28
29 # Create a nice config
30 loss_weights = (style_weight, content_weight)
31 cfg = {
32 'model': model,
33 'loss_weights': loss_weights,
34 'init_image': init_image,
35 'gram_style_features': gram_style_features,
36 'content_features': content_features
37 }
38
39 # For displaying
40 plt.figure(figsize=(15, 15))
41 num_rows = (num_iterations / display_num) // 5
42 t t ti ti ti ()
https://medium.com/tensorflow/neural-style-transfer-creating-art-with-deep-learning-using-tf-keras-and-eager-execution-7d541ac31398 13/21
19/3/2019 Transferencia de estilo neuronal: crear arte con aprendizaje profundo usando tf.keras y una ejecución impecable
42 start_time = time.time()
43 global_start = time.time()
44
45 norm_means = np.array([103.939, 116.779, 123.68])
46 min_vals = -norm_means
47 max_vals = 255 - norm_means
48 for i in range(num_iterations):
49 grads, all_loss = compute_grads(cfg)
50 loss, style_score, content_score = all_loss
51 # grads, _ = tf.clip_by_global_norm(grads, 5.0)
52 opt.apply_gradients([(grads, init_image)])
53 clipped = tf clip by value(init image min vals max
Let’s run it on our image of the turtle and Hokusai’s The Great Wave o
Kanagawa:
https://medium.com/tensorflow/neural-style-transfer-creating-art-with-deep-learning-using-tf-keras-and-eager-execution-7d541ac31398 14/21
19/3/2019 Transferencia de estilo neuronal: crear arte con aprendizaje profundo usando tf.keras y una ejecución impecable
https://medium.com/tensorflow/neural-style-transfer-creating-art-with-deep-learning-using-tf-keras-and-eager-execution-7d541ac31398 15/21
19/3/2019 Transferencia de estilo neuronal: crear arte con aprendizaje profundo usando tf.keras y una ejecución impecable
Here are some other cool examples of what neural style transfer can do.
Check it out!
https://medium.com/tensorflow/neural-style-transfer-creating-art-with-deep-learning-using-tf-keras-and-eager-execution-7d541ac31398 16/21
19/3/2019 Transferencia de estilo neuronal: crear arte con aprendizaje profundo usando tf.keras y una ejecución impecable
https://medium.com/tensorflow/neural-style-transfer-creating-art-with-deep-learning-using-tf-keras-and-eager-execution-7d541ac31398 17/21
19/3/2019 Transferencia de estilo neuronal: crear arte con aprendizaje profundo usando tf.keras y una ejecución impecable
https://medium.com/tensorflow/neural-style-transfer-creating-art-with-deep-learning-using-tf-keras-and-eager-execution-7d541ac31398 18/21
19/3/2019 Transferencia de estilo neuronal: crear arte con aprendizaje profundo usando tf.keras y una ejecución impecable
Key Takeaways
What we covered:
• We built several di erent loss functions and used backpropagation
to transform our input image in order to minimize these losses.
https://medium.com/tensorflow/neural-style-transfer-creating-art-with-deep-learning-using-tf-keras-and-eager-execution-7d541ac31398 19/21
19/3/2019 Transferencia de estilo neuronal: crear arte con aprendizaje profundo usando tf.keras y una ejecución impecable
https://medium.com/tensorflow/neural-style-transfer-creating-art-with-deep-learning-using-tf-keras-and-eager-execution-7d541ac31398 20/21
19/3/2019 Transferencia de estilo neuronal: crear arte con aprendizaje profundo usando tf.keras y una ejecución impecable
https://medium.com/tensorflow/neural-style-transfer-creating-art-with-deep-learning-using-tf-keras-and-eager-execution-7d541ac31398 21/21