File: index.html

package info (click to toggle)
keras 2.3.1%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 9,288 kB
  • sloc: python: 48,266; javascript: 1,794; xml: 297; makefile: 36; sh: 30
file content (603 lines) | stat: -rw-r--r-- 25,648 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  
  <link rel="canonical" href="http://keras.io/examples/neural_style_transfer/">
  <link rel="shortcut icon" href="../../img/favicon.ico">
  <title>Neural style transfer - Keras Documentation</title>
  <link href='https://fonts.googleapis.com/css?family=Lato:400,700|Source+Sans+Pro:400,700|Inconsolata:400,700' rel='stylesheet' type='text/css'>

  <link rel="stylesheet" href="../../css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../../css/theme_extra.css" type="text/css" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/github.min.css">
  
  <script>
    // Current page data
    var mkdocs_page_name = "Neural style transfer";
    var mkdocs_page_input_path = "examples/neural_style_transfer.md";
    var mkdocs_page_url = "/examples/neural_style_transfer/";
  </script>
  
  <script src="../../js/jquery-2.1.1.min.js" defer></script>
  <script src="../../js/modernizr-2.8.3.min.js" defer></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
  <script>hljs.initHighlightingOnLoad();</script> 
  
  <script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

      ga('create', 'UA-61785484-1', 'keras.io');
      ga('send', 'pageview');
  </script>
  
</head>

<body class="wy-body-for-nav" role="document">

  <div class="wy-grid-for-nav">

    
    <nav data-toggle="wy-nav-shift" class="wy-nav-side stickynav">
    <div class="wy-side-scroll">
      <a href="">
        <div class="keras-logo">
          <img src="/img/keras-logo-small.jpg" class="keras-logo-img">
          Keras Documentation
        </div>
      </a>

      <div class="wy-side-nav-search">
        <div role="search">
  <form id ="rtd-search-form" class="wy-form" action="../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" title="Type search term here" />
  </form>
</div>
      </div>

      <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="../..">Home</a>
                    </li>
                </ul>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="../../why-use-keras/">Why use Keras</a>
                    </li>
                </ul>
                <p class="caption"><span class="caption-text">Getting started</span></p>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="../../getting-started/sequential-model-guide/">Guide to the Sequential model</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../../getting-started/functional-api-guide/">Guide to the Functional API</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../../getting-started/faq/">FAQ</a>
                    </li>
                </ul>
                <p class="caption"><span class="caption-text">Models</span></p>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="../../models/about-keras-models/">About Keras models</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../../models/sequential/">Sequential</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../../models/model/">Model (functional API)</a>
                    </li>
                </ul>
                <p class="caption"><span class="caption-text">Layers</span></p>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="../../layers/about-keras-layers/">About Keras layers</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../../layers/core/">Core Layers</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../../layers/convolutional/">Convolutional Layers</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../../layers/pooling/">Pooling Layers</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../../layers/local/">Locally-connected Layers</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../../layers/recurrent/">Recurrent Layers</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../../layers/embeddings/">Embedding Layers</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../../layers/merge/">Merge Layers</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../../layers/advanced-activations/">Advanced Activations Layers</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../../layers/normalization/">Normalization Layers</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../../layers/noise/">Noise layers</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../../layers/wrappers/">Layer wrappers</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../../layers/writing-your-own-keras-layers/">Writing your own Keras layers</a>
                    </li>
                </ul>
                <p class="caption"><span class="caption-text">Preprocessing</span></p>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="../../preprocessing/sequence/">Sequence Preprocessing</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../../preprocessing/text/">Text Preprocessing</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../../preprocessing/image/">Image Preprocessing</a>
                    </li>
                </ul>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="../../losses/">Losses</a>
                    </li>
                </ul>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="../../metrics/">Metrics</a>
                    </li>
                </ul>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="../../optimizers/">Optimizers</a>
                    </li>
                </ul>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="../../activations/">Activations</a>
                    </li>
                </ul>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="../../callbacks/">Callbacks</a>
                    </li>
                </ul>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="../../datasets/">Datasets</a>
                    </li>
                </ul>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="../../applications/">Applications</a>
                    </li>
                </ul>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="../../backend/">Backend</a>
                    </li>
                </ul>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="../../initializers/">Initializers</a>
                    </li>
                </ul>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="../../regularizers/">Regularizers</a>
                    </li>
                </ul>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="../../constraints/">Constraints</a>
                    </li>
                </ul>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="../../visualization/">Visualization</a>
                    </li>
                </ul>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="../../scikit-learn-api/">Scikit-learn API</a>
                    </li>
                </ul>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="../../utils/">Utils</a>
                    </li>
                </ul>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="../../contributing/">Contributing</a>
                    </li>
                </ul>
                <p class="caption"><span class="caption-text">Examples</span></p>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="../addition_rnn/">Addition RNN</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../antirectifier/">Custom layer - antirectifier</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../babi_rnn/">Baby RNN</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../babi_memnn/">Baby MemNN</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../cifar10_cnn/">CIFAR-10 CNN</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../cifar10_resnet/">CIFAR-10 ResNet</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../conv_filter_visualization/">Convolution filter visualization</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../conv_lstm/">Convolutional LSTM</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../deep_dream/">Deep Dream</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../image_ocr/">Image OCR</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../imdb_bidirectional_lstm/">Bidirectional LSTM</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../imdb_cnn/">1D CNN for text classification</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../imdb_cnn_lstm/">Sentiment classification CNN-LSTM</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../imdb_fasttext/">Fasttext for text classification</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../imdb_lstm/">Sentiment classification LSTM</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../lstm_seq2seq/">Sequence to sequence - training</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../lstm_seq2seq_restore/">Sequence to sequence - prediction</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../lstm_stateful/">Stateful LSTM</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../lstm_text_generation/">LSTM for text generation</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="../mnist_acgan/">Auxiliary Classifier GAN</a>
                    </li>
                </ul>
      </div>
    </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">

      
      <nav class="wy-nav-top" role="navigation" aria-label="top navigation">
        <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
        <a href="../..">Keras Documentation</a>
      </nav>

      
      <div class="wy-nav-content">
        <div class="rst-content">
          <div role="navigation" aria-label="breadcrumbs navigation">
  <ul class="wy-breadcrumbs">
    <li><a href="../..">Docs</a> &raquo;</li>
    
      
    
    <li>Neural style transfer</li>
    <li class="wy-breadcrumbs-aside">
      
        <a href="https://github.com/keras-team/keras/tree/master/docs"
          class="icon icon-github"> Edit on GitHub</a>
      
    </li>
  </ul>
  
  <hr/>
</div>
          <div role="main">
            <div class="section">
              
                <p>Neural style transfer with Keras.</p>
<p>Run the script with:</p>
<pre><code>python neural_style_transfer.py path_to_your_base_image.jpg     path_to_your_reference.jpg prefix_for_results
</code></pre>

<p>e.g.:</p>
<pre><code>python neural_style_transfer.py img/tuebingen.jpg     img/starry_night.jpg results/my_result
</code></pre>

<p>Optional parameters:</p>
<pre><code>--iter, To specify the number of iterations     the style transfer takes place (Default is 10)
--content_weight, The weight given to the content loss (Default is 0.025)
--style_weight, The weight given to the style loss (Default is 1.0)
--tv_weight, The weight given to the total variation loss (Default is 1.0)
</code></pre>

<p>It is preferable to run this script on GPU, for speed.</p>
<p>Example result: https://twitter.com/fchollet/status/686631033085677568</p>
<h1 id="details">Details</h1>
<p>Style transfer consists in generating an image
with the same "content" as a base image, but with the
"style" of a different picture (typically artistic).</p>
<p>This is achieved through the optimization of a loss function
that has 3 components: "style loss", "content loss",
and "total variation loss":</p>
<ul>
<li>
<p>The total variation loss imposes local spatial continuity between
the pixels of the combination image, giving it visual coherence.</p>
</li>
<li>
<p>The style loss is where the deep learning keeps in --that one is defined
using a deep convolutional neural network. Precisely, it consists in a sum of
L2 distances between the Gram matrices of the representations of
the base image and the style reference image, extracted from
different layers of a convnet (trained on ImageNet). The general idea
is to capture color/texture information at different spatial
scales (fairly large scales --defined by the depth of the layer considered).</p>
</li>
<li>
<p>The content loss is a L2 distance between the features of the base
image (extracted from a deep layer) and the features of the combination image,
keeping the generated image close enough to the original one.</p>
</li>
</ul>
<h1 id="references">References</h1>
<pre><code>- [A Neural Algorithm of Artistic Style](http://arxiv.org/abs/1508.06576)
</code></pre>
<pre><code class="python">from __future__ import print_function
from keras.preprocessing.image import load_img, save_img, img_to_array
import numpy as np
from scipy.optimize import fmin_l_bfgs_b
import time
import argparse

from keras.applications import vgg19
from keras import backend as K

parser = argparse.ArgumentParser(description='Neural style transfer with Keras.')
parser.add_argument('base_image_path', metavar='base', type=str,
                    help='Path to the image to transform.')
parser.add_argument('style_reference_image_path', metavar='ref', type=str,
                    help='Path to the style reference image.')
parser.add_argument('result_prefix', metavar='res_prefix', type=str,
                    help='Prefix for the saved results.')
parser.add_argument('--iter', type=int, default=10, required=False,
                    help='Number of iterations to run.')
parser.add_argument('--content_weight', type=float, default=0.025, required=False,
                    help='Content weight.')
parser.add_argument('--style_weight', type=float, default=1.0, required=False,
                    help='Style weight.')
parser.add_argument('--tv_weight', type=float, default=1.0, required=False,
                    help='Total Variation weight.')

args = parser.parse_args()
base_image_path = args.base_image_path
style_reference_image_path = args.style_reference_image_path
result_prefix = args.result_prefix
iterations = args.iter

# these are the weights of the different loss components
total_variation_weight = args.tv_weight
style_weight = args.style_weight
content_weight = args.content_weight

# dimensions of the generated picture.
width, height = load_img(base_image_path).size
img_nrows = 400
img_ncols = int(width * img_nrows / height)

# util function to open, resize and format pictures into appropriate tensors


def preprocess_image(image_path):
    img = load_img(image_path, target_size=(img_nrows, img_ncols))
    img = img_to_array(img)
    img = np.expand_dims(img, axis=0)
    img = vgg19.preprocess_input(img)
    return img

# util function to convert a tensor into a valid image


def deprocess_image(x):
    if K.image_data_format() == 'channels_first':
        x = x.reshape((3, img_nrows, img_ncols))
        x = x.transpose((1, 2, 0))
    else:
        x = x.reshape((img_nrows, img_ncols, 3))
    # Remove zero-center by mean pixel
    x[:, :, 0] += 103.939
    x[:, :, 1] += 116.779
    x[:, :, 2] += 123.68
    # 'BGR'-&gt;'RGB'
    x = x[:, :, ::-1]
    x = np.clip(x, 0, 255).astype('uint8')
    return x

# get tensor representations of our images
base_image = K.variable(preprocess_image(base_image_path))
style_reference_image = K.variable(preprocess_image(style_reference_image_path))

# this will contain our generated image
if K.image_data_format() == 'channels_first':
    combination_image = K.placeholder((1, 3, img_nrows, img_ncols))
else:
    combination_image = K.placeholder((1, img_nrows, img_ncols, 3))

# combine the 3 images into a single Keras tensor
input_tensor = K.concatenate([base_image,
                              style_reference_image,
                              combination_image], axis=0)

# build the VGG19 network with our 3 images as input
# the model will be loaded with pre-trained ImageNet weights
model = vgg19.VGG19(input_tensor=input_tensor,
                    weights='imagenet', include_top=False)
print('Model loaded.')

# get the symbolic outputs of each &quot;key&quot; layer (we gave them unique names).
outputs_dict = dict([(layer.name, layer.output) for layer in model.layers])

# compute the neural style loss
# first we need to define 4 util functions

# the gram matrix of an image tensor (feature-wise outer product)


def gram_matrix(x):
    assert K.ndim(x) == 3
    if K.image_data_format() == 'channels_first':
        features = K.batch_flatten(x)
    else:
        features = K.batch_flatten(K.permute_dimensions(x, (2, 0, 1)))
    gram = K.dot(features, K.transpose(features))
    return gram

# the &quot;style loss&quot; is designed to maintain
# the style of the reference image in the generated image.
# It is based on the gram matrices (which capture style) of
# feature maps from the style reference image
# and from the generated image


def style_loss(style, combination):
    assert K.ndim(style) == 3
    assert K.ndim(combination) == 3
    S = gram_matrix(style)
    C = gram_matrix(combination)
    channels = 3
    size = img_nrows * img_ncols
    return K.sum(K.square(S - C)) / (4.0 * (channels ** 2) * (size ** 2))

# an auxiliary loss function
# designed to maintain the &quot;content&quot; of the
# base image in the generated image


def content_loss(base, combination):
    return K.sum(K.square(combination - base))

# the 3rd loss function, total variation loss,
# designed to keep the generated image locally coherent


def total_variation_loss(x):
    assert K.ndim(x) == 4
    if K.image_data_format() == 'channels_first':
        a = K.square(
            x[:, :, :img_nrows - 1, :img_ncols - 1] - x[:, :, 1:, :img_ncols - 1])
        b = K.square(
            x[:, :, :img_nrows - 1, :img_ncols - 1] - x[:, :, :img_nrows - 1, 1:])
    else:
        a = K.square(
            x[:, :img_nrows - 1, :img_ncols - 1, :] - x[:, 1:, :img_ncols - 1, :])
        b = K.square(
            x[:, :img_nrows - 1, :img_ncols - 1, :] - x[:, :img_nrows - 1, 1:, :])
    return K.sum(K.pow(a + b, 1.25))


# combine these loss functions into a single scalar
loss = K.variable(0.0)
layer_features = outputs_dict['block5_conv2']
base_image_features = layer_features[0, :, :, :]
combination_features = layer_features[2, :, :, :]
loss = loss + content_weight * content_loss(base_image_features,
                                            combination_features)

feature_layers = ['block1_conv1', 'block2_conv1',
                  'block3_conv1', 'block4_conv1',
                  'block5_conv1']
for layer_name in feature_layers:
    layer_features = outputs_dict[layer_name]
    style_reference_features = layer_features[1, :, :, :]
    combination_features = layer_features[2, :, :, :]
    sl = style_loss(style_reference_features, combination_features)
    loss = loss + (style_weight / len(feature_layers)) * sl
loss = loss + total_variation_weight * total_variation_loss(combination_image)

# get the gradients of the generated image wrt the loss
grads = K.gradients(loss, combination_image)

outputs = [loss]
if isinstance(grads, (list, tuple)):
    outputs += grads
else:
    outputs.append(grads)

f_outputs = K.function([combination_image], outputs)


def eval_loss_and_grads(x):
    if K.image_data_format() == 'channels_first':
        x = x.reshape((1, 3, img_nrows, img_ncols))
    else:
        x = x.reshape((1, img_nrows, img_ncols, 3))
    outs = f_outputs([x])
    loss_value = outs[0]
    if len(outs[1:]) == 1:
        grad_values = outs[1].flatten().astype('float64')
    else:
        grad_values = np.array(outs[1:]).flatten().astype('float64')
    return loss_value, grad_values

# this Evaluator class makes it possible
# to compute loss and gradients in one pass
# while retrieving them via two separate functions,
# &quot;loss&quot; and &quot;grads&quot;. This is done because scipy.optimize
# requires separate functions for loss and gradients,
# but computing them separately would be inefficient.


class Evaluator(object):

    def __init__(self):
        self.loss_value = None
        self.grads_values = None

    def loss(self, x):
        assert self.loss_value is None
        loss_value, grad_values = eval_loss_and_grads(x)
        self.loss_value = loss_value
        self.grad_values = grad_values
        return self.loss_value

    def grads(self, x):
        assert self.loss_value is not None
        grad_values = np.copy(self.grad_values)
        self.loss_value = None
        self.grad_values = None
        return grad_values


evaluator = Evaluator()

# run scipy-based optimization (L-BFGS) over the pixels of the generated image
# so as to minimize the neural style loss
x = preprocess_image(base_image_path)

for i in range(iterations):
    print('Start of iteration', i)
    start_time = time.time()
    x, min_val, info = fmin_l_bfgs_b(evaluator.loss, x.flatten(),
                                     fprime=evaluator.grads, maxfun=20)
    print('Current loss value:', min_val)
    # save current generated image
    img = deprocess_image(x.copy())
    fname = result_prefix + '_at_iteration_%d.png' % i
    save_img(fname, img)
    end_time = time.time()
    print('Image saved as', fname)
    print('Iteration %d completed in %ds' % (i, end_time - start_time))
</code></pre>
              
            </div>
          </div>
          <footer>
  

  <hr/>

  <div role="contentinfo">
    <!-- Copyright etc -->
    
  </div>

  Built with <a href="https://www.mkdocs.org/">MkDocs</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>.
</footer>
      
        </div>
      </div>

    </section>

  </div>

  <div class="rst-versions" role="note" aria-label="versions">
    <span class="rst-current-version" data-toggle="rst-current-version">
      
          <a href="http://github.com/keras-team/keras/" class="fa fa-github" style="float: left; color: #fcfcfc"> GitHub</a>
      
      
      
    </span>
</div>
    <script>var base_url = '../..';</script>
    <script src="../../js/theme.js" defer></script>
      <script src="../../search/main.js" defer></script>
    <script type="text/javascript" defer>
        window.onload = function () {
            SphinxRtdTheme.Navigation.enable(true);
        };
    </script>

</body>
</html>