Skip to content

Plot functions

VAE.utils.plot

Collection of plot functions.

VAE.utils.plot.decoder_plot

decoder_plot(decoder, z_values, z_mean=0, cond=None, target=None, order=None, index=0, channels=None, labels=None, highlight='lightgray', name='Decoder plot', batch_size=32, verbose=True, sharex=True, sharey=True)

Plot decoder output for sampled latent variable. One variable at a time.

Draw samples from latent space and plot decoder output. The function varies one latent variable at a time, while all others are set to z_mean.

Parameters:

  • decoder (Model) –

    Decoder model.

  • z_values (ndarray) –

    Values by which the latent variables will be varied.

  • z_mean (ndarray, default: 0 ) –

    Values of the unchanged latent variables. If Numpy array, z_mean must be broadcastable to an array of shape (len(z_values), set_size, latent_dim).

  • cond (ndarray, default: None ) –

    Optional input condition.

  • target (ndarray, default: None ) –

    Optional target data.

  • order (list[int], default: None ) –

    Plotting order of the latent dimensions.

  • index (int, default: 0 ) –

    Index of the decoder output that will be shown. Index refers to the second dimension of size set_size.

  • channels (list[int], default: None ) –

    Channels to be shown. Channels refer to the last dimension of the decoder output. If None, all channels will be shown.

  • labels (list[str], default: None ) –

    Labels of the channels.

  • name (str, default: 'Decoder plot' ) –

    Name of the figure.

  • verbose (bool, default: True ) –

    Verbosity level.

Returns: Tuple of figure and axes.

Source code in VAE/utils/plot.py
 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
def decoder_plot(decoder: Model,
                 z_values: np.ndarray,
                 z_mean: np.ndarray = 0,
                 cond: np.ndarray = None,
                 target: np.ndarray = None,
                 order: list[int] = None,
                 index: int = 0,
                 channels: list[int] = None,
                 labels: list[str] = None,
                 highlight: str = 'lightgray',
                 name: str = 'Decoder plot',
                 batch_size: int = 32,
                 verbose: bool = True,
                 sharex: bool = True,
                 sharey: bool = True):
    """Plot decoder output for sampled latent variable. One variable at a time.

    Draw samples from latent space and plot decoder output. The function varies one latent variable at a time, while all
    others are set to `z_mean`.

    Parameters:
        decoder:
            Decoder model.
        z_values:
            Values by which the latent variables will be varied.
        z_mean:
            Values of the unchanged latent variables. If Numpy array, `z_mean` must be broadcastable to an array of
            shape `(len(z_values), set_size, latent_dim)`.
        cond:
            Optional input condition.
        target:
            Optional target data.
        order:
            Plotting order of the latent dimensions.
        index:
            Index of the decoder output that will be shown. Index refers to the second dimension of size `set_size`.
        channels:
            Channels to be shown. Channels refer to the last dimension of the decoder output. If None, all channels
            will be shown.
        labels:
            Labels of the channels.
        name:
            Name of the figure.
        verbose:
            Verbosity level.

     Returns:
        Tuple of figure and axes.

    """
    _, set_size, latent_dim = decoder.inputs[0].get_shape().as_list()
    _, set_size, output_length, output_channels = decoder.outputs[0].get_shape().as_list()

    z_mean = np.broadcast_to(z_mean, (len(z_values), set_size, latent_dim))
    z_values = np.array(z_values)[:, None]
    idx_z0 = np.argmin(np.abs(z_values - z_mean[:, 0, :]), axis=0)

    if channels is None:
        channels = range(output_channels)

    if cond is not None:
        cond = np.broadcast_to(cond, (len(z_values), set_size, cond.shape[-1]))

    if order is None:
        order = np.arange(latent_dim)

    output_reverse = [layer.name for layer in decoder.layers if 'reverse' in layer.name]
    if output_reverse:
        x = range(-output_length, 0)
    else:
        x = range(output_length)

    linestyles = cycler(color=[plt.get_cmap('tab10')(n) for n in channels])

    fig, axs = _create_figure(fig=name, rows=len(z_values), columns=len(order), sharex=sharex, sharey=sharey)
    pbar = Progbar(len(order), unit_name='latent dimension', verbose=verbose, interval=1)
    for column, k in enumerate(order):
        z = z_mean.copy()
        z[..., k] = z_values

        # predict
        if cond is None:
            y = decoder.predict(z, batch_size=batch_size)
        else:
            y = decoder.predict([z, cond], batch_size=batch_size)

        y = y[:, index, ...][..., channels]

        axs[-1, column].set_title('$k={}$'.format(k))

        for row, yr in enumerate(y):
            ax = axs[row, column]
            ax.set_prop_cycle(linestyles)
            p = ax.plot(x, yr, zorder=1.1, linewidth=2)
            if target is not None:
                ax.plot(x, target, zorder=1, alpha=0.5)

            ax.grid(axis='both', linestyle=':')
            ax.axhline(0, color='k', linewidth=1.25, linestyle=':')
            if column == 0:
                ax.set_ylabel(z_values[row, 0])

            if row == idx_z0[k]:
                ax.set_facecolor(highlight)

            if (row == len(y) - 1) and (column == len(order) - 1):
                if labels is not None:
                    ax.legend(p, labels, loc='upper left', bbox_to_anchor=(1, 1.05))

        pbar.add(1)

    fig.text(0.01, 0.5, '$z_k$', va='center', rotation='vertical', fontsize='large')

    return fig, axs

VAE.utils.plot.decoder_plot2d

decoder_plot2d(decoder, latent_pair, z_values, z_mean=0, cond=None, target=None, index=0, channels=None, labels=None, highlight='lightgray', batch_size=32, name='Decoder plot 2D', verbose=True, sharex=True, sharey=True)

Plot decoder output for sampled latent variable. Two variables at a time.

Draw samples from latent space and plot decoder output. The function varies two latent variable at a time and sets all others to z0.

Note

For models in :mod:models_single.

Parameters:

  • decoder (Model) –

    Instance of the decoder model.

  • latent_pair (tuple[int, int]) –

    Latent dimensions that will be varied.

  • z_values (ndarray) –

    Values by which the latent variables will be varied.

  • z_mean (ndarray, default: 0 ) –

    Values of the unchanged latent variables. If Numpy array, z_mean must be broadcastable to an array of shape (len(z_values), set_size, latent_dim).

  • cond (ndarray, default: None ) –

    Optional input condition.

  • target

    Optional target data.

  • index (int, default: 0 ) –

    Index of the decoder output that will be shown. Index refers to the second dimension of size set_size.

  • channels (list[int], default: None ) –

    Channels to be shown. Channels refer to the last dimension of the decoder output. If None, all channels will be shown.

  • labels (list[str], default: None ) –

    Labels of the channels.

  • name (str, default: 'Decoder plot 2D' ) –

    Name of the figure.

Returns:

  • Tuple of figure and axes.

Source code in VAE/utils/plot.py
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
def decoder_plot2d(decoder: Model,
                   latent_pair: tuple[int, int],
                   z_values: np.ndarray,
                   z_mean: np.ndarray = 0,
                   cond: np.ndarray = None,
                   target=None,
                   index: int = 0,
                   channels: list[int] = None,
                   labels: list[str] = None,
                   highlight: str = 'lightgray',
                   batch_size: int = 32,
                   name: str = "Decoder plot 2D",
                   verbose: bool = True,
                   sharex: bool = True,
                   sharey: bool = True):
    """Plot decoder output for sampled latent variable. Two variables at a time.

    Draw samples from latent space and plot decoder output. The function varies two latent variable at a time and sets
    all others to ``z0``.

    Note:
        For models in :mod:`models_single`.

    Parameters:
        decoder:
            Instance of the decoder model.
        latent_pair:
            Latent dimensions that will be varied.
        z_values:
            Values by which the latent variables will be varied.
        z_mean:
            Values of the unchanged latent variables. If Numpy array, `z_mean` must be broadcastable to an array of
            shape `(len(z_values), set_size, latent_dim)`.
        cond:
            Optional input condition.
        target:
            Optional target data.
        index:
            Index of the decoder output that will be shown. Index refers to the second dimension of size `set_size`.
        channels:
            Channels to be shown. Channels refer to the last dimension of the decoder output. If None, all channels
            will be shown.
        labels:
            Labels of the channels.
        name:
            Name of the figure.

    Returns:
        Tuple of figure and axes.

    """
    _, set_size, latent_dim = decoder.inputs[0].get_shape().as_list()
    _, set_size, output_length, output_channels = decoder.outputs[0].get_shape().as_list()

    z_mean = np.broadcast_to(z_mean, (len(z_values), set_size, latent_dim))
    z_values = np.array(z_values)[:, None]
    k0, k1 = latent_pair
    idx_z0 = np.argmin(np.abs(z_values - z_mean[:, 0, :]), axis=0)

    if channels is None:
        channels = range(output_channels)

    if cond is not None:
        cond = np.broadcast_to(cond, (len(z_values), set_size, cond.shape[-1]))

    output_reverse = [layer.name for layer in decoder.layers if 'reverse' in layer.name]
    if output_reverse:
        x = range(-output_length, 0)
    else:
        x = range(output_length)

    linestyles = cycler(color=[plt.get_cmap('tab10')(n) for n in channels])

    fig, axs = _create_figure(fig=name, rows=len(z_values), columns=len(z_values), sharex=sharex, sharey=sharey)
    pbar = Progbar(len(z_values), unit_name='column', verbose=verbose, interval=1)
    for column in range(len(z_values)):
        # prepare latent samples
        z = z_mean.copy()
        z[..., k0] = z_values[column, ...]
        z[..., k1] = z_values

        # predict
        if cond is None:
            y = decoder.predict(z, batch_size=batch_size)
        else:
            y = decoder.predict([z, cond], batch_size=batch_size)

        y = y[:, index, ...][..., channels]

        axs[0, column].set_xlabel(z_values[column, 0])
        for row, yr in enumerate(y):
            ax = axs[row, column]
            ax.set_prop_cycle(linestyles)
            p = ax.plot(x, yr, zorder=1, linewidth=2)
            if target is not None:
                ax.plot(x, target, zorder=1, alpha=0.5)

            ax.grid(axis='both', linestyle=':')
            ax.axhline(0, color='k', linewidth=1.25, linestyle=':')
            if column == 0:
                ax.set_ylabel(z_values[row, 0])

            if (column == idx_z0[k0]) and (row == idx_z0[k1]):
                ax.set_facecolor(highlight)

            if (row == len(y) - 1) and (column == len(z_values) - 1):
                if labels is not None:
                    ax.legend(p, labels, loc='upper left', bbox_to_anchor=(1, 1.05))

        pbar.add(1)

    fig.text(0.01, 0.5, f'$z_{{{k1}}}$', va='center', rotation='vertical', fontsize='large')
    fig.text(0.5, 0.01, f'$z_{{{k0}}}$', ha='center', fontsize='large')

    return fig, axs

VAE.utils.plot.decoder_pcolormesh

decoder_pcolormesh(decoder, z_values, z0=0, cond=None, channel=0, order=None, vmin=None, vmax=None, cmap=None, highlight='#bbbbbb', name='Decoder plot', batch_size=32, verbose=True)

Plot decoder output for sampled latent variable. One variable at a time.

Draw samples from latent space and plot decoder output. The function varies one latent variable at a time, while all others are set to z0.

Parameters:

  • decoder (Model) –

    Instance of the decoder model.

  • z_values (ndarray) –

    Values by which the latent variables will be varied.

  • z0 (ndarray, default: 0 ) –

    Values of the unchanged latent variables. If Numpy array, z0 must be compatible with shape (len(z_values), latent_dim).

  • cond (ndarray, default: None ) –

    Optional input condition.

  • channel (int, default: 0 ) –

    Channel to be shown.

  • order (list[int], default: None ) –

    Plotting order of the latent dimensions.

  • name (str, default: 'Decoder plot' ) –

    Name of the figure.

  • verbose (bool, default: True ) –

    Verbosity mode.

Returns: Tuple of figure and axes.

Source code in VAE/utils/plot.py
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
def decoder_pcolormesh(decoder: Model,
                       z_values: np.ndarray,
                       z0: np.ndarray = 0,
                       cond: np.ndarray = None,
                       channel: int = 0,
                       order: list[int] = None,
                       vmin: float = None,
                       vmax: float = None,
                       cmap: str = None,
                       highlight: str = '#bbbbbb',
                       name: str = 'Decoder plot',
                       batch_size: int = 32,
                       verbose: bool = True):
    """Plot decoder output for sampled latent variable. One variable at a time.

    Draw samples from latent space and plot decoder output. The function varies one latent variable at a time, while all
    others are set to ``z0``.

    Parameters:
        decoder:
            Instance of the decoder model.
        z_values:
            Values by which the latent variables will be varied.
        z0:
            Values of the unchanged latent variables. If Numpy array, ``z0`` must be compatible
            with shape ``(len(z_values), latent_dim)``.
        cond:
            Optional input condition.
        channel:
            Channel to be shown.
        order:
            Plotting order of the latent dimensions.
        name:
            Name of the figure.
        verbose:
            Verbosity mode.

     Returns:
        Tuple of figure and axes.

    """
    z_values = np.array(z_values)
    latent_dim = decoder.inputs[0].get_shape().as_list()[1]
    z0 = np.broadcast_to(z0, (1, latent_dim))
    z0 = np.repeat(z0, len(z_values), axis=0)

    if cond is not None:
        cond = np.repeat(cond, len(z_values), axis=0)

    idx_z0 = np.argmin(np.abs(z_values[:, None] - z0), axis=0)

    if order is None:
        order = np.arange(latent_dim)

    fig, axs = _create_figure(fig=name, rows=len(z_values), columns=len(order), subplots_adjust=False)

    pbar = Progbar(len(order), unit_name='latent dimension', verbose=verbose, interval=1)

    for column, column_k in enumerate(order):
        # sample from latent space
        # vary single value and set others to z0
        z = z0.copy()
        z[:, column_k] = z_values

        # predict
        if cond is None:
            y = decoder.predict(z, batch_size=batch_size)
        else:
            y = decoder.predict([z, cond], batch_size=batch_size)

        axs[-1, column].set_title('$k={}$'.format(column_k))

        for row, yr in enumerate(y):
            ax = axs[row, column]
            ax.pcolormesh(yr[..., channel], vmin=vmin, vmax=vmax, cmap=cmap, zorder=1)

            if column == 0:
                ax.set_ylabel('$z_k={:.1f}$'.format(z_values[row]))

            if row == idx_z0[column_k]:
                ax.patch.set_edgecolor(highlight)
                ax.patch.set_linewidth(10)

        pbar.add(1)

    return fig, axs

VAE.utils.plot.decoder_response

decoder_response(decoder, inputs, z_pertub_p=None, z_pertub_n=None, order=None, index=0, channels=None, labels=None, batch_size=32, name='Decoder response', verbose=1, showmax=True, sharex=True, sharey=True)

Plot decoder response.

Decoder response with respect to changes in the latent variables. The response is the difference between the decoder output of the positive response from z_pertub_p and the negative response from z_pertub_n.

Parameters:

  • decoder (Model) –

    Model Instance of the decoder model.

  • inputs

    Inputs to the decoder.

  • z_pertub_p

    callable, optional Callable applied to the latent variables that will be used to calculate the positive response.

  • z_pertub_n

    callable, optional Callable applied to the latent variables that will be used to calculate the negative/neutral response.

  • order

    list of int Plotting order of the latent dimensions.

  • index

    int Index of the decoder output that will be shown. Index refers to the first dimension after the batch dimension.

  • channels

    list of ints Channels to be shown. Channels refer to the last dimension of the decoder output. If None, all channels will be shown.

  • labels

    list of str Labels of the channels.

  • name

    str Name of the figure.

Returns: tuple: fig: :class:matplotlib.figure.Figure The figure instance. axs: Array of :class:matplotlib.axes.Axes Array of axes objects.

Source code in VAE/utils/plot.py
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
def decoder_response(decoder: Model,
                     inputs,
                     z_pertub_p=None,
                     z_pertub_n=None,
                     order=None,
                     index=0,
                     channels=None,
                     labels=None,
                     batch_size=32,
                     name='Decoder response',
                     verbose=1,
                     showmax=True,
                     sharex=True,
                     sharey=True):
    """Plot decoder response.

    Decoder response with respect to changes in the latent variables. The response is the difference between the decoder
    output of the positive response from `z_pertub_p` and the negative response from `z_pertub_n`.

    Parameters:
        decoder: Model
            Instance of the decoder model.
        inputs:
            Inputs to the decoder.
        z_pertub_p : callable, optional
            Callable applied to the latent variables that will be used to calculate the positive response.
        z_pertub_n : callable, optional
            Callable applied to the latent variables that will be used to calculate the negative/neutral response.
        order: list of int
            Plotting order of the latent dimensions.
        index : int
            Index of the decoder output that will be shown. Index refers to the first dimension after the batch
            dimension.
        channels : list of ints
            Channels to be shown. Channels refer to the last dimension of the decoder output. If None, all channels
            will be shown.
        labels : list of str
            Labels of the channels.
        name: str
            Name of the figure.

     Returns:
        tuple:
            fig: :class:`matplotlib.figure.Figure`
                The figure instance.
            axs: Array of :class:`matplotlib.axes.Axes`
                Array of axes objects.

    """
    if isinstance(inputs, list):
        z_mean, condition = inputs
        condition = [condition]
    else:
        z_mean = inputs
        condition = []

    _, set_size, output_length, output_channels = decoder.outputs[0].get_shape().as_list()
    latent_dim = decoder.inputs[0].get_shape().as_list()[-1]
    if channels is None:
        channels = range(output_channels)

    if z_mean.ndim == 2:
        z_mean = z_mean[:, None, :]

    z_mean = np.broadcast_to(z_mean, (len(z_mean), set_size, latent_dim))

    if order is None:
        order = range(latent_dim)

    pbar = Progbar(len(order), unit_name='latent dimension', verbose=verbose, interval=1)
    fig, axs = _create_figure(fig=name,
                              rows=len(channels),
                              columns=len(order),
                              flip_rows=False,
                              sharex=sharex,
                              sharey=sharey)

    output_reverse = [layer.name for layer in decoder.layers if 'reverse' in layer.name]
    if output_reverse:
        x = range(-output_length, 0)
    else:
        x = range(output_length)

    for column, k in enumerate(order):
        zp = z_mean.copy()
        zn = z_mean.copy()

        if z_pertub_p is not None:
            zp[..., k] = z_pertub_p(zp[..., k])

        if z_pertub_n is not None:
            zn[..., k] = z_pertub_n(zp[..., k])

        # predict
        yp = decoder.predict([zp] + condition, batch_size=batch_size)
        yn = decoder.predict([zn] + condition, batch_size=batch_size)
        y_diff = yp - yn
        y_diff = y_diff[:, index, ...][..., channels]

        # average over batches
        y_diff_mean = np.mean(y_diff, axis=0)
        y_diff_prcs = np.percentile(y_diff, [5, 95], axis=0)

        axs[0, column].set_title(f'$z_{{{k}}}$')
        for row in range(len(channels)):
            ax = axs[row, column]
            ax.plot(x, y_diff_mean[:, row], color='tab:blue', zorder=1.2)
            ax.fill_between(x,
                            y_diff_prcs[0, :, row],
                            y_diff_prcs[1, :, row],
                            facecolor='lightsteelblue',
                            edgecolor='tab:blue',
                            linewidth=1,
                            zorder=1.1)

            ax.grid(axis='both', linestyle=':')
            ax.axhline(0, color='k', linewidth=1.25, linestyle=':')
            if column == 0:
                if labels is not None:
                    ax.set_ylabel(labels[row])
                else:
                    ax.set_ylabel(row)
            if showmax:
                peaks, _ = find_peaks(np.abs(y_diff_mean[:, row]))
                if len(peaks) > 0:
                    plt.text(0.05,
                             0.95,
                             f'\u0394={x[peaks[0]]}',
                             transform=ax.transAxes,
                             ha='left',
                             va='top',
                             bbox=dict(facecolor='white', alpha=0.5))

        pbar.add(1)

    for ax_row in axs:
        ylims = [np.max(np.abs(ax.get_ylim())) for ax in ax_row]
        if sharey:
            ax_row[0].set_ylim(-ylims[0], ylims[0])
        else:
            for ax, ylim in zip(ax_row, ylims):
                ax.set_ylim(-ylim, ylim)

    return fig, axs

VAE.utils.plot.decoder_composite

decoder_composite(decoder, inputs, order=None, index=0, channels=None, adjusted=False, labels=None, batch_size=32, name='Decoder composite', verbose=1, showmax=True, sharex=True, sharey=True)

Plot decoder composite.

The decoder composite is obtained by setting all but one latent dimension to zero.

Parameters:

  • decoder (Model) –

    Model Instance of the decoder model.

  • inputs

    Inputs to the decoder.

  • order

    list of int Plotting order of the latent dimensions.

  • index

    int Index of the decoder output that will be shown. Index refers to the first dimension after the batch dimension.

  • channels

    list of ints Channels to be shown. Channels refer to the last dimension of the decoder output. If None, all channels will be shown.

  • adjusted

    bool Whether the composite is adjusted by removing the average decoder output sampled from the prior.

  • labels

    list of str Labels of the channels.

  • name

    str Name of the figure.

Returns: tuple: fig: :class:matplotlib.figure.Figure The figure instance. axs: Array of :class:matplotlib.axes.Axes Array of axes objects.

Source code in VAE/utils/plot.py
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
def decoder_composite(decoder: Model,
                      inputs,
                      order=None,
                      index=0,
                      channels=None,
                      adjusted=False,
                      labels=None,
                      batch_size=32,
                      name='Decoder composite',
                      verbose=1,
                      showmax=True,
                      sharex=True,
                      sharey=True):
    """Plot decoder composite.

    The decoder composite is obtained by setting all but one latent dimension to zero.

    Parameters:
        decoder: Model
            Instance of the decoder model.
        inputs:
            Inputs to the decoder.
        order: list of int
            Plotting order of the latent dimensions.
        index : int
            Index of the decoder output that will be shown. Index refers to the first dimension after the batch
            dimension.
        channels : list of ints
            Channels to be shown. Channels refer to the last dimension of the decoder output. If None, all channels
            will be shown.
        adjusted: bool
            Whether the composite is adjusted by removing the average decoder output sampled from the prior.
        labels : list of str
            Labels of the channels.
        name: str
            Name of the figure.

     Returns:
        tuple:
            fig: :class:`matplotlib.figure.Figure`
                The figure instance.
            axs: Array of :class:`matplotlib.axes.Axes`
                Array of axes objects.

    """
    if isinstance(inputs, list):
        z_mean, condition = inputs
        condition = [condition]
    else:
        z_mean = inputs
        condition = []

    _, set_size, output_length, output_channels = decoder.outputs[0].get_shape().as_list()
    latent_dim = decoder.inputs[0].get_shape().as_list()[-1]
    if channels is None:
        channels = range(output_channels)

    if z_mean.ndim == 2:
        z_mean = z_mean[:, None, :]

    z_mean = np.broadcast_to(z_mean, (len(z_mean), set_size, latent_dim))

    if order is None:
        order = range(latent_dim)

    pbar = Progbar(len(order), unit_name='latent dimension', verbose=verbose, interval=1)
    fig, axs = _create_figure(fig=name,
                              rows=len(channels),
                              columns=len(order),
                              flip_rows=False,
                              sharex=sharex,
                              sharey=sharey)

    output_reverse = [layer.name for layer in decoder.layers if 'reverse' in layer.name]
    if output_reverse:
        x = range(-output_length, 0)
    else:
        x = range(output_length)

    for column, k in enumerate(order):
        zc = np.zeros_like(z_mean)
        zc[..., k] = z_mean[..., k]

        # predict
        yc = decoder.predict([zc] + condition, batch_size=batch_size)

        if adjusted:
            yc -= decoder.predict([zc * 0] + condition, batch_size=batch_size)

        yc = yc[:, index, ...][..., channels]

        # average over batches
        # positive
        idx = z_mean[:, 0, k] > 0
        yp_mean = np.mean(yc[idx, ...], axis=0)
        yp_prcs = np.percentile(yc[idx, ...], [5, 95], axis=0)
        # negative
        idx = z_mean[:, 0, k] < 0
        yn_mean = np.mean(yc[idx, ...], axis=0)
        yn_prcs = np.percentile(yc[idx, ...], [5, 95], axis=0)

        axs[0, column].set_title(f'$z_{{{k}}}$')
        for row in range(len(channels)):
            ax = axs[row, column]
            hp1, = ax.plot(x, yp_mean[:, row], color='tab:red', zorder=1.2)
            hp2 = ax.fill_between(x,
                                  yp_prcs[0, :, row],
                                  yp_prcs[1, :, row],
                                  alpha=0.5,
                                  facecolor='tab:red',
                                  edgecolor='tab:red',
                                  linewidth=1,
                                  zorder=1.1)

            hn1, = ax.plot(x, yn_mean[:, row], color='tab:blue', zorder=1.2)
            hn2 = ax.fill_between(x,
                                  yn_prcs[0, :, row],
                                  yn_prcs[1, :, row],
                                  alpha=0.5,
                                  facecolor='tab:blue',
                                  edgecolor='tab:blue',
                                  linewidth=1,
                                  zorder=1.1)

            ax.grid(axis='both', linestyle=':')
            ax.axhline(0, color='k', linewidth=1.25, linestyle=':')
            if column == 0:
                if labels is not None:
                    ax.set_ylabel(labels[row])
                else:
                    ax.set_ylabel(row)

            if ax == axs[0, -1]:
                ax.legend([(hp1, hp2), (hn1, hn2)], ['$z>0$', '$z<0$'], loc='upper left', bbox_to_anchor=(1, 1))

            if showmax:
                peaks, _ = find_peaks(np.abs(yp_mean[:, row]))
                if len(peaks) > 0:
                    plt.text(0.05,
                             0.95,
                             f'\u0394={x[peaks[0]]}',
                             transform=ax.transAxes,
                             ha='left',
                             va='top',
                             bbox=dict(facecolor='white', alpha=0.5))

        pbar.add(1)

    for ax_row in axs:
        ylims = [np.max(np.abs(ax.get_ylim())) for ax in ax_row]
        if sharey:
            ax_row[0].set_ylim(-ylims[0], ylims[0])
        else:
            for ax, ylim in zip(ax_row, ylims):
                ax.set_ylim(-ylim, ylim)

    return fig, axs

VAE.utils.plot.decoder_response_hist

decoder_response_hist(decoder, inputs, z_pertub_p=None, z_pertub_n=None, order=None, index=0, channels=None, bins=10, vmin=None, vmax=None, cmap=None, norm=None, batch_size=32, name='Temporal response', labels=None, verbose=1, sharex=True, sharey=True)

Plot decoder response histogram.

Decoder response with respect to changes in the latent variables.

Parameters:

  • decoder

    Model Instance of the decoder.

  • inputs

    Inputs to the decoder.

  • z_pertub_p

    callable, optional Callable applied to the latent variables that will be used to calculate the positive response.

  • z_pertub_n

    callable, optional Callable applied to the latent variables that will be used to calculate the negative/neutral response.

  • bins

    int or Sequence See :func:numpy.histogram.

  • order

    iterable Plotting order of the latent dimensions.

  • index

    int Index of the decoder output that will be shown. Index refers to the first dimension after the batch dimension.

  • channels

    list of ints Channels to be shown. Channels refer to the last dimension of the decoder output. If None, all channels will be shown.

  • labels

    list of str Labels of the channels.

  • name

    str Name of the figure.

Returns: tuple: fig: :class:matplotlib.figure.Figure The figure instance. axs: Array of :class:matplotlib.axes.Axes Array of axes objects.

Source code in VAE/utils/plot.py
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
def decoder_response_hist(decoder: Model,
                          inputs,
                          z_pertub_p=None,
                          z_pertub_n=None,
                          order=None,
                          index=0,
                          channels=None,
                          bins=10,
                          vmin=None,
                          vmax=None,
                          cmap=None,
                          norm=None,
                          batch_size=32,
                          name='Temporal response',
                          labels=None,
                          verbose=1,
                          sharex=True,
                          sharey=True):
    """Plot decoder response histogram.

    Decoder response with respect to changes in the latent variables.

    Parameters:
        decoder : Model
            Instance of the decoder.
        inputs :
            Inputs to the decoder.
        z_pertub_p : callable, optional
            Callable applied to the latent variables that will be used to calculate the positive response.
        z_pertub_n : callable, optional
            Callable applied to the latent variables that will be used to calculate the negative/neutral response.
        bins : int or Sequence
            See :func:`numpy.histogram`.
        order : iterable
            Plotting order of the latent dimensions.
        index : int
            Index of the decoder output that will be shown. Index refers to the first dimension after the batch
            dimension.
        channels : list of ints
            Channels to be shown. Channels refer to the last dimension of the decoder output. If None, all channels
            will be shown.
        labels : list of str
            Labels of the channels.
        name : str
            Name of the figure.

     Returns:
        tuple:
            fig: :class:`matplotlib.figure.Figure`
                The figure instance.
            axs: Array of :class:`matplotlib.axes.Axes`
                Array of axes objects.

    """
    def _hist(x, bins):
        pdf = []
        for x_row in x.T:
            new_pdf, bins = np.histogram(x_row, bins=bins, density=True)
            pdf.append(new_pdf)

        return np.stack(pdf, axis=1), bins

    if isinstance(inputs, list):
        z_mean, condition = inputs
        condition = [condition]
    else:
        z_mean = inputs
        condition = []

    _, set_size, output_length, output_channels = decoder.outputs[0].get_shape().as_list()
    latent_dim = decoder.inputs[0].get_shape().as_list()[-1]
    if channels is None:
        channels = range(output_channels)

    if z_mean.ndim == 2:
        z_mean = z_mean[:, None, :]

    z_mean = np.broadcast_to(z_mean, (len(z_mean), set_size, latent_dim))

    if order is None:
        order = np.arange(latent_dim)

    output_reverse = [layer.name for layer in decoder.layers if 'reverse' in layer.name]
    if output_reverse:
        x = range(-output_length, 0)
    else:
        x = range(output_length)

    pbar = Progbar(len(order), unit_name='latent dimension', verbose=verbose, interval=1)
    fig, axs = _create_figure(fig=name,
                              rows=len(channels),
                              columns=len(order),
                              flip_rows=False,
                              sharex=sharex,
                              sharey=sharey)

    for column, k in enumerate(order):
        zp = z_mean.copy()
        zn = z_mean.copy()

        if z_pertub_p is not None:
            zp[..., k] = z_pertub_p(zp[..., k])

        if z_pertub_n is not None:
            zn[..., k] = z_pertub_n(zp[..., k])

        # predict
        yp = decoder.predict([zp] + condition, batch_size=batch_size)
        yn = decoder.predict([zn] + condition, batch_size=batch_size)
        yp = yp[:, index, ...][..., channels]
        yn = yn[:, index, ...][..., channels]

        axs[0, column].set_title(f'$z_{{{k}}}$')
        bins = np.array(bins)
        for row in range(len(channels)):
            yp_pdf, bins = _hist(yp[:, :, row], bins=bins)
            yn_pdf, bins = _hist(yn[:, :, row], bins=bins)
            y_pdf = yp_pdf - yn_pdf

            ax = axs[row, column]
            ax.pcolormesh(x, bins, y_pdf, vmin=vmin, vmax=vmax, cmap=cmap, norm=norm, zorder=1.1)
            ax.grid(axis='x')
            if column == 0:
                if labels is not None:
                    ax.set_ylabel(labels[row])
                else:
                    ax.set_ylabel(channels[row])

        pbar.add(1)

    return fig, axs

VAE.utils.plot.encoder_boxplot

encoder_boxplot(encoder, inputs, plottype='kl', sort=True, batch_size=None, name='Encoder boxplot', verbose=1)

Boxplot of latent variables from encoder output.

If plottype equals to mean, the function creates a boxplot of the latent variable z_mean that correspond to inputs given to the encoder. If plottype equals to var, the function creates a boxplot of the latent variable z_log_var. If plottype equals to kl, the function creates a boxplot of the KL divergence.

Parameters:

  • encoder

    class:keras.Model Instance of the encoder model.

  • inputs

    Numpy array or generator Input to the encoder.

  • plottype

    str Type of boxplot. One of mean, var, kl.

  • sort

    bool Plot latent dimension in descending order of mean Kullback-Leibler divergence.

  • name

    String Name of the figure.

Returns: tuple: fig: :class:matplotlib.figure.Figure The figure instance. axs: :class:matplotlib.axes.Axes Axes object. idx: Sequence Order of sorted latent dimensions. kl_loss : 2D Numpy array Values of the KL divergence corresponding to the input.

Source code in VAE/utils/plot.py
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
def encoder_boxplot(encoder, inputs, plottype='kl', sort=True, batch_size=None, name="Encoder boxplot", verbose=1):
    """Boxplot of latent variables from encoder output.

    If `plottype` equals to `mean`, the function creates a boxplot of the latent variable `z_mean` that correspond
    to `inputs` given to the encoder. If `plottype` equals to `var`, the function creates a boxplot of the latent
    variable `z_log_var`. If `plottype` equals to `kl`, the function  creates a boxplot of the KL divergence.

    Parameters:
        encoder : class:`keras.Model`
            Instance of the encoder model.
        inputs : Numpy array or generator
            Input to the encoder.
        plottype : str
            Type of boxplot. One of `mean`, `var`, `kl`.
        sort : bool
            Plot latent dimension in descending order of mean Kullback-Leibler divergence.
        name: String
            Name of the figure.

     Returns:
        tuple:
            fig: :class:`matplotlib.figure.Figure`
                The figure instance.
            axs: :class:`matplotlib.axes.Axes`
                Axes object.
            idx: Sequence
                Order of sorted latent dimensions.
            kl_loss : 2D Numpy array
                Values of the KL divergence corresponding to the input.

    """
    # get latent samples
    z_mean, z_log_var, *_ = encoder.predict(inputs, verbose=verbose, batch_size=batch_size)

    # z has shape (samples, latent_dim)
    latent_dim = z_mean.shape[1]

    fig = plt.figure(name)
    fig.clf()
    ax = fig.add_subplot(1, 1, 1)

    kl_loss = 1 + z_log_var - np.square(z_mean) - np.exp(z_log_var)
    kl_loss *= -0.5
    kl_loss_mean = np.mean(kl_loss, axis=0)

    if sort:
        idx = np.argsort(kl_loss_mean)
        idx = idx[::-1]
    else:
        idx = np.arange(latent_dim)

    labels = ['{}'.format(i) for i in idx]

    if plottype.lower() == 'mean':
        variable = z_mean
        yscale = 'Linear'
        ylabel = 'Mean'
    elif plottype.lower() == 'var':
        variable = np.exp(z_log_var)
        yscale = 'log'
        ylabel = 'Variance'
    elif plottype.lower() == 'kl':
        variable = kl_loss
        yscale = 'linear'
        ylabel = 'KL divergence'
    else:
        assert False, "Unknown option in `plottype` argument."

    ax.boxplot(
        variable[:, idx],
        showfliers=False,
        labels=labels,
        patch_artist=True,
        showmeans=True,
        boxprops=dict(facecolor='lightsteelblue'),
        medianprops=dict(color='tab:blue'),
        meanprops=dict(markerfacecolor='tab:blue'),
        zorder=2,
    )

    ax.set_xlabel('k')
    ax.set_ylabel(ylabel)
    ax.set_yscale(yscale)
    ax.grid(axis='both', linestyle=':')

    return fig, ax, idx, kl_loss

VAE.utils.plot.encoder_hist

encoder_hist(encoder, inputs, latent_sampling=None, bins=30, order=None, show_null=True, batch_size=None, name='Encoder hist', verbose=1)

Histogram of latent variables from encoder output.

The function plots the histogram of the latent variable z_mean that correspond to inputs given to the encoder. If latent_sampling is specified, then the histogram of random samples z from latent_sampling is shown instead.

Together with the histogram, the prior distribution is shown as a bold line.

Parameters:

  • encoder

    class:keras.Model Instance of the encoder model.

  • inputs

    4D Numpy array Input to the encoder. The first dimension is the batch dimension.

  • latent_sampling

    class:keras.Model Instance of the latent sampling model. Defaults to None.

  • bins

    Integer or sequence Number or edges of bins.

  • order

    Sequence Plotting order of the latent dimensions.

  • show_null

    boolean Whether to show the null hypothesis of a normal distribution with mean 0 and standard deviation 1.

  • name

    String Name of the figure.

Returns: tuple: fig: :class:matplotlib.figure.Figure The figure instance. axs: Array of :class:matplotlib.axes.Axes Array of axes objects.

Source code in VAE/utils/plot.py
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
def encoder_hist(encoder,
                 inputs,
                 latent_sampling=None,
                 bins=30,
                 order=None,
                 show_null=True,
                 batch_size=None,
                 name="Encoder hist",
                 verbose=1):
    """Histogram of latent variables from encoder output.

    The function plots the histogram of the latent variable `z_mean` that correspond to `inputs` given to the encoder.
    If `latent_sampling` is specified, then the histogram of random samples `z` from `latent_sampling` is shown instead.

    Together with the histogram, the prior distribution is shown as a bold line.

    Parameters:
        encoder: class:`keras.Model`
            Instance of the encoder model.
        inputs: 4D Numpy array
            Input to the encoder. The first dimension is the batch dimension.
        latent_sampling : class:`keras.Model`
            Instance of the latent sampling model. Defaults to `None`.
        bins: Integer or sequence
            Number or edges of bins.
        order: Sequence
            Plotting order of the latent dimensions.
        show_null : boolean
            Whether to show the null hypothesis of a normal distribution with mean 0 and standard deviation 1.
        name: String
            Name of the figure.

     Returns:
        tuple:
            fig: :class:`matplotlib.figure.Figure`
                The figure instance.
            axs: Array of :class:`matplotlib.axes.Axes`
                Array of axes objects.

    """
    # get latent samples
    z_mean, z_log_var, *_ = encoder.predict(inputs, verbose=verbose, batch_size=batch_size)

    # draw random z
    if latent_sampling is not None:
        zs = latent_sampling.predict([z_mean, z_log_var], verbose=verbose, batch_size=batch_size)
        if zs.ndim == 3:
            zs = zs[:, 0, :]

    bins = np.array(bins)
    if bins.size == 1:
        bins = np.linspace(np.min(z_mean), np.max(z_mean), bins)

    norm_pdf = norm.pdf(bins, 0, 1)

    fig, axs = _create_figure(fig=name, rows=1, columns=len(order))

    for column, column_k in enumerate(order):
        ax = axs[0, column]
        if latent_sampling is None:
            ax.hist(z_mean[:, column_k],
                    bins=bins,
                    density=True,
                    color='red',
                    histtype='stepfilled',
                    edgecolor='k',
                    zorder=2.2)
        else:
            ax.hist(zs[:, column_k],
                    bins=bins,
                    density=True,
                    color='tab:cyan',
                    histtype='stepfilled',
                    edgecolor='k',
                    zorder=2.1)

        if show_null:
            ax.plot(bins, norm_pdf, color='k', zorder=2.3)

        ax.axvline(0, color='k', linewidth=1.25, linestyle=':', zorder=2.2)
        ax.set_xlabel('$z_{{{}}}$'.format(column_k))
        ax.xaxis.set_minor_locator(ticker.AutoMinorLocator())

    xl = np.max(np.abs(ax.get_xlim()))
    ax.set_xlim([-xl, xl])

    return fig, axs

VAE.utils.plot.encoder_hist2d

encoder_hist2d(encoder, inputs, latent_sampling=None, bins=30, order=None, batch_size=None, cmap=None, norm=None, name='Encoder hist2d', verbose=1)

Histogram of pairs of latent variables from encoder output.

The function creates pariwise histograms of the latent variable z_mean that correspond to inputs given to the encoder. If latent_sampling is specified, then pairwise histograms of random samples z from latent_sampling are shown instead.

Parameters:

  • encoder

    :class:keras.Model Instance of the encoder model.

  • inputs

    4D Numpy array Input to the encoder. The first dimension is the batch dimension.

  • latent_sampling

    class:keras.Model Instance of the latent sampling model. Defaults to None.

  • bins

    int or sequence Number or edges of bins.

  • order

    Sequence Plotting order of the latent dimensions.

  • name

    str Name of the figure.

Returns: tuple: fig: :class:matplotlib.figure.Figure The figure instance. axs: Array of :class:matplotlib.axes.Axes Array of axes objects.

Source code in VAE/utils/plot.py
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
def encoder_hist2d(encoder,
                   inputs,
                   latent_sampling=None,
                   bins=30,
                   order=None,
                   batch_size=None,
                   cmap=None,
                   norm=None,
                   name="Encoder hist2d",
                   verbose=1):
    """Histogram of pairs of latent variables from encoder output.

    The function creates pariwise histograms of the latent variable `z_mean` that correspond to ``inputs`` given to the
    encoder. If `latent_sampling` is specified, then pairwise histograms of random samples `z` from `latent_sampling`
    are shown instead.

    Parameters:
        encoder : :class:`keras.Model`
            Instance of the encoder model.
        inputs : 4D Numpy array
            Input to the encoder. The first dimension is the batch dimension.
        latent_sampling : class:`keras.Model`
            Instance of the latent sampling model. Defaults to `None`.
        bins : int or sequence
            Number or edges of bins.
        order : Sequence
            Plotting order of the latent dimensions.
        name : str
            Name of the figure.

     Returns:
        tuple:
            fig: :class:`matplotlib.figure.Figure`
                The figure instance.
            axs: Array of :class:`matplotlib.axes.Axes`
                Array of axes objects.

    """
    # get latent samples
    z_mean, z_log_var, *_ = encoder.predict(inputs, verbose=verbose, batch_size=batch_size)

    # draw random z
    if latent_sampling is not None:
        z = latent_sampling.predict([z_mean, z_log_var], verbose=verbose, batch_size=batch_size)
        if z.ndim == 3:
            z = z[:, 0, :]

    # z_mean has shape (samples, latent_dim)
    latent_dim = z_mean.shape[-1]

    if order is None:
        order = np.arange(latent_dim)

    limit = np.max(np.abs(z_mean[:, order]))
    bins = np.array(bins)
    if bins.size == 1:
        bins = np.linspace(-limit, limit, bins)

    fig, axs = _create_figure(fig=name, rows=len(order), columns=len(order), sharex=False, sharey=False)

    for row, row_k in enumerate(order):
        for column, column_k in enumerate(order):
            ax = axs[row, column]

            if row == column:
                if latent_sampling is None:
                    ax.hist(z_mean[:, column_k],
                            bins=bins,
                            density=True,
                            color='red',
                            histtype='stepfilled',
                            edgecolor='k')
                else:
                    ax.hist(z[:, column_k],
                            bins=bins,
                            density=True,
                            color='tab:cyan',
                            histtype='stepfilled',
                            edgecolor='k')

            else:
                if latent_sampling is None:
                    ax.hist2d(z_mean[:, column_k], z_mean[:, row_k], bins=bins, density=True, norm=norm, cmap=cmap)
                else:
                    ax.hist2d(z[:, column_k], z[:, row_k], bins=bins, density=True, norm=norm, cmap=cmap)

                ax.axhline(0, color='k', zorder=0)
                ax.axvline(0, color='k', zorder=0)
                ax.set_xlim([-limit, limit])
                ax.set_ylim([-limit, limit])

            if row == 0:
                ax.set_xlabel('$z_{{{}}}$'.format(column_k))

            if column == 0:
                ax.set_ylabel('$z_{{{}}}$'.format(row_k), rotation=0)

            if row == len(order):
                z_var = np.median(np.exp(z_log_var[:, column_k]))
                title = r'$\sigma_{{{}}}^2={:1.2f}$'.format(column_k, z_var)
                ax.set_title(title)

    return fig, axs

VAE.utils.plot.encoder_scatter

encoder_scatter(encoder, inputs, latent_sampling=None, bins=30, order=None, batch_size=None, name='Encoder scatter', verbose=1)

Scatter plot of latent variables from encoder output.

The function creates pairwise scatter plots of the latent variable z_mean that correspond to inputs given to the encoder. If latent_sampling is specified, then pairwise scatter plots of the random samples z from latent_sampling are likewwise shown.

Parameters:

  • encoder

    class:ks.Model Instance of the encoder model.

  • inputs

    4D Numpy array Input to the encoder. The first dimension is the batch dimension.

  • latent_sampling

    class:keras.Model Instance of the latent sampling model. Defaults to None. bins: Integer or sequence Number or edges of bins of histograms along main diagonal.

  • order

    Sequence Plotting order of the latent dimensions.

  • name

    String Name of the figure.

Returns: tuple: fig: :class:matplotlib.figure.Figure The figure instance. axs: Array of :class:matplotlib.axes.Axes Array of axes objects.

Source code in VAE/utils/plot.py
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
def encoder_scatter(encoder,
                    inputs,
                    latent_sampling=None,
                    bins=30,
                    order=None,
                    batch_size=None,
                    name='Encoder scatter',
                    verbose=1):
    """Scatter plot of latent variables from encoder output.

    The function creates pairwise scatter plots of the latent variable `z_mean` that correspond to ``inputs`` given to
    the encoder. If `latent_sampling` is specified, then pairwise scatter plots of the random samples `z` from
    `latent_sampling` are likewwise shown.

    Parameters:
        encoder : class:`ks.Model`
            Instance of the encoder model.
        inputs : 4D Numpy array
            Input to the encoder. The first dimension is the batch dimension.
        latent_sampling : class:`keras.Model`
            Instance of the latent sampling model. Defaults to `None`.
         bins: Integer or sequence
            Number or edges of bins of histograms along main diagonal.
        order: Sequence
            Plotting order of the latent dimensions.
        name: String
            Name of the figure.

     Returns:
        tuple:
            fig: :class:`matplotlib.figure.Figure`
                The figure instance.
            axs: Array of :class:`matplotlib.axes.Axes`
                Array of axes objects.

    """
    # get latent samples
    z_mean, z_log_var, *_ = encoder.predict(inputs, verbose=verbose, batch_size=batch_size)

    # draw random z
    if latent_sampling is not None:
        z = latent_sampling.predict([z_mean, z_log_var], verbose=verbose, batch_size=batch_size)
        if z.ndim == 3:
            z = z[:, 0, :]

    # z has shape (samples, latent_dim)
    latent_dim = z_mean.shape[1]

    limit = np.max(np.abs(z_mean))
    bins = np.array(bins)
    if bins.size == 1:
        bins = np.linspace(-limit, limit, bins)

    if order is None:
        order = np.arange(latent_dim)

    fig, axs = _create_figure(fig=name, rows=len(order), columns=len(order), sharex=False, sharey=False)

    for row, row_k in enumerate(order):
        for column, column_k in enumerate(order):
            ax = axs[row, column]

            if row == column:
                if latent_sampling is None:
                    ax.hist(z_mean[:, column_k],
                            bins=bins,
                            density=True,
                            color='tab:red',
                            histtype='stepfilled',
                            edgecolor='k')
                else:
                    ax.hist(z[:, column_k],
                            bins=bins,
                            density=True,
                            color='tab:cyan',
                            histtype='stepfilled',
                            edgecolor='k')

            else:
                if latent_sampling is not None:
                    ax.plot(z[:, column_k], z[:, row_k], '.', color='tab:cyan', markersize=3, zorder=1)

                ax.plot(z_mean[:, column_k], z_mean[:, row_k], '.', color='tab:red', markersize=3, zorder=1.2)
                ax.axhline(0, color='k', zorder=1.1)
                ax.set_ylim([-limit, limit])

            ax.set_xlim([-limit, limit])
            ax.axvline(0, color='k', zorder=0)

            if row == 0:
                ax.set_xlabel('$z_{{{}}}$'.format(column_k))

            if column == 0:
                ax.set_ylabel('$z_{{{}}}$'.format(row_k), rotation=0)

            if row == len(order):
                z_var = np.median(np.exp(z_log_var[:, column_k]))
                title = r'$\sigma_{{{}}}^2={:1.2f}$'.format(column_k, z_var)
                ax.set_title(title)

    return fig, axs

VAE.utils.plot.map_plot

map_plot(latitude, longitude, map_data, labels=None, ncols=1, vmin=None, vmax=None, projection=ccrs.PlateCarree(), coastlinespec_kw=None, colorbar_kw=None, gridlinespec_kw=None, gridspec_kw=None, landspec_kw=None, figwidth=None, **kwargs)

Plot a sequence of maps.

The function creates a map for each entry in map_data.

Parameters:

  • latitude

    Numpy array Latitude coordinate corresponding to the leading dimension of the maps.

  • longitude

    Numpy array Longitude coordinate corresponding to the second dimension of the maps.

  • map_data

    dict or sequence of ndarray Dictionary or sequence of 2D map data. Can also be a 3D array.

  • labels

    List of str List of labels for the sequence of the map data. Length must match the length of map_data.

  • ncols

    int Number of columns in which the subplots will be arranged.

  • **kwargs

    Additional keyword arguments passed to the plotting function.

Returns:

  • tuple

    fig : Figure object. axs : Array of axes objects. cb : Colorbar object.

Source code in VAE/utils/plot.py
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
def map_plot(latitude,
             longitude,
             map_data,
             labels=None,
             ncols=1,
             vmin=None,
             vmax=None,
             projection=ccrs.PlateCarree(),
             coastlinespec_kw=None,
             colorbar_kw=None,
             gridlinespec_kw=None,
             gridspec_kw=None,
             landspec_kw=None,
             figwidth=None,
             **kwargs):
    """Plot a sequence of maps.

    The function creates a map for each entry in `map_data`.

    Parameters:
        latitude : Numpy array
            Latitude coordinate corresponding to the leading dimension of the maps.
        longitude : Numpy array
            Longitude coordinate corresponding to the second dimension of the maps.
        map_data : dict or sequence of ndarray
            Dictionary or sequence of 2D map data. Can also be a 3D array.
        labels : List of str
            List of labels for the sequence of the map data. Length must match the length of map_data.
        ncols : int
            Number of columns in which the subplots will be arranged.

        **kwargs :
            Additional keyword arguments passed to the plotting function.

    Returns:
        tuple:
            fig : Figure object.
            axs : Array of axes objects.
            cb :  Colorbar object.

    """
    map_data, labels = _map_to_dict(map_data, labels)
    nrows = -(-len(map_data) // ncols)  # ceil

    coastlinespec_kw = coastlinespec_kw or {'color': 'k', 'alpha': 1, 'linewidth': 1}
    colorbar_kw = colorbar_kw or {'shrink': 0.7 / nrows, 'pad': 0.01, 'aspect': 40 / nrows, 'extend': 'both'}
    gridspec_kw = gridspec_kw or {'wspace': 0.05, 'hspace': 0.25}
    gridlinespec_kw = gridlinespec_kw or {'draw_labels': True, 'linestyle': ':'}

    subplot_kw = dict(projection=projection)
    fig, axs = plt.subplots(nrows, ncols, subplot_kw=subplot_kw, gridspec_kw=gridspec_kw, squeeze=False)

    if (vmin is None) and ('norm' not in kwargs):
        vmin = np.nanmin([np.nanmin(value) for value in map_data.values()])

    if (vmax is None) and ('norm' not in kwargs):
        vmax = np.nanmax([np.nanmax(value) for value in map_data.values()])

    for ax, label, value in zip(axs.flat, labels, map_data.values()):
        value_cyclic, longitude_cyclic = add_cyclic_point(value, coord=longitude)
        im = ax.pcolormesh(longitude_cyclic,
                           latitude,
                           value_cyclic,
                           vmin=vmin,
                           vmax=vmax,
                           shading='nearest',
                           transform=ccrs.PlateCarree(),
                           **kwargs)
        gl = ax.gridlines(**gridlinespec_kw)
        gl.top_labels = False
        gl.right_labels = False
        if ax not in axs[:, 0]:
            gl.left_labels = False

        if ax not in axs[-1, :]:
            gl.bottom_labels = False

        ax.coastlines(**coastlinespec_kw)
        if landspec_kw is not None:
            ax.add_feature(cfeature.LAND, **landspec_kw)
        ax.set_title(label)

    if figwidth:
        _set_figure_size(fig, axs, figwidth)

    for ax in axs.flat[len(map_data):]:
        fig.delaxes(ax)

    if len(map_data) == axs.size:
        cb = fig.colorbar(im, ax=axs, **colorbar_kw)
    else:
        pad = colorbar_kw.get('pad', 0.05)
        if colorbar_kw.get('orientation', 'vertical').lower() == 'vertical':
            cb = fig.colorbar(im, ax=axs[-1, :], **{**colorbar_kw, 'pad': pad - 1 / ncols})
        else:
            cb = fig.colorbar(im, ax=axs[:, -1], **{**colorbar_kw, 'pad': pad - 1 / nrows})

    return fig, axs, cb

VAE.utils.plot.map_zonal

map_zonal(datetime, latitude, longitude, map_data, lon_lim=(-180, 180), labels=None, cmap='seismic', norm=None, vmin=None, vmax=None, figsize=None)

Plot a sequencde of zonal averages.

The function plots the zonal average for each entry in map_data.

Parameters:

  • datetime

    datetime Datetime corresponding to the leading dimension in the entries of map_data.

  • latitude

    Numpy array Latitude coordinate corresponding to the second dimension in the entries of map_data.

  • longitude

    Numpy array Longitude coordinate corresponding to the third dimension in the entries of map_data.

  • map_data

    dict or sequence of ndarray Dictionary or sequence of 2D map data. Can also be a 3D array.

  • lon_lim

    tuple of two float Longitude limits in which the zonal average is obtained.

  • labels

    List of str List of labels . Must match the length of map_data.

Returns:

  • tuple

    fig: :class:matplotlib.figure.Figure The figure instance. axs: Array of :class:matplotlib.axes.Axes Array of axes objects.

Source code in VAE/utils/plot.py
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
def map_zonal(datetime,
              latitude,
              longitude,
              map_data,
              lon_lim=(-180, 180),
              labels=None,
              cmap='seismic',
              norm=None,
              vmin=None,
              vmax=None,
              figsize=None):
    """Plot a sequencde of zonal averages.

    The function plots the zonal average for each entry in `map_data`.

    Parameters:
        datetime: datetime
            Datetime corresponding to the leading dimension in the entries of `map_data`.
        latitude : Numpy array
            Latitude coordinate corresponding to the second dimension in the entries of `map_data`.
        longitude : Numpy array
            Longitude coordinate corresponding to the third dimension in the entries of `map_data`.
        map_data : dict or sequence of ndarray
            Dictionary or sequence of 2D map data. Can also be a 3D array.
        lon_lim : tuple of two float
            Longitude limits in which the zonal average is obtained.
        labels : List of str
            List of labels . Must match the length of map_data.

    Returns:
        tuple:
            fig: :class:`matplotlib.figure.Figure`
                The figure instance.
            axs: Array of :class:`matplotlib.axes.Axes`
                Array of axes objects.

    """
    map_data, labels = _map_to_dict(map_data, labels)

    minimum, maximum = lon_lim
    minimum = np.deg2rad(minimum) % (2 * np.pi)
    maximum = np.deg2rad(maximum) % (2 * np.pi)
    lon = np.deg2rad(longitude) % (2 * np.pi)

    if minimum < maximum:
        lon_idx = np.flatnonzero(np.logical_and(minimum <= lon, lon <= maximum))
    elif minimum >= maximum:
        lon_idx = np.flatnonzero(np.logical_or(minimum <= lon, lon <= maximum))

    nrows = len(map_data)
    fig, axs = plt.subplots(nrows, 1, squeeze=True, sharex=True, sharey=True, figsize=figsize)
    lon_fmt = cticker.LongitudeFormatter()

    for ax, label, value in zip(axs.flat, labels, map_data.values()):
        zonal_mean = np.nansum(value[:, :, lon_idx], axis=-1) / len(lon_idx)
        if vmax is None and vmin is None:
            vmax = np.nanpercentile(np.abs(zonal_mean), 99)
            vmin = -vmax

        any_isfinite = np.any(np.isfinite(value), axis=(1, 2))
        any_isfinite = np.flatnonzero(any_isfinite)
        sl = slice(any_isfinite[0], any_isfinite[-1])

        im = ax.pcolormesh(datetime[sl],
                           latitude,
                           zonal_mean[sl, :].T,
                           shading='nearest',
                           cmap=cmap,
                           norm=norm,
                           vmin=vmin,
                           vmax=vmax)

        ax.set_title('{} ({}\u2013{})'.format(label, *[lon_fmt._format_value(lon, None) for lon in lon_lim]))
        ax.grid(which='major', axis='both')
        ax.grid(which='minor', axis='x', linestyle=':')
        fig.colorbar(im, ax=ax, pad=0.01, fraction=0.05, shrink=0.9 / min(nrows, 3))

    ax.xaxis.set_major_locator(dates.YearLocator(5))
    ax.xaxis.set_minor_locator(dates.YearLocator(1))
    ax.xaxis.set_major_formatter(dates.DateFormatter('%Y'))
    ax.yaxis.set_major_locator(cticker.LatitudeLocator())
    ax.yaxis.set_major_formatter(cticker.LatitudeFormatter())

    return fig, axs

VAE.utils.plot.map_meridional

map_meridional(datetime, latitude, longitude, map_data, lat_lim=(-90, 90), labels=None, cmap='seismic', norm=None, vmin=None, vmax=None, figsize=None)

Plot a sequence of meridional averages.

The function plots the meridional average for each entry in map_data.

Parameters:

  • datetime

    datetime Datetime corresponding to the leading dimension in the entries of map_data.

  • latitude

    Numpy array Latitude coordinate corresponding to the second dimension in the entries of map_data.

  • longitude

    Numpy array Longitude coordinate corresponding to the third dimension in the entries of map_data.

  • map_data

    dict or sequence of ndarray Dictionary or sequence of 2D map data. Can also be a 3D array.

  • lat_lim

    tuple of two float Latitude limits in which the meridional average is obtained.

  • labels

    List of str List of labels . Must match the length of map_data.

Returns:

  • tuple

    fig: :class:matplotlib.figure.Figure The figure instance. axs: Array of :class:matplotlib.axes.Axes Array of axes objects.

Source code in VAE/utils/plot.py
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
def map_meridional(datetime,
                   latitude,
                   longitude,
                   map_data,
                   lat_lim=(-90, 90),
                   labels=None,
                   cmap='seismic',
                   norm=None,
                   vmin=None,
                   vmax=None,
                   figsize=None):
    """Plot a sequence of meridional averages.

    The function plots the meridional average for each entry in `map_data`.

    Parameters:
        datetime: datetime
            Datetime corresponding to the leading dimension in the entries of `map_data`.
        latitude : Numpy array
            Latitude coordinate corresponding to the second dimension in the entries of `map_data`.
        longitude : Numpy array
            Longitude coordinate corresponding to the third dimension in the entries of `map_data`.
        map_data : dict or sequence of ndarray
            Dictionary or sequence of 2D map data. Can also be a 3D array.
        lat_lim : tuple of two float
            Latitude limits in which the meridional average is obtained.
        labels : List of str
            List of labels . Must match the length of map_data.

    Returns:
        tuple:
            fig: :class:`matplotlib.figure.Figure`
                The figure instance.
            axs: Array of :class:`matplotlib.axes.Axes`
                Array of axes objects.

    """
    map_data, labels = _map_to_dict(map_data, labels)

    minimum, maximum = lat_lim
    lat_idx = np.flatnonzero(np.logical_and(minimum <= latitude, latitude <= maximum))

    longitude_wrap = longitude.copy()
    longitude_wrap[longitude_wrap > 180] -= 360
    lon_idx = np.argsort(longitude_wrap)

    nrows = len(map_data)
    fig, axs = plt.subplots(nrows, 1, squeeze=True, sharex=True, sharey=True, figsize=figsize)
    lat_fmt = cticker.LatitudeFormatter()

    for ax, label, value in zip(axs.flat, labels, map_data.values()):
        meridional_mean = np.nansum(value[:, lat_idx, :], axis=1) / len(lat_idx)
        if vmax is None and vmin is None:
            vmax = np.nanpercentile(np.abs(meridional_mean), 99)
            vmin = -vmax

        any_isfinite = np.any(np.isfinite(value), axis=(1, 2))
        any_isfinite = np.flatnonzero(any_isfinite)
        sl = slice(any_isfinite[0], any_isfinite[-1])

        im = ax.pcolormesh(datetime[sl],
                           longitude_wrap[lon_idx],
                           meridional_mean[sl, lon_idx].T,
                           shading='nearest',
                           cmap=cmap,
                           norm=norm,
                           vmin=vmin,
                           vmax=vmax)

        ax.set_title('{} ({}\u2013{})'.format(label, *[lat_fmt._format_value(lat, None) for lat in lat_lim]))
        ax.grid(which='major', axis='both')
        ax.grid(which='minor', axis='x', linestyle=':')
        fig.colorbar(im, ax=ax, pad=0.01, fraction=0.05, shrink=0.9 / min(nrows, 3))

    ax.xaxis.set_major_locator(dates.YearLocator(5))
    ax.xaxis.set_minor_locator(dates.YearLocator(1))
    ax.xaxis.set_major_formatter(dates.DateFormatter('%Y'))
    ax.yaxis.set_major_locator(cticker.LongitudeLocator())
    ax.yaxis.set_major_formatter(cticker.LongitudeFormatter())

    return fig, axs