Exemplo n.º 1
0
def plot_pearson_coefficients(spikerates_batch,
                              activations_batch,
                              config,
                              path=None):
    """
    Plot the Pearson correlation coefficients for each layer, averaged over one
    mini batch.

    Parameters
    ----------

    spikerates_batch: list[tuple[np.array, str]]
        Each entry in ``spikerates_batch`` contains a tuple
        ``(spikerates, label)`` for each layer of the network (for the first
        batch only, and excluding ``Flatten`` layers).

        ``spikerates`` contains the average firing rates of all neurons in a
        layer. It has the same shape as the original layer, e.g.
        (batch_size, n_features, n_rows, n_cols) for a convolution layer.

        ``label`` is a string specifying both the layer type and the index,
        e.g. ``'03Dense'``.

    activations_batch: list[tuple[np.array, str]]
        Contains the activations of a net. Same structure as
        ``spikerates_batch``.

    config: configparser.ConfigParser
        Settings.

    path: Optional[str]
        Where to save the output.
    """

    from snntoolbox.utils.utils import extract_label

    max_rate = 1. / config.getfloat('simulation', 'dt')
    co = get_pearson_coefficients(spikerates_batch, activations_batch,
                                  max_rate)

    # Average over batch
    corr = np.mean(co, axis=1)
    std = np.std(co, axis=1)

    labels = [sp[1] for sp in spikerates_batch]
    if config.getboolean('output', 'use_simple_labels'):
        labels = [extract_label(label)[1] for label in labels]

    plt.figure()
    plt.bar([i + 0.1 for i in range(len(corr))],
            corr,
            width=0.8,
            yerr=std,
            color=(0.8, 0.8, 0.8))
    plt.ylim([0, 1])
    plt.xlim([0, len(corr)])
    plt.xticks([i + 0.5 for i in range(len(labels))], labels, rotation=90)
    plt.tick_params(bottom=False)
    plt.title('Correlation between ANN activations \n and SNN spikerates,\n ' +
              'averaged over {} samples'.format(len(spikerates_batch[0][0])))
    plt.ylabel('Pearson Correlation Coefficient')
    if path is not None:
        filename = 'Pearson'
        plt.savefig(os.path.join(path, filename), bbox_inches='tight')
    else:
        plt.show()
    plt.close()
Exemplo n.º 2
0
def plot_layer_summaries(plot_vars, config, path=None, data_format=None):
    """Display or save a number of plots for a specific layer.

    Parameters
    ----------

    plot_vars: dict

        Example items:

        - spikerates: list[tuple[np.array, str]]
            Each entry in ``spikerates`` contains a tuple ``(rates, label)``
            for each layer of the network (for the first batch only, and
            excluding ``Flatten`` layers).

            ``rates`` contains the average firing rates of all neurons in a
            layer. It has the same shape as the original layer, e.g.
            (n_features, n_rows, n_cols) for a convolution layer.

            ``label`` is a string specifying both the layer type and the index,
            e.g. ``'03Dense'``.

        - activations: list[tuple[np.array, str]]
            Contains the activations of a net. Same structure as
            ``spikerates``.

        - spiketrains: list[tuple[np.array, str]]
            Each entry in ``spiketrains`` contains a tuple
            ``(spiketimes, label)`` for each layer of the network (for the
            first batch only, and excluding ``Flatten`` layers).

            ``spiketimes`` is an array where the last index contains the spike
            times of the specific neuron, and the first indices run over the
            number of neurons in the layer: (n_chnls, n_rows, n_cols, duration)

            ``label`` is a string specifying both the layer type and the index,
            e.g. ``'03Dense'``.

    config: configparser.ConfigParser
        Settings.

    path: Optional[str]
        If not ``None``, specifies where to save the resulting image. Else,
        display plots without saving.

    data_format: Optional[str]
        One of 'channels_first' or 'channels_last'.
    """

    from snntoolbox.utils.utils import extract_label

    plot_keys = eval(config.get('output', 'plot_vars'))

    if len(plot_vars.keys()) == 0:
        return

    num_layers = len(list(plot_vars.values())[0])

    for i in range(num_layers):
        label = list(plot_vars.values())[0][i][1]
        name = extract_label(label)[1] \
            if config.getboolean('output', 'use_simple_labels') else label
        print("Plotting layer {}".format(label))
        newpath = os.path.join(path, label)
        if not os.path.exists(newpath):
            os.makedirs(newpath)
        if 'spiketrains' in plot_keys:
            plot_spiketrains(plot_vars['spiketrains_n_l_t'][i],
                             config.getfloat('simulation', 'dt'), newpath,
                             data_format)
        if 'spikerates' in plot_keys:
            plot_layer_activity(plot_vars['spikerates_n_l'][i],
                                str('Spikerates'),
                                newpath,
                                data_format=data_format)
            plot_hist(
                {'Spikerates': plot_vars['spikerates_n_l'][i][0].flatten()},
                'Spikerates', name, newpath)
        if 'activations' in plot_keys:
            plot_layer_activity(plot_vars['activations_n_l'][i],
                                str('Activations'),
                                newpath,
                                data_format=data_format)
        if 'spikerates_n_l' in plot_vars and 'activations_n_l' in plot_vars:
            plot_activations_minus_rates(plot_vars['activations_n_l'][i][0],
                                         plot_vars['spikerates_n_l'][i][0],
                                         name, newpath, data_format)
        if 'correlation' in plot_keys:
            plot_layer_correlation(
                plot_vars['spikerates_n_l'][i][0].flatten(),
                plot_vars['activations_n_l'][i][0].flatten(),
                str('ANN-SNN correlations\n of layer ' + name), config,
                newpath, False)