def __init__(self,img_path,label_path,num_color = 10):
     self.img = cv2.imread(img_path)
     self.img_o = cv2.imread(img_path)
     self.img_t = cv2.imread(img_path)
     create_c = np.array(cm.tab10(num_color))[:3]*255
     self.color_list = [np.array(cm.tab10(color_num))[:3]*255 for color_num in range(num_color)]
     self.x1,self.x2,self.y1,self.y2 = 0,0,0,0
     self.drawing = False
     self.label = label_path
Exemple #2
0
def plot_orbital_list(orbital_idx, C, bases, postfix='', **kwargs):
    """ Visualizing all orbitals
    """

    for j, i in enumerate(orbital_idx):
        if i - 1 >= C.shape[1] or i - 1 < 0:
            print('Orbital %d does not exist. Skipping' % i)
        else:
            plot_orbital(C[:, i - 1], bases, color=cm.tab10(j)[:3], **kwargs)
            mlab.text(0.05,
                      0.1 * j,
                      str(i) + postfix,
                      width=0.2,
                      color=cm.tab10(j)[:3])
Exemple #3
0
def build_plot(y_true=[], scores=[], labels=[]):
    """
    Generates two plots: a roc plot and a preision/recall plot
    """
    gradient = np.linspace(0, 1, 10)
    color_list = [cm.tab10(x) for x in gradient]

    fig, axes = plt.subplots(1, 2, figsize=(12, 5),
                             sharex=True, sharey=True)
    ax = axes[0]
    n_line = 0
    for i_score, score in enumerate(scores):
        fpr, tpr, _ = roc_curve(y_true[n_line], score, drop_intermediate=False)
        n_line = n_line + 1
        ax.plot(fpr, tpr, linestyle='-.', c=color_list[i_score], lw=1, label=labels[i_score])
    ax.set_title("ROC", fontsize=20)
    ax.set_xlabel('False Positive Rate', fontsize=18)
    ax.set_ylabel('True Positive Rate (Recall)', fontsize=18)
    ax.legend(loc='lower center', fontsize=8)

    ax = axes[1]
    n_line = 0
    for i_score, score in enumerate(scores):
        precision, recall, _ = precision_recall_curve(y_true[n_line], score)
        n_line = n_line + 1
        ax.step(recall, precision, linestyle='-.', c=color_list[i_score], lw=1, where='post', label=labels[i_score])
    ax.set_title("Precision-Recall", fontsize=20)
    ax.set_xlabel('Recall (True Positive Rate)', fontsize=18)
    ax.set_ylabel('Precision', fontsize=18)
    ax.legend(loc='lower center', fontsize=8)
    plt.show()
Exemple #4
0
def plot_param(kfoldres,algoname):

    params,acc = kfoldres
    ntrial = 10
    fig, ax = plt.subplots()
    acc_mean = np.round(np.mean(acc[algoname],1)[:,0]*100)
    #ax.scatter(range(ntrial),acc_mean)
    feat_mean =  np.mean(acc[algoname],1)[:,1]
    import matplotlib.cm as cm
    colors = cm.tab10(np.linspace(0, 1, ntrial))
    #plt.scatter(11, 1, color='white',label = '(regwgt,thresh)')
    #plt.scatter(11, 1, color='white',label = 'Fisher_thresh')
    plt.scatter(11, 1, color='white',label = 'MP_eps')
    for x,(y, c) in enumerate(zip(acc_mean, colors)):
        #lbl = "(%f,%f)"%(params['L1_regwgt'][x], params['L1_thresh'][x])
        #lbl = "%f"%(params['Fisher_thresh'][x])
        lbl = "%f"%(params['MP_eps'][x])
        plt.scatter(x, y, color=c,label = lbl)
        txt = "%d"%feat_mean[x]
        ax.annotate(txt, (x, acc_mean[x]),fontsize='large')
    ax.legend(fontsize='large')
    ax.tick_params(direction='out', labelsize='medium')
    plt.xticks(np.arange(ntrial), range(ntrial))
    #plt.title('Hyperparameters tuning for %s'%algoname,fontsize='large')
    plt.title('Hyperparameters tuning for Matching Pursuit',fontsize='large')
    plt.xlabel('Trial',fontsize='large')
    plt.ylabel('Accuracy',fontsize='large')
    plt.savefig('%s.png'%algoname,bbox_inches='tight')
Exemple #5
0
def plot_latent(dataLoader, model, vectors=(0,1)):
    """For 2D latent spaces 
    """

    digits = range(10)
    colors = [cm.tab10(digit/10.0) for digit in digits]
    coldict = {d:c for d, c in zip(digits, colors)}

    fig, axes = plt.subplots()

    # fake legend
    for d, c in zip(digits, colors):
        plt.scatter(-100, -100, c=[c], label=d)
    plt.legend()

    # get the latent space values and plot them in colors of digits
    for i, (data, labels) in enumerate(dataLoader):
        with torch.no_grad():
            data = data.to(DEVICE)
            mu = model.forward_mu(data.view(-1, 784))
            for digit, color in zip(digits, colors):
                digitMask = labels == digit
                x, y = vectors
                plt.scatter(mu[:, x][digitMask].cpu(), mu[:, y][digitMask].cpu(),
                            c=[color], alpha=0.12)

    plt.title("Autoencoders Latent space")
    plt.xlabel(f"Dimension {vectors[0]}")
    plt.ylabel(f"Dimension {vectors[1]}")
    plt.xlim(-15, 15)
    plt.ylim(-5, 5)
    plt.tight_layout()
    return fig, axes
 def _set_clusters(self):
     """ Set clusters colors """
     # Set color for each pre-labelled cluster
     for i in range(len(self.cluster_names)):
         color = cm.tab10(i / len(self.cluster_names))
         color_hex = mpl_colors.rgb2hex(color[:3])
         self.cluster_colors[self.cluster_names[i]] = color_hex
Exemple #7
0
def getColorPallet(palletSize=1, palletName="tab10"):
    pallet = []
    if palletName == "tab10":
        for i in range(palletSize):
            color = tuple((np.array(cm.tab10(i))[:3]*255))
            pallet.append(color)
    return pallet
Exemple #8
0
def scatter_with_compare(X2d, y, predicted_labels, dataset_name):
    fig, axes = plt.subplots(1, 2, figsize=(17, 6))
    plt.rcParams.update({'axes.titlesize': 'xx-large'})

    axes[0].scatter(X2d[:, 0],
                    X2d[:, 1],
                    marker='o',
                    color='white',
                    alpha=1.0,
                    linewidths=1,
                    s=64,
                    cmap='tab10',
                    edgecolors=cm.tab10(y))
    axes[0].set_title('Position by MPPCA, Color by True Label')

    axes[1].scatter(X2d[:, 0],
                    X2d[:, 1],
                    c=predicted_labels,
                    s=64,
                    alpha=0.7,
                    cmap='tab10')
    axes[1].set_title('Position and Color by MPPCA')

    plt.tight_layout()
    plt.savefig('./plots/mppca_{}.png'.format(dataset_name))
    plt.gcf().clear()
    def make_ellipses(self, gmm, ax, clusters):
        colors = []
        for i in range(clusters):
            color = cm.tab10(i / clusters)
            color_hex = mpl_colors.rgb2hex(color[:3])
            colors.append(color_hex)

        for n, color in enumerate(colors):
            if gmm.covariance_type == 'full':
                covariances = gmm.covariances_[n][:2, :2]
            elif gmm.covariance_type == 'tied':
                covariances = gmm.covariances_[:2, :2]
            elif gmm.covariance_type == 'diag':
                covariances = np.diag(gmm.covariances_[n][:2])
            elif gmm.covariance_type == 'spherical':
                covariances = np.eye(gmm.means_.shape[1]) * gmm.covariances_[n]
            v, w = np.linalg.eigh(covariances)
            u = w[0] / np.linalg.norm(w[0])
            angle = np.arctan2(u[1], u[0])
            angle = 180 * angle / np.pi  # convert to degrees
            v = 2. * np.sqrt(2.) * np.sqrt(v)
            ell = mpl.patches.Ellipse(gmm.means_[n, :2],
                                      v[0],
                                      v[1],
                                      180 + angle,
                                      color=color)
            ell.set_clip_box(ax.bbox)
            ell.set_alpha(0.5)
            ax.add_artist(ell)
Exemple #10
0
def evaluate(dataset_name, id):
    X, y, K = load_dataset(id)

    gmm = GaussianMixture(n_components=K, covariance_type='diag')
    gmm.fit(X)
    predicted_labels1 = gmm.predict(X)
    measure_cluster(y, predicted_labels1, msg='GMM on the original dataset')

    pca = PCA(n_components=K)
    X2d = pca.fit_transform(X)
    gmm2 = GaussianMixture(n_components=K, covariance_type='diag')
    gmm2.fit(X2d)
    predicted_labels2 = gmm2.predict(X2d)
    measure_cluster(y, predicted_labels2, msg='PCA then GMM on reduced data')

    # plots
    fig, axes = plt.subplots(1, 3, figsize=(21, 7))
    plt.rcParams.update({'axes.titlesize': 'xx-large'})

    # True label
    axes[0].scatter(X2d[:, 0],
                    X2d[:, 1],
                    marker='o',
                    color='white',
                    alpha=1.0,
                    linewidths=1,
                    s=64,
                    cmap='tab10',
                    edgecolors=cm.tab10(y))
    axes[0].set_title('Border color = True labels')

    # GMM labels
    # axes[1].scatter(X2d[:, 0], X2d[:, 1], marker='o', color='white', alpha=0.6,
    #             linewidths=1, s=64,
    #             cmap='tab10', edgecolors=cm.tab10(y))
    axes[1].scatter(X2d[:, 0],
                    X2d[:, 1],
                    marker='o',
                    alpha=1.0,
                    linewidths=1,
                    s=64,
                    cmap='tab10',
                    c=predicted_labels1)
    axes[1].set_title('Predicted labels with GMM on original data')

    # PCA -> GMM labels
    # axes[2].scatter(X2d[:, 0], X2d[:, 1], marker='o', color='white', alpha=0.6,
    #             linewidths=1, s=64,
    #             cmap='tab10', edgecolors=cm.tab10(y))
    axes[2].scatter(X2d[:, 0],
                    X2d[:, 1],
                    c=predicted_labels2,
                    s=64,
                    alpha=1.0,
                    cmap='tab10')
    axes[2].set_title('Predicted labels with GMM on reduced data by PCA')

    plt.tight_layout()
    plt.savefig('./plots/pca_gmm_{}.png'.format(dataset_name))
Exemple #11
0
    def _class_to_color(self, class_):
        if self.num_classes <= 10:
            colormap = cm.tab10(np.arange(self.num_classes))
        else:
            colormap = cm.gist_stern(
                np.arange(self.num_classes) / self.num_classes)

        return tf.gather(colormap, class_, axis=0)
Exemple #12
0
def color(idx):
    import matplotlib.cm as cm
    import numpy as np
    if idx == 0:
        colors = cm.tab10(np.linspace(0, 1, 10))
    elif idx == 1:
        colors = cm.tab20(np.linspace(0, 1, 20))
    return colors
Exemple #13
0
def colors_1_to_255(colors_1):
    num_colors = len(colors_1)

    colors_255 = []
    for i in range(num_colors):
        colors_255_i = tuple(np.flip(np.array(cm.tab10(i))[0:3]*255))
        colors_255.append(colors_255_i)

    return colors_255
Exemple #14
0
def setup_marker_colors():
    for i in range(10):
        color = list(cm.tab10(i)[:3])
        color[0] = int(color[0] * 255)
        color[1] = int(color[1] * 255)
        color[2] = int(color[2] * 255)
        color = color[::
                      -1]  # This is a bug fix to BGR to RGB behaviour in opencv3
        color = tuple(color)
        marker_colors.append(color)
Exemple #15
0
def scatter(codes, labels, top_n=8):

    #fig = plt.figure()
    '''
    if codes.shape[1] == 2:
        ndim = 2
        ax = fig.add_subplot(111)
    elif codes.shape[1] == 3:
        ndim = 3
        ax = fig.add_subplot(111, projection='3d')
    else:
        raise ValueError("Codes must have 2 or 3 dimensions")
    '''
    ndim = codes.shape[1]
    plotsize = 7
    counter = Counter(labels)
    if top_n <= len(set(labels)):
        nlabels = top_n
    else:
        nlabels = len(set(labels))
    colors = cm.tab10(np.linspace(0, 1, nlabels))
    for index, element in enumerate(counter.most_common()):
        if index < nlabels and element[0] != 'NA':
            lab = element[0]
            x_vals = [
                codes[:, 0][i] for i in np.arange(len(labels))
                if labels[i] == lab
            ]
            y_vals = [
                codes[:, 1][i] for i in np.arange(len(labels))
                if labels[i] == lab
            ]
            if ndim == 2:
                ax.scatter(x_vals,
                           y_vals,
                           s=plotsize,
                           label=str(lab),
                           color=colors[index],
                           marker='o',
                           alpha=0.5)
            elif ndim == 3:
                z_vals = [
                    codes[:, 2][i] for i in np.arange(len(labels))
                    if labels[i] == lab
                ]
                ax.scatter(x_vals,
                           y_vals,
                           z_vals,
                           s=plotsize,
                           label=str(lab),
                           color=colors[index],
                           marker='o',
                           alpha=0.6)
Exemple #16
0
def plot_planes(X, y, local_model, central_model, dist_model):
    sns.set_style('ticks')

    y = pd.DataFrame(y)
    y.loc[y[0] == -1, 0] = colors.to_hex(cm.Pastel2(0))
    y.loc[y[0] == 1, 0]  = colors.to_hex(cm.Pastel2(1))
    y = y.values.T[0]

    w, b = get_average_best_plane(dist_model)

    plt.figure()
    draw_plane(w,
               b,
               cm.tab10(0),
               1,
               2.2,
               '-',
               "SVM Distribuído com C = " + str(dist_model.C) + " e " + "c = " + str(dist_model.c))
    draw_plane(central_model.coef_[0],
               central_model.intercept_[0],
               cm.tab10(1),
               1,
               2.2,
               '--',
               "SVM Central com C = " + str(central_model.get_params()['C']))
    draw_plane(local_model.coef_[0],
               local_model.intercept_[0],
               cm.tab10(2),
               1,
               2.2,
               '-.',
               "SVM Local com C = " + str(local_model.get_params()['C']))


    plt.scatter(X[:, 0], X[:, 1], marker = 'o', c = y, alpha = 0.5)
    sns.despine()
    plt.legend(loc = 2)
    plt.ylim(-4.8, 4.8)
    file = str(plots_path) + "/simple_graph_compare.pdf"
    plt.savefig(file, transparent = True)
Exemple #17
0
def label_to_2d_image(labels, alpha=0.5, cmap=None):
    """
    :param labels: (x, y, z), values are label values
    :return: (x, y, rgba)
    """
    labels_2d = labels.max(-1).T
    if cmap:
        rgba = cmap((labels_2d % 10 + 1) * (labels_2d > 0))
    else:
        rgba = cm.tab10((labels_2d % 10 + 1) * (labels_2d > 0))
    rgba[:, :, -1] = alpha
    rgba[np.where(labels_2d == 0)] = np.zeros(4)
    return rgba
Exemple #18
0
def label_to_2d_image(labels, z='sum', alpha=0.5):
    """
    :param labels: (x, y, z), values are label values
    :return: (x, y, rgba)
    """
    if z == 'sum':
        labels_2d = labels.max(-1)
    else:
        labels_2d = labels[z, :, :]
    rgba = cm.tab10(labels_2d)
    rgba[:, :, -1] = alpha
    rgba[np.where(labels_2d == 0)] = np.zeros(4)
    return rgba
Exemple #19
0
def get_colors(num_colors = 5,type = 'lines'):
    colors = []
    for i in range(num_colors):
        if type == 'gradual':
            color = np.array([0, 0, 0])+i/num_colors
            rgb = tuple(color* 255)
            colors.append(rgb)
        elif type == 'lines':
            # convert to RGB
            rgb = tuple(np.flip(np.array(cm.tab10(i))[0:3]*255))
            colors.append(rgb)

    return colors
 def test_assign_colors(self):
     X = np.array([[1, 3], [4, 6], [7, 9], [10, 12]])
     Y = np.array([[100, 1000], [200, 2000], [300, 3000], [400, 4000]])
     ds = Dataset(X, Y, random_state=10)
     ds.assign_colors()
     arr = np.array([0., 1.])
     self.assertIn('f0', ds.feature_colors.keys())
     self.assertIn('f1', ds.feature_colors.keys())
     self.assertIn('t0', ds.target_colors.keys())
     self.assertIn('t1', ds.target_colors.keys())
     self.assertTrue(np.allclose(np.array(list(ds.feature_colors.values())),
                                 cm.tab10(arr)))
     self.assertTrue(np.allclose(np.array(list(ds.target_colors.values())),
                                 cm.Dark2(arr)))
Exemple #21
0
def waves(data, metric, title, sax=None, wax=None, rat=None, n=15, logy=True):

    if sax is None:
        fig, (sax, wax, rat) = plt.subplots(nrows=1,
                                            ncols=3,
                                            figsize=(16, 5),
                                            dpi=150)
        fig.set_facecolor('white')

    series = data[metric]
    minima = series.index[argrelextrema(series.values, np.less, order=n)[0]]
    maxima = series.index[argrelextrema(series.values, np.greater, order=n)[0]]
    waves = list(zip_longest(minima, maxima[1:]))

    series.plot(logy=logy, c='grey', ax=sax, title=title)
    series.loc[minima].plot(c='g', style='.', ax=sax)
    series.loc[maxima].plot(c='r', style='.', ax=sax)
    sax.title.set_fontweight('bold')

    df = pd.DataFrame()
    colours = []
    maxes = []

    for i, (start, end) in enumerate(waves, start=2):
        colour = cm.tab10(i)
        colours.append(colour)
        wave_data = data[metric].loc[start:end]
        wave_data.plot(ax=sax, color=colour)
        series = wave_data.reset_index()[metric]
        series -= series[0]
        name = f'Wave {i}, {start:%b %y}'
        df[name] = series
        maxes.append((series.max(), name))

    df.index.name = 'days'
    df.plot(logy=logy, title='Relative to Wave Start', ax=wax, color=colours)
    wax.legend(loc='lower right')

    relative_to_name = sorted(maxes)[-1][1]
    relative_to = df[relative_to_name]
    relative_to.fillna(relative_to.max(), inplace=True)
    ratio = df.divide(relative_to, axis='rows')
    ratio.plot(ax=rat,
               color=colours,
               legend=False,
               title='Relative to Worst',
               ylim=(0, 1))
    rat.yaxis.set_major_formatter(
        FuncFormatter(lambda y, pos: f"{y * 100:,.0f}%"))
Exemple #22
0
def _create_categorical_colors(n_categories: int):
    if n_categories > 51:
        raise ValueError(
            f"Maximum number of colors (51) exceeded: `{n_categories}`.")
    colors = [cm.Set1(i) for i in range(cm.Set1.N)][:n_categories]
    colors += [cm.Set2(i)
               for i in range(cm.Set2.N)][:n_categories - len(colors)]
    colors += [cm.Set3(i)
               for i in range(cm.Set3.N)][:n_categories - len(colors)]
    colors += [cm.tab10(i)
               for i in range(cm.tab10.N)][:n_categories - len(colors)]
    colors += [cm.Paired(i)
               for i in range(cm.Paired.N)][:n_categories - len(colors)]

    return _convert_to_hex_colors(colors)
def plot(X,Y,model,coefs,initial_conditions,tmin,tmax,dataset,path = ''):
    x = Variable(torch.from_numpy(X), requires_grad=False).type(torch.FloatTensor)
    fig, ax = plt.subplots( nrows=1, ncols=1 ) 
    for i in range(100):
        prediction = model(x)[0][:, :Y.shape[1]].data.numpy()
        for dim in range(Y.shape[1]):
            col = cm.tab10(dim)
            ax.plot(X, prediction[:, dim], color=col, alpha=0.1)

    for dim in range(Y.shape[1]):
        col = cm.tab10(dim)
        ax.scatter(X, Y[:, dim], color=col, alpha=0.1)

    real_x,real_y = generate_data(500, initial_conditions, coefs.flatten(), dataset, tmin, tmax)
    for dim in range(Y.shape[1]):
        col = cm.tab10(dim)
        ax.scatter(real_x, real_y[:, dim], color=col)    

    if len(path) > 0:
        fig.savefig(path, bbox_inches='tight')
        plt.close(fig)
    else:
        fig.show()
        plt.close(fig)
Exemple #24
0
def plot_clusters(
    X,
    y,
    dim,
    points,
    labels_prefix='cluster',
    points_name='centroids',
    colors=cm.tab10,  # a qualitative map 
    # https://matplotlib.org/examples/color/colormaps_reference.html
    #                   colors = ['brown', 'orange', 'olive',
    #                             'green', 'cyan', 'blue',
    #                             'purple', 'pink'],
    #                   points_color = 'red'
    points_color=cm.tab10(
        10)  # by default the last of the map (to be improved)
):
    """
    Plot a two dimensional projection of an array of labelled points
    X:      array with at least two columns
    y:      vector of labels, length as number of rows in X
    dim:    the two columns to project, inside range of X columns, e.g. (0,1)
    points: additional points to plot as 'stars'
    labels_prefix: prefix to the labels for the legend ['cluster']
    points_name:   legend name for the additional points ['centroids']
    colors: a color map
    points_color: the color for the points
    """
    # plot the labelled (colored) dataset and the points
    labels = np.unique(y)
    for i in range(len(labels)):
        color = colors(i / len(labels))  # choose a color from the map
        plt.scatter(
            X[y == labels[i], dim[0]],
            X[y == labels[i], dim[1]],
            s=10,
            c=[color],  # scatter requires a sequence of colors
            marker='s',
            label=labels_prefix + str(labels[i]))
    plt.scatter(points[:, dim[0]],
                points[:, dim[1]],
                s=50,
                marker='*',
                c=[points_color],
                label=points_name)
    plt.legend()
    plt.grid()
    plt.show()
Exemple #25
0
def overlapping_histograms(
        *args, **kwargs):  # overlapping semi-transparent histograms
    from matplotlib.pyplot import gca, Axes

    #the first positional arg may be a subplot or the array
    if isinstance(args[0], Axes): sp, args = args[0], args[1:]
    else: sp = gca()

    labels = kwargs.get(
        'labels', None) or ['data ' + str(n + 1) for n in range(len(args))]

    #remove key 'labels' from kwargs
    if 'labels' in kwargs: del kwargs['labels']

    #make sure the lengths match
    assert len(labels) == len(args), "number of labels doesnt match"

    #handle colours list
    from matplotlib.cm import tab10
    colors = kwargs.get('colors', None) or kwargs.get(
        'colours', None) or [tab10(n) for n in range(len(args))]
    assert len(colors) == len(args), "number of colors does not match"

    #remove key 'color' & 'colours' from kwargs
    kwargs.pop('color') if kwargs.__contains__('color') else None
    kwargs.pop('colors') if kwargs.__contains__('colors') else None

    #let the rest of the keywords provided by the user be added to the dict which will be passes into plt.hist function
    d = dict(histtype='stepfilled', alpha=0.3, normed=True, bins=40)
    d.update(kwargs)

    #draw the histograms
    [
        sp.hist(arr, **d, label=labels[i], color=colors[i])
        for i, arr in enumerate(args)
    ]
    sp.legend()
    return sp
Exemple #26
0
 def Plot_predictions(self, predictions, names=[], group=[], group_name=[]):
     Xrange = np.linspace(self.minX, self.maxX, 30).reshape([30, 1])
     scaling = self.mean_std_X[0][1] * self.max_X[0]
     for i in range(len(predictions)):
         valid_indices = np.where(np.array(predictions[i]) != 0)
         if len(group) > 0:
             col_group_sub = cm.tab10(group[i])
             plt.plot(Xrange[valid_indices] * scaling +
                      self.mean_std_X[0][0],
                      np.array(predictions[i])[valid_indices],
                      color=col_group_sub)
         else:
             plt.plot(
                 Xrange[valid_indices] * scaling + self.mean_std_X[0][0],
                 np.array(predictions[i])[valid_indices])
         if len(names) > 0:
             max = np.int(
                 np.where(predictions[i] == np.max(predictions[i]))[0])
             plt.annotate(names[i],
                          xy=(Xrange[max] * scaling + self.mean_std_X[0][0],
                              predictions[i][max]))
     plt.title('Predicted staging')
     plt.show()
 def print_summary(self):
     times = np.array(self.runtimes)
     mean_times = np.mean(times, axis=0)
     names = [
         "Subsequence", "SAX", "Search", "Collision", "Filtering",
         "Gap Score"
     ]
     colors = [cm.tab10(i) for i in range(len(names))]
     plt.figure(figsize=(10, 9))
     plt.title("Runtime per Section")
     plt.ylabel("Runtime (s)")
     plt.xlabel("Section")
     plt.bar(range(len(names)), mean_times, color=colors)
     plt.xticks(range(len(names)), labels=names)
     plt.savefig(join(getcwd(), "bar_chart.png"))
     normalized = 100 * mean_times / np.sum(mean_times)
     plt.figure(figsize=(10, 9))
     plt.title("Percentage of Total Runtime by Section")
     plt.pie(normalized,
             labels=names,
             autopct="%2.2f%%",
             explode=(0.15, 0.15, 0.15, 0.15, 0.15, 0.15),
             colors=colors)
     plt.savefig(join(getcwd(), "usage_chart.png"))
Exemple #28
0
bp4 = plt.boxplot(np.transpose(result_all_unet[3, :]),
                  positions=[positions[3]],
                  widths=width)
bp5 = plt.boxplot(np.transpose(result_all_deeplab[0, :]),
                  positions=[positions[0] + width],
                  widths=width)
bp6 = plt.boxplot(np.transpose(result_all_deeplab[1, :]),
                  positions=[positions[1] + width],
                  widths=width)
bp7 = plt.boxplot(np.transpose(result_all_deeplab[2, :]),
                  positions=[positions[2] + width],
                  widths=width)
bp8 = plt.boxplot(np.transpose(result_all_deeplab[3, :]),
                  positions=[positions[3] + width],
                  widths=width)
set_box_color(bp1, cm.tab10(0), 'blue')
set_box_color(bp2, cm.tab10(0), 'red')
set_box_color(bp3, cm.tab10(0), 'green')
set_box_color(bp4, cm.tab10(0), 'purple')
set_box_color(bp5, cm.tab10(1), 'blue')
set_box_color(bp6, cm.tab10(1), 'red')
set_box_color(bp7, cm.tab10(1), 'green')
set_box_color(bp8, cm.tab10(1), 'purple')
plt.xlim([-0.25, 3.75])
plt.xticks(
    np.arange(len(run_types)) + width / 2,
    ['base', 'low diversity', 'high diversity', 'higher diversity'])
plt.plot([], c=cm.tab10(0), label='U-Net')
plt.plot([], c=cm.tab10(1), label='Deeplab-CRF')
plt.ylim([75, 77])
plt.legend(loc='lower left')
def create_rgb(i):
    return tuple(np.array(cm.tab10(i)[:3]) * 255)
Exemple #30
0
def tree_correlation_plot_list(correlations_list,
                               x,
                               y,
                               plot_file=None,
                               labels=[],
                               param_dict_list=[],
                               min_joint_number=10,
                               scale_t=False,
                               ylim=[-0.3, 1.1],
                               xlim=[None, None]):
    mapping = {
        z: i
        for i, z in enumerate([
            "x(t+dt)", "g(t+dt)", "l(t+dt)", "q(t+dt)", "x(t)", "g(t)", "l(t)",
            "q(t)"
        ])
    }

    norm = mcolors.Normalize(vmin=0, vmax=9.9)

    colors_sets = {}
    for i, l in enumerate(labels):
        colors_sets[l] = cm.tab10(norm(i))

    # =========== figure =========== #
    fig, _ = plt.subplots(figsize=(8, 4))
    ax0 = plt.subplot2grid((1, 1), (0, 0))
    axs = [ax0]

    for ax in axs:
        ax.spines["top"].set_visible(False)
        ax.spines["right"].set_visible(False)
        # set the x-spine
        ax.spines['left'].set_position('zero')

        # turn off the right spine/ticks
        ax.spines['right'].set_color('none')
        ax.yaxis.tick_left()

    # =========== plot =========== #
    # decide if exponential will be plotted
    for correlations, param_dict, label in zip(correlations_list,
                                               param_dict_list, labels):
        gamma = None
        if x[0] == "l" and y[0] == "l":
            gamma = param_dict["gamma_lambda"]
        elif x[0] == "q" and y[0] == "q":
            gamma = param_dict["gamma_q"]

        # =========== correlation =========== #
        rs = []
        errs = []

        dts = []
        corr_naive = []

        for i, corr in enumerate(correlations):
            if corr.n > min_joint_number:
                dts.append(corr.dt)

                rs.append(corr.corr_mle[mapping[x], mapping[y]])
                errs.append(corr.corr_mle_err[mapping[x], mapping[y]])

                corr_naive.append(corr.corr_naive[mapping[x], mapping[y]])

        dts = np.array(dts).astype(float)
        if scale_t:
            dts /= (np.log(2) / param_dict["mean_lambda"])
            if gamma != None:
                gamma *= (np.log(2) / param_dict["mean_lambda"])

        else:
            if param_dict != None:
                ax0.axvline(np.log(2) / param_dict["mean_lambda"],
                            color=colors_sets[label],
                            alpha=0.5)

        ax0.errorbar(dts,
                     rs,
                     yerr=errs,
                     lw=2,
                     color=colors_sets[label],
                     label=label)

        if gamma != None:
            ax0.plot(dts,
                     np.exp(-dts * gamma),
                     ls='--',
                     color=colors_sets[label],
                     alpha=0.6)
        else:
            ax0.plot(dts, dts * 0, color=colors_sets[label])

    # ===== layout ===== #
    ax0.set_ylabel(r"$\langle {:s}, {:s}\rangle$".format(x, y))
    ax0.set_ylim(ylim)
    ax0.set_xlim(xlim)
    ax0.legend()
    if scale_t:
        ax0.set_xlabel("norm. dt")

    else:
        ax0.set_xlabel("dt (min)")

    fig.tight_layout(h_pad=4)
    if plot_file != None:
        plot_output = plot_file.format(y[0], x[0])
        print("Saved in", plot_output)
        fig.savefig(plot_output, dpi=300, facecolor="white")
    else:
        plt.show()
from nets.vgg16 import vgg16
from nets.resnet_v1 import resnetv1

import torch

CLASSES = ('__background__',
           'aeroplane', 'bicycle', 'bird', 'boat',
           'bottle', 'bus', 'car', 'cat', 'chair',
           'cow', 'diningtable', 'dog', 'horse',
           'motorbike', 'person', 'pottedplant',
           'sheep', 'sofa', 'train', 'tvmonitor')

NETS = {'vgg16': ('vgg16_faster_rcnn_iter_%d.pth',), 'res101': ('res101_faster_rcnn_iter_%d.pth',)}
DATASETS = {'pascal_voc': ('voc_2007_trainval',), 'pascal_voc_0712': ('voc_2007_trainval+voc_2012_trainval',)}

COLORS = [cm.tab10(i) for i in np.linspace(0., 1., 10)]


def demo(net, image_name):
    """Detect object classes in an image using pre-computed object proposals."""

    # Load the demo image
    im_file = os.path.join(cfg.DATA_DIR, 'demo', image_name)
    im = cv2.imread(im_file)

    # Detect all object classes and regress object bounds
    timer = Timer()
    timer.tic()
    scores, boxes = im_detect(net, im)
    timer.toc()
    print('Detection took {:.3f}s for {:d} object proposals'.format(timer.total_time(), boxes.shape[0]))
Exemple #32
0
def stacked_bar_plot(data, labels, legend=None, table_header=None, title=None,
                     ax_names=None, normalize=False, normalize_factor=None,
                     width=0.8):
    """Creates a stacked bar plot.

    Parameters
    ----------
    data : numpy.array
        Multi-dimensional array.
    labels : list
        List of xtick labels. Should have the same length as `data`.
    title : str
        Title of the plot.
    table_header : list
        List with the header of the table object. Each element represents
        a column.
    title : str
        Title of the plot.
    ax_names : list
        List with the labels for the x-axis (first element) and y-axis
        (second element).
    normalize : bool
        If True, values of the `data` array will be normalized by the
        `normalize_factor`
    normalize_factor : int or float
        Number used to normalize values of the `data` array.

    Returns
    -------
    fig : matplotlib.Figure
        Figure object of the plot.
    lgd : matplotlib.Legend
        Legend object of the plot.
    table : list
        Table data in list format. Each item in the list corresponds to a
        table row.
    """

    plt.rcParams["figure.figsize"] = (8, 6)

    if normalize:

        data_original = np.copy(data)
        data = np.array([[y / normalize_factor for y in x] for x in data])

    if len(labels) > 10:
        plt.rcParams["figure.figsize"] = (len(labels) / 3, 6)
    else:
        plt.rcParams["figure.figsize"] = (8, 6)

    # Use ggpot style
    plt.style.use("ggplot")

    fig, ax = plt.subplots()

    # Get bottom positions for stacked bar
    bottoms = np.cumsum(np.vstack((np.zeros(data.shape[1]), data)),
                        axis=0)[:-1]

    # Get x positions
    xpos = [x + (width / 2) for x in range(len(labels))]

    for c, d in enumerate(data):

        if len(data) <= 10:
            c1 = c if c < 9 else c - 10
            clr = cm.tab10(c1, 1)
        else:
            c1 = c if c < 19 else c - 20
            clr = cm.tab20(c1, 1)

        if legend:
            current_lgd = legend[c]
        else:
            current_lgd = None

        if c == 0:
            bplot = ax.bar(xpos, d, width, color=clr, label=current_lgd,
                           alpha=.9)
        else:
            bplot = ax.bar(xpos, d, width, color=clr, label=current_lgd,
                           alpha=.9, bottom=bottoms[c])

    # Set x labels
    plt.xticks([x + (width / 2) for x in xpos], labels, ha="right",
               rotation=45)

    # Set legend
    if legend:
        if len(legend) <= 4:
            cols = 1
        else:
            cols = len(legend) if len(legend) < 3 else 3
        borderpad = cols * -6
        lgd = plt.legend(loc=7, fancybox=True,
                         shadow=True, framealpha=.8, ncol=cols,
                         borderaxespad=borderpad)
    else:
        lgd = None

    # Generate table structure
    if table_header:
        table = [table_header]
    else:
        table = []
    if normalize:
        for i, lbl in enumerate(labels):
            table.append([lbl] + list(chain.from_iterable((int(x[i]), y[i])
                                      for x, y in zip(*[data_original, data]))))
    else:
        for i, lbl in enumerate(labels):
            table.append([lbl] + [x[i] for x in data])

    return fig, lgd, table