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 (536 lines) | stat: -rw-r--r-- 22,679 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
<!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/variational_autoencoder_deconv/">
  <link rel="shortcut icon" href="../../img/favicon.ico">
  <title>Variational autoencoder deconv - 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 = "Variational autoencoder deconv";
    var mkdocs_page_input_path = "examples/variational_autoencoder_deconv.md";
    var mkdocs_page_url = "/examples/variational_autoencoder_deconv/";
  </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>Variational autoencoder deconv</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>Example of VAE on MNIST dataset using CNN</p>
<p>The VAE has a modular design. The encoder, decoder and VAE
are 3 models that share weights. After training the VAE model,
the encoder can be used to  generate latent vectors.
The decoder can be used to generate MNIST digits by sampling the
latent vector from a Gaussian distribution with mean=0 and std=1.</p>
<h1 id="reference">Reference</h1>
<p>[1] Kingma, Diederik P., and Max Welling.
"Auto-encoding variational bayes."
https://arxiv.org/abs/1312.6114</p>
<pre><code class="python">from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from keras.layers import Dense, Input
from keras.layers import Conv2D, Flatten, Lambda
from keras.layers import Reshape, Conv2DTranspose
from keras.models import Model
from keras.datasets import mnist
from keras.losses import mse, binary_crossentropy
from keras.utils import plot_model
from keras import backend as K

import numpy as np
import matplotlib.pyplot as plt
import argparse
import os


# reparameterization trick
# instead of sampling from Q(z|X), sample eps = N(0,I)
# then z = z_mean + sqrt(var)*eps
def sampling(args):
    &quot;&quot;&quot;Reparameterization trick by sampling fr an isotropic unit Gaussian.

    # Arguments
        args (tensor): mean and log of variance of Q(z|X)

    # Returns
        z (tensor): sampled latent vector
    &quot;&quot;&quot;

    z_mean, z_log_var = args
    batch = K.shape(z_mean)[0]
    dim = K.int_shape(z_mean)[1]
    # by default, random_normal has mean=0 and std=1.0
    epsilon = K.random_normal(shape=(batch, dim))
    return z_mean + K.exp(0.5 * z_log_var) * epsilon


def plot_results(models,
                 data,
                 batch_size=128,
                 model_name=&quot;vae_mnist&quot;):
    &quot;&quot;&quot;Plots labels and MNIST digits as function of 2-dim latent vector

    # Arguments
        models (tuple): encoder and decoder models
        data (tuple): test data and label
        batch_size (int): prediction batch size
        model_name (string): which model is using this function
    &quot;&quot;&quot;

    encoder, decoder = models
    x_test, y_test = data
    os.makedirs(model_name, exist_ok=True)

    filename = os.path.join(model_name, &quot;vae_mean.png&quot;)
    # display a 2D plot of the digit classes in the latent space
    z_mean, _, _ = encoder.predict(x_test,
                                   batch_size=batch_size)
    plt.figure(figsize=(12, 10))
    plt.scatter(z_mean[:, 0], z_mean[:, 1], c=y_test)
    plt.colorbar()
    plt.xlabel(&quot;z[0]&quot;)
    plt.ylabel(&quot;z[1]&quot;)
    plt.savefig(filename)
    plt.show()

    filename = os.path.join(model_name, &quot;digits_over_latent.png&quot;)
    # display a 30x30 2D manifold of digits
    n = 30
    digit_size = 28
    figure = np.zeros((digit_size * n, digit_size * n))
    # linearly spaced coordinates corresponding to the 2D plot
    # of digit classes in the latent space
    grid_x = np.linspace(-4, 4, n)
    grid_y = np.linspace(-4, 4, n)[::-1]

    for i, yi in enumerate(grid_y):
        for j, xi in enumerate(grid_x):
            z_sample = np.array([[xi, yi]])
            x_decoded = decoder.predict(z_sample)
            digit = x_decoded[0].reshape(digit_size, digit_size)
            figure[i * digit_size: (i + 1) * digit_size,
                   j * digit_size: (j + 1) * digit_size] = digit

    plt.figure(figsize=(10, 10))
    start_range = digit_size // 2
    end_range = n * digit_size + start_range + 1
    pixel_range = np.arange(start_range, end_range, digit_size)
    sample_range_x = np.round(grid_x, 1)
    sample_range_y = np.round(grid_y, 1)
    plt.xticks(pixel_range, sample_range_x)
    plt.yticks(pixel_range, sample_range_y)
    plt.xlabel(&quot;z[0]&quot;)
    plt.ylabel(&quot;z[1]&quot;)
    plt.imshow(figure, cmap='Greys_r')
    plt.savefig(filename)
    plt.show()


# MNIST dataset
(x_train, y_train), (x_test, y_test) = mnist.load_data()

image_size = x_train.shape[1]
x_train = np.reshape(x_train, [-1, image_size, image_size, 1])
x_test = np.reshape(x_test, [-1, image_size, image_size, 1])
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255

# network parameters
input_shape = (image_size, image_size, 1)
batch_size = 128
kernel_size = 3
filters = 16
latent_dim = 2
epochs = 30

# VAE model = encoder + decoder
# build encoder model
inputs = Input(shape=input_shape, name='encoder_input')
x = inputs
for i in range(2):
    filters *= 2
    x = Conv2D(filters=filters,
               kernel_size=kernel_size,
               activation='relu',
               strides=2,
               padding='same')(x)

# shape info needed to build decoder model
shape = K.int_shape(x)

# generate latent vector Q(z|X)
x = Flatten()(x)
x = Dense(16, activation='relu')(x)
z_mean = Dense(latent_dim, name='z_mean')(x)
z_log_var = Dense(latent_dim, name='z_log_var')(x)

# use reparameterization trick to push the sampling out as input
# note that &quot;output_shape&quot; isn't necessary with the TensorFlow backend
z = Lambda(sampling, output_shape=(latent_dim,), name='z')([z_mean, z_log_var])

# instantiate encoder model
encoder = Model(inputs, [z_mean, z_log_var, z], name='encoder')
encoder.summary()
plot_model(encoder, to_file='vae_cnn_encoder.png', show_shapes=True)

# build decoder model
latent_inputs = Input(shape=(latent_dim,), name='z_sampling')
x = Dense(shape[1] * shape[2] * shape[3], activation='relu')(latent_inputs)
x = Reshape((shape[1], shape[2], shape[3]))(x)

for i in range(2):
    x = Conv2DTranspose(filters=filters,
                        kernel_size=kernel_size,
                        activation='relu',
                        strides=2,
                        padding='same')(x)
    filters //= 2

outputs = Conv2DTranspose(filters=1,
                          kernel_size=kernel_size,
                          activation='sigmoid',
                          padding='same',
                          name='decoder_output')(x)

# instantiate decoder model
decoder = Model(latent_inputs, outputs, name='decoder')
decoder.summary()
plot_model(decoder, to_file='vae_cnn_decoder.png', show_shapes=True)

# instantiate VAE model
outputs = decoder(encoder(inputs)[2])
vae = Model(inputs, outputs, name='vae')

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    help_ = &quot;Load h5 model trained weights&quot;
    parser.add_argument(&quot;-w&quot;, &quot;--weights&quot;, help=help_)
    help_ = &quot;Use mse loss instead of binary cross entropy (default)&quot;
    parser.add_argument(&quot;-m&quot;, &quot;--mse&quot;, help=help_, action='store_true')
    args = parser.parse_args()
    models = (encoder, decoder)
    data = (x_test, y_test)

    # VAE loss = mse_loss or xent_loss + kl_loss
    if args.mse:
        reconstruction_loss = mse(K.flatten(inputs), K.flatten(outputs))
    else:
        reconstruction_loss = binary_crossentropy(K.flatten(inputs),
                                                  K.flatten(outputs))

    reconstruction_loss *= image_size * image_size
    kl_loss = 1 + z_log_var - K.square(z_mean) - K.exp(z_log_var)
    kl_loss = K.sum(kl_loss, axis=-1)
    kl_loss *= -0.5
    vae_loss = K.mean(reconstruction_loss + kl_loss)
    vae.add_loss(vae_loss)
    vae.compile(optimizer='rmsprop')
    vae.summary()
    plot_model(vae, to_file='vae_cnn.png', show_shapes=True)

    if args.weights:
        vae.load_weights(args.weights)
    else:
        # train the autoencoder
        vae.fit(x_train,
                epochs=epochs,
                batch_size=batch_size,
                validation_data=(x_test, None))
        vae.save_weights('vae_cnn_mnist.h5')

    plot_results(models, data, batch_size=batch_size, model_name=&quot;vae_cnn&quot;)
</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>