Beispiel #1
0
def pplot_patch(patch, resolution=1., return_fig=True, header=None):
    """
    plot a patch that has already been extracted
    :param header:
    :param patch:
    :param resolution:
    :param return_fig:
    :return:
    """
    if header is None:
        header = ['' for _ in range(len(patch))]

    # computing number of rows and columns...
    nb_rows = (len(patch) + 4) // 5
    nb_cols = 5

    plt('patch_ext',
        figsize=(nb_cols * 6.4 * resolution, nb_rows * 4.8 * resolution))
    fig = get_figure('patch_ext')
    for i, (t, p) in enumerate(zip(header, patch)):
        plt('patch_ext').subplot(nb_rows, nb_cols, i + 1)
        plt('patch_ext').title(t, fontsize=20)
        plt('patch_ext').imshow(p, aspect='auto')
        if len(p.shape) < 3:
            plt('patch_ext').colorbar()
    fig.tight_layout()
    if return_fig:
        return fig
    else:
        fig.show()
        plt('patch_ext').close(fig)
Beispiel #2
0
 def last_call(self):
     print('here')
     fig = get_figure(self.figure_name)
     ax = fig.gca()
     scatter = np.array(self.alignment_history)
     ax.plot(scatter)
     save_fig_direct_call(figure_name=self.figure_name)
Beispiel #3
0
 def last_call(self):
     """
     Last call of the callback. The figure is generated here
     :return:
     """
     fig = get_figure('StatCallback')
     ax = fig.gca()
     for j, i in enumerate(self.dir_variances):
         ax.plot(i, label='Layer ' + str(j + 1))
     fig.legend()
     save_fig_direct_call(figure_name='StatCallback')
Beispiel #4
0
    def last_call(self):
        # transform data into matrix

        matrix = np.array(self.parameters_history)
        matrix = matrix.reshape((matrix.shape[0], matrix.shape[1]))
        matrix = np.transpose(matrix, (1, 0))
        iterations = max(matrix.shape[1] - self.window_size + 1, 1)
        scatter_points = []
        # the number of iterations depend on the window size
        for i in range(iterations):
            variance = np.var(matrix[:, i:(i+self.window_size)], axis=1)

            if self.averaged:
                variance = [np.average(variance)]
            scatter_points.append(variance)
        scatter_points = np.array(scatter_points)

        fig = get_figure(self.fig_name)
        ax = fig.gca()
        for i in range(scatter_points.shape[1]):
            ax.plot(scatter_points[:, i])
        save_fig_direct_call(figure_name=self.fig_name)
Beispiel #5
0
    def last_call(self):
        # transform data into matrix
        matrix = np.transpose(np.array(self.filters_history), (1, 0, 2))

        iterations = max(matrix.shape[1] - self.window_size + 1, 1)
        scatter_points = []
        # the number of iterations depend on the window size
        for i in range(iterations):
            current_time_window = matrix[:, i:(i+self.window_size), :]

            # for each window what is the average filter
            mean_filters = np.average(current_time_window, axis=1)
            variance = []
            # for each filter
            for j in range(mean_filters.shape[0]):
                one_filter = []
                variance.append(one_filter)

                # for each occurrence of the filter in the time window
                for z in range(current_time_window.shape[1]):
                    # dot product
                    one_filter.append(np.dot(current_time_window[j, z], mean_filters[j]))

            # compute the variance of the dot product per filter
            variance = np.var(np.array(variance), axis=1)
            if self.averaged:
                variance = [np.average(variance)]
            scatter_points.append(variance)

        scatter_points = np.array(scatter_points)

        fig = get_figure(self.fig_name)
        ax = fig.gca()
        for i in range(scatter_points.shape[1]):
            ax.plot(scatter_points[:, i])
        save_fig_direct_call(figure_name=self.fig_name)
Beispiel #6
0
 def last_call(self):
     fig = get_figure('StatCallback')
     ax = fig.gca()
     for j, i in enumerate(self.dir_variances):
         ax.plot(i, label='Layer ' + str(j + 1))
     fig.legend()
Beispiel #7
0
 def last_call(self):
     fig = get_figure('ConvergenceCallBack')
     ax = fig.gca()
     for j, i in enumerate(self.convergence):
         ax.plot(i, label='Layer ' + str(j + 1))
     fig.legend()
Beispiel #8
0
 def last_call(self):
     fig = get_figure('JacobianCallBack')
     ax = fig.gca()
     ax.plot(self.JJT_norm)
     fig.legend()
Beispiel #9
0
 def last_call(self):
     fig = get_figure('GradientCallBack')
     ax = fig.gca()
     for j, i in enumerate(self.grad_mean):
         ax.plot(i, label='Layer ' + str(j + 1))
     fig.legend()
ax = plt('roc_curve').gca()

ax.set_xlim([-0.007, 1.0])
ax.set_ylim([0.0, 1.01])
ax.set_xlabel('False Positive Rate')
ax.set_ylabel('True Positive Rate')
ax.set_title('Receiver operating characteristic (AUC: %.3f)' % auc(fpr, tpr))

ax.plot([0, 1], [0, 1], color='red', linestyle='--', label='Random model')
ax.plot(fpr, tpr, color='yellow', label='IArt')
ax.plot([0, 0, 1], [0, 1, 1],
        color='green',
        linestyle='--',
        label='Perfect model')

ax.legend(loc="lower right")

ax = plt('confusion_matrix').gca()
y_threshold = (df.prediction > 0.6).astype(int)

matrix = confusion_matrix(df.true_label, y_threshold)

matrix = matrix / matrix.astype(np.float).sum(axis=1)

im = ax.imshow(matrix, cmap=cm.Greys_r, extent=(-3, 3, 3, -3))
ax.axis('off')
get_figure('confusion_matrix').colorbar(im)

save_fig()
def plot_on_map(activations,
                map_ids,
                n_cols=1,
                n_rows=1,
                figsize=4,
                log_scale=False,
                mean_size=1,
                selected=tuple(),
                legend=None,
                output="activations",
                style="grey",
                exp_scale=False,
                cmap=None,
                alpha=None,
                bad_alpha=1.,
                font_size=12,
                color_text='black',
                color_tick='black'):
    if log_scale:
        print_info("apply log...")
        activations = activations + 1.0
        activations = np.log(activations)
    elif exp_scale:
        print_info("apply exp...")
        p = np.full(activations.shape, 1.2)
        activations = np.power(p, activations)

    print_info("construct array activation map...")
    pos = []
    max_x = 0
    max_y = 0
    for id_ in map_ids:
        x, y = id_.split("_")
        x, y = int(x), int(y)
        pos.append((x, y))
        if x > max_x:
            max_x = x
        if y > max_y:
            max_y = y
    size = max(max_x + 1, max_y + 1)
    while size % mean_size != 0:
        size += 1
    nb = n_cols * n_rows
    act_map = np.ndarray((nb, size, size))
    act_map[:] = np.nan

    print_info("select neurons to print...")
    if len(selected) > 0:
        list_select = selected
    else:
        list_select = random.sample(list(range(activations.shape[1])), nb)

    print_info("fill activation map array...")
    for k, act in enumerate(activations):
        for idx, j in enumerate(list_select):
            x, y = pos[k][0], pos[k][1]
            act_map[idx, x, y] = act[j]
    """
    fig, axs = plt.subplots(n_rows, n_cols, sharex='col', sharey='row',
                            figsize=(n_cols*figsize*1.2, n_rows*figsize))
    fig.subplots_adjust(wspace=0.5)
    plt.tight_layout(pad=1.5)

    print_info("make figure...")
    for j in range(nb):
        if mean_size != 1:
            height, width = act_map[j].shape
            act_map_j = np.ma.average(np.split(np.ma.average(np.split(act_map[j], width // mean_size, axis=1),
                                               axis=2), height // mean_size, axis=1), axis=2)
        else:
            act_map_j = act_map[j]

        masked_array = np.ma.array(act_map_j, mask=np.isnan(act_map_j))
        cmap = matplotlib.cm.inferno
        cmap.set_bad('grey', 1.)
        im = axs[j // n_cols, j % n_cols].imshow(masked_array, cmap=cmap, interpolation='none')
        axs[j // n_cols, j % n_cols].set_title(str(list_select[j]))
        divider = make_axes_locatable(axs[j // n_cols, j % n_cols])
        cax = divider.append_axes("right", size="5%", pad=0.05)
        fig.colorbar(im, cax=cax)
    """

    font = {'family': 'normal', 'weight': 'bold', 'size': font_size}

    matplotlib.rc('font', **font)

    if legend is None:
        legend = list(map(str, list_select))

    mplt.rcParams['text.color'] = color_text
    mplt.rcParams['axes.labelcolor'] = color_tick
    mplt.rcParams['xtick.color'] = color_tick
    mplt.rcParams['ytick.color'] = color_tick

    plt(output, figsize=(n_cols * figsize * 1.2, n_rows * figsize))
    fig = get_figure(output)
    fig.subplots_adjust(wspace=0.05)

    print_info("make figure...")
    for j in range(nb):
        if mean_size != 1:
            height, width = act_map[j].shape
            act_map_j = np.nanmean(np.split(np.nanmean(np.split(act_map[j],
                                                                width //
                                                                mean_size,
                                                                axis=1),
                                                       axis=2),
                                            height // mean_size,
                                            axis=1),
                                   axis=2)
        else:
            act_map_j = act_map[j]
        print(act_map_j[2, 572])
        masked_array = np.ma.array(act_map_j, mask=np.isnan(act_map_j))
        if cmap is None:
            if style == "grey":
                cmap = matplotlib.cm.inferno
                cmap.set_bad('grey', bad_alpha)
            elif style == "white":
                cmap = matplotlib.cm.inferno
                cmap.set_bad('white', bad_alpha)
        ax = plt(output).subplot(n_rows, n_cols, j + 1)
        ax.set_facecolor((0, 0, 0, 0))
        im = plt(output).imshow(masked_array,
                                cmap=cmap,
                                interpolation='none',
                                alpha=alpha)
        plt(output).title(legend[j])
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.05)
        plt(output).colorbar(im, cax=cax)

    fig.tight_layout(pad=0.05)
    fig.patch.set_alpha(0.0)

    save_fig(figure_name=output, extension='png')