示例#1
0
def jd_to_heatmap(K, title, max_scale, save=True):

    # Generate a colormap
    cmap = "BuGn"
    x = [0.5, 1.5, 2.5]

    # Draw the heatmap with the mask and correct aspect ratio
    sns.heatmap(
        K,
        cmap=cmap,
        vmax=max_scale,
        vmin=.72,
        #center=0,
        square=True,
        linewidths=.75,
        cbar_kws={
            'shrink': .75,
            'label': ''
        },
        xticklabels=True,
        yticklabels=True,
        annot=True,
    )
    sns.set(font_scale=2)
    sns.set(style="white")
    plt.xticks(x, names)
    plt.yticks(x, names)
    plt.title(title)
    if save:
        filename = clean_filename(title, 'png', plot_directory)
        print(f'saving plot to {filename}')
        plt.savefig(filename)
    plt.show()
示例#2
0
def plot_gow(G, title, color, layout, save=True):
    """
    Plots graph of words
    Wrapper around nx.draw_network
    """
    verbose = True
    size = 15
    width = .15
    node_size = 200
    font_size = 30
    title_size = 25
    node_color = 'grey'

    layouts = map_layouts()
    pos = layouts[layout](G)

    plt.figure(figsize=(size, size))
    plt.title(title, fontsize=title_size)
    nx.draw_networkx(
        G,
        pos,
        width=width,
        node_size=node_size,
        node_color=node_color,
        font_size=font_size,
        font_color=color,
    )
    if save:
        if verbose:
            print(
                f'saving plot to {clean_filename(title , "png", plot_directory)}'
            )
        plt.savefig(clean_filename(title, 'png', plot_directory))
    plt.show()
示例#3
0
def plot_PR_curves(save=True):
    #Plot Precision-Recall curve for each class and iso-f1 curves
    # setup plot details
    legend_size = 12
    title_size = 18
    color_dict = get_color_dict()
    colors = cycle([
        list(color_dict.values())[0],
        list(color_dict.values())[1],
        list(color_dict.values())[2], 'darkorange', 'teal'
    ])

    clf = get_classifier_name(algo)
    title = f'{method}+{clf}'

    plt.figure(figsize=(7, 8))
    f_scores = np.linspace(0.2, 0.8, num=4)
    lines = []
    labels = []

    # plot iso-f1 curves
    for f_score in f_scores:
        x = np.linspace(0.01, 1)
        y = f_score * x / (2 * x - f_score)
        l, = plt.plot(x[y >= 0], y[y >= 0], color='gray', alpha=0.2)
        plt.annotate(f'f1={f_score:0.1f}', xy=(0.9, y[45] + 0.02))

    lines.append(l)
    labels.append('iso-f1 curves')
    l, = plt.plot(recall["micro"], precision["micro"], color='gold', lw=2)
    lines.append(l)
    labels.append(
        f'micro-average precision-recall (area = {average_precision["micro"]:0.2f})'
    )

    for i, color in zip(range(n_classes), colors):
        handle = string.ascii_uppercase[i]
        l, = plt.plot(recall[i], precision[i], color=color, lw=2)
        lines.append(l)
        labels.append(
            f'Precision-recall for handle {handle} (area = {average_precision[i]:0.2f})'
        )

    fig = plt.gcf()
    fig.subplots_adjust(bottom=0.25)
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.05])
    plt.xlabel('Recall')
    plt.ylabel('Precision')
    plt.title(title, fontsize=title_size)
    plt.legend(lines, labels, loc=(0, -.37), prop=dict(size=legend_size))
    if save:
        title = f'PR {algo} {method}'
        plt.savefig(clean_filename(title, 'png', plot_dir))
    plt.show()
示例#4
0
def pgv_plot(G, prefix, color, directory):
    """pygraphviz graph vizualisation"""
    verbose = 0

    # Convert nx graph to pyvizgraph
    A = _init_graph(G, prefix, color, 20)

    filename = clean_filename(prefix + '_pgv', 'png', directory)
    if verbose: print(f'Saving plot as {filename}')

    A.draw(filename, prog="circo")
示例#5
0
def plot_Gmeta(array1, array2, array3, title, ylabel, density):
    barWidth = .3
    colors = ['tan', 'yellowgreen', 'midnightblue']
    labels = ['Corpus', 'k-core', 'k-truss']
    names = get_names()

    bars = [array1, array2, array3]

    fig, ax = plt.subplots()
    # Set position of bar on X axis
    r = list()
    r.append(np.arange(len(bars[0])) + barWidth / 2)
    r.append([x + barWidth for x in r[0]])
    r.append([x + barWidth for x in r[1]])

    # Make the plot
    for i in range(3):
        plt.bar(r[i],
                bars[i],
                color=colors[i],
                width=barWidth,
                edgecolor='white',
                label=labels[i])

    text_x_offset = .1
    text_y_offset = 1.5
    for i in range(3):
        for j in range(3):
            x_pos = r[i][j] - barWidth / 3 + text_x_offset
            if density == False:
                y_pos = bars[i][j] + np.exp(text_y_offset)
                label = f'{bars[i][j]:.0f}'
            else:
                y_pos = bars[i][j] + np.log(1.0001)
                label = f'{bars[i][j]:.3f}'
            plt.text(x_pos,
                     y_pos,
                     label,
                     horizontalalignment='center',
                     rotation=0,
                     color='black',
                     fontsize=10)

    # Add ticks on the middle of the group bars
    plt.ylabel(ylabel, fontweight='normal')
    plt.xticks([r + barWidth for r in range(len(array1))], names)
    ax.set_yscale('log')
    plt.title(title)

    # Create legend show graphic & save to file
    plt.legend(loc='best', fontsize='small')
    plt.savefig(clean_filename(title, 'png', plot_directory))
    plt.show()
示例#6
0
def ROC_plot(fpr, tpr, roc_auc, n_classes, ix, gmean, algo, method, save=True):
    '''Plots ROC curves
    gmean = average
    '''
    color_dict = get_color_dict()
    names = get_names()
    handles = get_handles()

    lw = 1
    figsize = 6
    title = f'ROC {method}+{algo}'

    # Make plot
    plt.figure(figsize=(figsize, figsize))
    colors = cycle([
        color_dict[handles[0]], color_dict[handles[1]], color_dict[handles[2]]
    ])

    for i, color in zip(range(n_classes), colors):
        plt.plot(fpr[i],
                 tpr[i],
                 color=color,
                 linewidth=lw,
                 label=f'ROC {names[i]} (auc = {roc_auc[i]:0.2f})')
        if i == 0:
            plt.scatter(fpr[i][ix[i]],
                        tpr[i][ix[i]],
                        marker='o',
                        color='black',
                        label=f'Best (gmeans={gmean:.3f})')
        else:
            plt.scatter(fpr[i][ix[i]],
                        tpr[i][ix[i]],
                        marker='o',
                        color='black')
    plt.plot([0, 1], [0, 1], 'k--', linewidth=lw, label='No Skill')  # diagonal

    plt.xlim([0, 1])
    plt.ylim([0, 1])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title(title)
    plt.legend(loc="lower right")
    if save:
        plt.savefig(clean_filename(title, 'png', plot_directory))
    plt.show()
示例#7
0
def plot_confusion_matrix(y_pred,
                          y_test,
                          score,
                          handles,
                          algo,
                          method,
                          normalize,
                          save=True):
    """
    Plot a confusion matrix
    Expected True values x-axis & predicted y-axis
    obtained from : confusion_matrix(y_pred, y_test, labels = labels)
    note: this order is the opposite of that suggested in scikit-learn
    """
    figsize_x = 6.5
    figsize_y = 6
    cm = confusion_matrix(y_pred, y_test, labels=handles)
    print(cm)
    print(f'[confusion_matrix_wrapper] {algo} score = {score}\n')
    labels = get_names()
    #print(f'[plot_confusion_matrix] labels = {labels}')
    accuracy = np.trace(cm) / float(np.sum(cm))
    print(f'[plot_confusion_matrix] Accuracy={accuracy}')
    print(f'[plot_confusion_matrix] confusion matrix:\n{cm}')
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        cm = np.round(cm, 2)

    fig = plt.figure(figsize=(figsize_x, figsize_y))
    ax = fig.add_subplot(111)
    ax.matshow(cm)

    #if method == 'GOW': method = 'Graph of Words'
    title = f'{method}+{algo}'
    plt.title(title, y=1.1)
    plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Wistia)
    ax.set_xticklabels([''] + labels)
    ax.set_yticklabels([''] + labels)
    plt.ylabel('Predicted')
    plt.xlabel(f'True\naccuracy={accuracy:0.3f}')
    for i in range(3):
        for j in range(3):
            plt.text(j, i, str(cm[i][j]))
    if save:
        plt.savefig(clean_filename(title, 'png', plot_directory))
    plt.show()
示例#8
0
def kernel_to_heatmap(K, title, max_scale, save=True):

    # Generate a mask for the upper triangle
    #mask = np.triu(np.ones_like(K, dtype=np.bool))
    # Generate a custom diverging colormap
    cmap = "YlGn"
    rotation = 0
    x = [0.5, 1.5, 2.5]
    name_dict = get_name_dict()
    handles = name_dict.values()

    # Draw the heatmap with the mask and correct aspect ratio
    sns.heatmap(
        K,
        #mask=mask,
        cmap=cmap,
        vmax=max_scale,
        #center=0,
        square=True,
        linewidths=.75,
        cbar_kws={
            'shrink': .75,
            'label': 'Kernel values'
        },
        xticklabels=True,
        yticklabels=True,
        annot=True,
    )
    sns.set(font_scale=2)
    sns.set(style="white")

    plt.xticks(x, handles, rotation=rotation)
    plt.yticks(x, handles, rotation=0)
    plt.title(title)
    if save:
        filename = clean_filename(title, 'png', plot_directory)
        print(f'saving plot to {filename}')
        plt.savefig(filename)
    plt.show()