Example #1
0
def plot_classification_report(cr,
                               title='Classification report ',
                               with_avg_total=False,
                               cmap=plt.cm.Blues):

    lines = cr.split('\n')

    classes = []
    plotMat = []
    for line in lines[2:(len(lines) - 3)]:
        #print(line)
        t = line.split()
        if len(t):
            classes.append(t[0])
            v = [float(x) for x in t[1:len(t) - 1]]
            print(v)
            plotMat.append(v)

    if with_avg_total:
        aveTotal = lines[len(lines) - 1].split()
        classes.append('avg/total')
        vAveTotal = [float(x) for x in t[1:len(aveTotal) - 1]]
        plotMat.append(vAveTotal)

    plt.imshow(plotMat, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    x_tick_marks = np.arange(3)
    y_tick_marks = np.arange(len(classes))
    plt.xticks(x_tick_marks, ['precision', 'recall', 'f1-score', 'support'],
               rotation=45)
    plt.yticks(y_tick_marks, classes)
    plt.tight_layout()
    plt.ylabel('Classes')
    plt.xlabel('Measures')
Example #2
0
def plot_sets(partitioner,
              start=0,
              end=10,
              step=1,
              tam=[5, 5],
              colors=None,
              save=False,
              file=None,
              axes=None,
              data=None,
              window_size=1,
              only_lines=False,
              legend=True):

    range = np.arange(start, end, step)
    ticks = []
    if axes is None:
        fig, axes = plt.subplots(nrows=1, ncols=1, figsize=tam)

    for ct, key in enumerate(partitioner.ordered_sets):
        fset = partitioner.sets[key]
        if not only_lines:
            for t in range:
                tdisp = t - (t % window_size)
                fset.membership(0, tdisp)
                param = fset.perturbated_parameters[str(tdisp)]

                if fset.mf == Membership.trimf:
                    if t == start:
                        line = axes.plot([t, t + 1, t], param, label=fset.name)
                        fset.metadata['color'] = line[0].get_color()
                    else:
                        axes.plot([t, t + 1, t],
                                  param,
                                  c=fset.metadata['color'])

                ticks.extend(["t+" + str(t), ""])
        else:
            tmp = []
            for t in range:
                tdisp = t - (t % window_size)
                fset.membership(0, tdisp)
                param = fset.perturbated_parameters[str(tdisp)]
                tmp.append(np.polyval(param, tdisp))
            axes.plot(range, tmp, ls="--", c="blue")

    axes.set_ylabel("Universe of Discourse")
    axes.set_xlabel("Time")
    plt.xticks([k for k in range], ticks, rotation='vertical')

    if legend:
        handles0, labels0 = axes.get_legend_handles_labels()
        lgd = axes.legend(handles0, labels0, loc=2, bbox_to_anchor=(1, 1))

    if data is not None:
        axes.plot(np.arange(start, start + len(data), 1), data, c="black")

    if file is not None:
        plt.tight_layout()
        Util.show_and_save_image(fig, file, save)
Example #3
0
def musicType_plot(rap, randb, classical, indie, pop, df):
    plt.figure()

    # declaring testing data
    xs = [1, 2, 3, 4, 5]
    ys = [randb, rap, classical, pop, indie]

    # setting range
    xrng = np.arange(len(xs))
    yrng = np.arange(0, max(ys)+60, 50)

    #labeling data
    plt.xlabel('Music Type')
    plt.ylabel('Music volume')

    # spacing and declare bar chart
    plt.bar(xrng, ys, 0.45, align="center") 


    # labeling
    plt.xticks(xrng, ["randb", "rap", "classical", "pop", "indie"])
    plt.yticks(yrng)

    plt.grid(True)
    plt.show()
def plot_3df(
    df, plot_title, x_axis, y_axis, plot, save
):  # function for plotting high-dimension and low-dimension eigenvalues
    x1 = df[df.columns[0]]
    y1 = df[df.columns[1]]
    y2 = df[df.columns[2]]
    y3 = df[df.columns[3]]
    min1 = df[df.columns[1]].min()
    min2 = df[df.columns[2]].min()
    min3 = df[df.columns[3]].min()
    df_min = min(min1, min2, min3)
    plt.figure(figsize=(8, 8))
    plt.plot(x1, y1, color='red')
    plt.plot(x1, y2, color='blue')
    plt.plot(x1, y3, color='green')
    plt.grid(color='black', linestyle='-',
             linewidth=0.1)  # parameters for plot grid
    plt.xticks(np.arange(0,
                         max(x1) * 1.1,
                         int(max(x1) / 10)))  # adjusting the intervals to 250
    plt.yticks(np.arange(df_min * 0.9, 100, int(max(y1) / 10)))
    plt.title(plot_title).set_position([0.5, 1.05])
    plt.xlabel(x_axis)
    plt.ylabel(y_axis)
    plt.legend(loc='best')  # creating legend and placing in at the top right
    if save == 'yes':
        plt.savefig(plot_title)
    if plot == 'yes':
        plt.show()
    plt.close()
Example #5
0
def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    print(cm)

    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, cm[i, j],
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
Example #6
0
def plot_df(
    df1, df2, plot_title, x_axis, y_axis, plot, save
):  # function for plotting high-dimension and low-dimension eigenvalues
    y1 = df1[df1.columns[1]]
    x1 = df1['M']
    y2 = df2[df2.columns[1]]
    x2 = df2['M']

    plt.figure(figsize=(8, 8))
    plt.plot(x1, y1, color='red')
    plt.plot(x2, y2, color='blue')
    plt.grid(color='black', linestyle='-',
             linewidth=0.1)  # parameters for plot grid
    plt.xticks(np.arange(0,
                         max(x1) * 1.1,
                         int(max(x1) / 10)))  # adjusting the intervals to 250
    plt.yticks(np.arange(0, max(y1) * 1.1, int(max(y1) / 10)))
    plt.title(plot_title).set_position([0.5, 1.05])
    plt.xlabel(x_axis)
    plt.ylabel(y_axis)
    plt.legend(loc='best')  # creating legend and placing in at the top right
    if save == 'yes':
        plt.savefig(plot_title)
    if plot == 'yes':
        plt.show()
    plt.close()
Example #7
0
def plot_confusion_matrix(cls_pred, cls_true):
    # This is called from print_test_accuracy() below.

    # cls_pred is an array of the predicted class-number for
    # all images in the test-set.

    # Get the true classifications for the test-set.

    # Get the confusion matrix using sklearn.
    cm = confusion_matrix(y_true=cls_true,
                          y_pred=cls_pred)

    # Print the confusion matrix as text.
    print(cm)

    # Plot the confusion matrix as an image.
    plt.matshow(cm)

    # Make various adjustments to the plot.
    plt.colorbar()
    tick_marks = np.arange(labels_type)
    plt.xticks(tick_marks, range(labels_type))
    plt.yticks(tick_marks, range(labels_type))
    plt.xlabel('Predicted')
    plt.ylabel('True')

    # Ensure the plot is shown correctly with multiple plots
    # in a single Notebook cell.
    plt.show()
Example #8
0
def plot_test_image(testX, image_index, predictions_array, true_binary_labels):
    """
        testX: this is the test dataset
        image_index: index of the image that we will plot from the test dataset
        predictions_array: it is the array that contains all the predictions of the test dataset as output of model.predict(testX)
        true_binary_labels: these are the true label expressed as INTEGER values. It does not work with hot-encoding and string labels. 
    """
    single_predictions_array, true_binary_label, test_image = predictions_array, true_binary_labels[
        image_index], testX[image_index]
    plt.grid(False)
    plt.xticks([])
    plt.yticks([])

    plt.imshow(test_image, cmap=plt.cm.binary)

    predicted_binary_label = np.argmax(predictions_array)
    #print ("predicted_binary_label:", predicted_binary_label)
    #print ("true_binary_label:",true_binary_label)

    if predicted_binary_label == true_binary_label:
        color = 'blue'
    else:
        color = 'red'

    plt.xlabel("predicted: {} {:2.0f}% (true: {})".format(
        predicted_binary_label, 100 * np.max(single_predictions_array),
        true_binary_label),
               color=color)
def plot_response_time_various_X():
    dataframe = pd.DataFrame()
    index = []
    meanResponseTime = []

    for X in malus:
        index.append(f"X={X}s")

    dataframe['index'] = index
    plt.xticks([k for k in range(len(index))], [k for k in index])

    for X in malus:
        df = scalar_df_parse(f"./csv/pool_classico_vario_X/{modes[1]}{X}.csv")
        response = df[df.name == "queueLength"]
        meanResponseTime.append(response.value.mean())

    plt.plot(index, meanResponseTime, label=f"X={X}s")

    # plt.xticks(x_pos, index)
    # plt.xticks([k for k in range(len(index))], [k for k in index])
    plt.xlabel("Value of t")
    plt.ylabel("Queue length")
    plt.title(f"Comparison of various values of X")
    plt.legend(loc='best')
    # plt.savefig(f"./analysis/Experiment2/Queue Length Xvario-mfisso exponential_m{m}.png")
    plt.show()
Example #10
0
def plotConfusionMatrix(lbllist, predlist, classes, type):
    confusionMatrix = confusion_matrix(lbllist, predlist)

    # print(confusionMatrix)

    plt.imshow(confusionMatrix, interpolation="nearest", cmap=plt.cm.Blues)
    if type == 'train':
        plt.title("Confusion matrix training")
    elif type == 'test':
        plt.title("Confusion matrix testing")
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    fmt = "d"
    thresh = confusionMatrix.max() / 2.
    for i, j in itertools.product(range(confusionMatrix.shape[0]),
                                  range(confusionMatrix.shape[1])):
        plt.text(j,
                 i,
                 format(confusionMatrix[i, j], fmt),
                 horizontalalignment="center",
                 color="white" if confusionMatrix[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel("True label")
    plt.xlabel("Predicted label")
    # plt.show()
    if type == 'train':
        plt.savefig(LOG_PATH + 'Confusion matrix training.png')
    elif type == 'test':
        plt.savefig(LOG_PATH + 'Confusion matrix testing.png')
    plt.close()
def plot_response_time_variousNDL():
    dataframe = pd.DataFrame()
    index = []

    for k in number_datalink:
        index.append(f"nA={k}")

    dataframe['index'] = index

    for mode in modes:
        meanResponseTime = []
        var = mode.split("-")[0]
        var2 = mode.split("-")[1]

        for i in number_datalink:
            df = scalar_df_parse(f"csv/pool_classico_varia_NA/{mode}{i}.csv")
            response = df[df.name == "responseTime"]
            meanResponseTime.append(response.value.mean())

        dataframe[f'responseTime{mode}{i}'] = meanResponseTime

        plt.plot(meanResponseTime, ":o", label=f"{var} {var2}")

    plt.xticks([k for k in range(len(index))], [k for k in index])
    plt.xticks(rotation=25)
    plt.xlabel("Value of nA")
    plt.ylabel("Response time")
    plt.title("Comparison of various values of nA")
    plt.legend(loc='best')
    plt.savefig(
        "./analysis/variandoNDLeNA/responseTimeAlVariareDinAT=2sk=20msm=3sx=0.05s.png"
    )
    plt.show()
def plot_response_time_various_X_k():
    dataframe = pd.DataFrame()
    index = []
    error = []

    for k in interarrival_time:
        index.append(f"k={k}s")

    dataframe['index'] = index
    plt.xticks([k for k in range(len(index))], [k for k in index])

    for m in monitoring_time:
        for X in malus:
            meanResponseTime = []

            for k in interarrival_time:
                df = scalar_df_parse(
                    f"./csv/pool_classico_variano_X_k/m={m}s/{modes[0]}{k},{X}.csv"
                )
                response = df[df.name == "responseTime"]
                meanResponseTime.append(response.value.mean())

        plt.plot(index, meanResponseTime, label=f"X={X}s")

        # plt.xticks(x_pos, index)
        # plt.xticks([k for k in range(len(index))], [k for k in index])
        plt.xlabel("Value of k")
        plt.ylabel("Response time")
        plt.title(f"Comparison of various values of X, m={m}s")
        plt.legend(loc='best')
        # plt.savefig(f"./analysis/Experiment2/Queue Length Xvario-mfisso exponential_m{m}.png")
        plt.show()
def plotRetinaSpikes(retina=None, label=""):
    
    assert retina is not None, "Network is not initialised! Visualising failed."
    import matplotlib.pyplot as plt
    from matplotlib import animation
    
    print "Visualising {0} Spikes...".format(label) 

    spikes = [x.getSpikes() for x in retina]
#     print spikes
    
    sortedSpikes = sortSpikes(spikes)
#     print sortedSpikes
    
    framesOfSpikes = generateFrames(sortedSpikes)
#     print framesOfSpikes
    
    x = range(0, dimensionRetinaX)
    y = range(0, dimensionRetinaY)
    from numpy import meshgrid
    rows, pixels = meshgrid(x,y)
    
    fig = plt.figure()
    
    initialData = createInitialisingData()
    
    imNet = plt.imshow(initialData, cmap='green', interpolation='none', origin='upper')
    
    plt.xticks(range(0, dimensionRetinaX)) 
    plt.yticks(range(0, dimensionRetinaY))
    args = (framesOfSpikes, imNet)
    anim = animation.FuncAnimation(fig, animate, fargs=args, frames=int(simulationTime)*10, interval=30)
          
    plt.show()
def plotColorCodedNetworkSpikes(network):
    assert network is not None, "Network is not initialised! Visualising failed."
    import matplotlib as plt
    from NetworkBuilder import sameDisparityInd
    
    cellsOutSortedByDisp = []
    spikes = []
    for disp in range(0, maxDisparity+1):
        cellsOutSortedByDisp.append([network[x][2] for x in sameDisparityInd[disp]])
        spikes.append([x.getSpikes() for x in cellsOutSortedByDisp[disp]])
    
    sortedSpikes = sortSpikesByColor(spikes)
    print sortedSpikes
    framesOfSpikes = generateColoredFrames(sortedSpikes)
    print framesOfSpikes
    
    fig = plt.figure()
    
    initialData = createInitialisingDataColoredPlot()
    
    imNet = plt.imshow(initialData[0], c=initialData[1], cmap=plt.cm.coolwarm, interpolation='none', origin='upper')
    
    plt.xticks(range(0, dimensionRetinaX)) 
    plt.yticks(range(0, dimensionRetinaY))
    plt.title("Disparity Map {0}".format(disparity))
    args = (framesOfSpikes, imNet)
    anim = animation.FuncAnimation(fig, animate, fargs=args, frames=int(simulationTime)*10, interval=30)
          
    plt.show()
def print_save_all_mean_faces(x_class_mean, global_mean, show, save):
    rows = 4
    cols = 14
    index = 1
    font_size = 10
    plt.figure(figsize=(20, 10))
    plt.subplot(rows, cols,
                index), plt.imshow(np.reshape(global_mean, (46, 56)).T,
                                   cmap='gist_gray')
    title = str("Global Mean")
    plt.title(title, fontsize=font_size).set_position([0.5, 0.95]), plt.xticks(
        []), plt.yticks([])
    index = index + 1
    for i in range(0, x_class_mean.shape[1]):
        title = str("Class Mean " + str(i + 1))
        plt.subplot(rows, cols,
                    index), plt.imshow(np.reshape(x_class_mean[:, i],
                                                  (46, 56)).T,
                                       cmap='gist_gray')
        plt.title(title, fontsize=font_size).set_position(
            [0.5, 0.95]), plt.xticks([]), plt.yticks([])
        index = index + 1
    if show == 'yes':
        plt.show()
    if save == 'yes':
        plt.savefig('Global and Class Mean')
    plt.close()
def chartData(data, keyword):
    #Takes input of the results of the fts search and the phrase that was searched for
    #and creates bar chart of occurences by book for the phrase
    from matplotlib import pyplot as plt
    import numpy as np
    import math
    
    data = sorted(data, key=lambda x: x[1], reverse=True)
    info = []#number of occurences 
    books = []#list of books
    for d in data:
        info.append(d[1])
        b = d[0]
        books.append(b[b.find('LIBER'):])#Use only book number for label since name is the same for all books
    
    #create chart
    plt.close()
    fig = plt.figure()
    width = 0.4
    ind = np.arange(len(books))
    plt.bar(ind, info, width=width)
    plt.xticks(ind + width/2., books)
    plt.yticks(np.arange(0,max(info)*2,math.ceil(max(info)/5)))
    plt.ylabel('Number of Occurences')
    plt.xlabel('Books')
    plt.title('Occurences of "' + keyword + '" by book in Curtius Rufus (Latin)')
    fig.autofmt_xdate()
    plt.show(block=False)#display plot, and continue with program
Example #17
0
def plot_confusion_matrix(cm,
                          classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print("Confusion Matrix, without normalization")
    print(cm)
    #imshow displays data as an image on a 2d master
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    #returns evenly spaced values with a given inteerval
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)
    fmt = '.2f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j,
                 i,
                 format(cm[i, j], fmt),
                 horizontalalignment='center',
                 color='white' if cm[i, j] > thresh else "black")
    plt.tight_layout()
    plt.ylabel('True Label')
    plt.xlabel('Predicted Label')
Example #18
0
def plot_feature_importance(estimator=None, col_names=None):
    '''
    Plots the feature importance from a trained scikit learn estimator
    as a bar chart.

    Parameters:
    -----------
        estimator: scikit  learn estimator.

            Model that has been fit and contains the feature_importance_ attribute.

        col_names: list

            The names of the columns. Must map unto feature importance array.

    Returns:
    --------
        Matplotlib figure showing feature importances
    '''
    if estimator is None:
        raise ValueError("estimator: Expecting an estimator that implements the fit api, got None")
    if col_names is None:
        raise ValueError("col_names: Expecting a list of column names, got 'None'")
    
    if len(col_names) != len(estimator.feature_importances_):
        raise ValueError("col_names: Lenght of col_names must match lenght of feature importances")

    imps = estimator.feature_importances_
    feats_imp = pd.DataFrame({"features": col_names, "importance": imps}).sort_values(by='importance', ascending=False)
    sns.barplot(x='features', y='importance', data=feats_imp)
    plt.xticks(rotation=90)
    plt.title("Feature importance plot")
    plt.show()
Example #19
0
def plot_sleep(label, pred, file_time, kfold, name):
    x = range(0, len(label))
    y = np.arange(5)
    y_stage = ["W", "REM", "N1", "N2", "N3"]
    plt.figure(figsize=(24, 8))
    plt.ylabel("Sleep Stage")
    plt.xlabel("Sleep Time")
    time_choice = np.array([
        s.decode('UTF-8')
        for s in file_time[0:len(file_time):int(len(file_time) / 10)]
    ])
    plt.xticks(range(0, len(file_time), int(len(file_time) / 10)),
               time_choice)  ##为了将坐标刻度设为字
    plt.yticks(y, y_stage)  ##为了将坐标刻度设为字
    # plot中参数的含义分别是横轴值,纵轴值,线的形状,颜色,透明度,线的宽度和标签
    plt.plot(x,
             pred,
             'r-',
             color='blue',
             alpha=1,
             linewidth=1,
             label='predict')
    plt.plot(x, label, 'r-', color='red', alpha=1, linewidth=1, label='label')
    plt.legend(loc='best')
    plt.savefig(sleepPicture_path + str(kfold) + "sdt" + str(name) +
                ".svg")  ##保存睡眠模型图文件
    plt.close()
def plot_confusion_matrix(cm, classes, title='混淆矩阵', cmap=plt.cm.Greens):
    # imshow() 表示绘制并显示二维图 有18个参数
    # 参数1 X 混淆矩阵中显示的数值 二维数组
    # 参数2 cmap 颜色 plt.cm.Blues表示蓝色 plt.cm.Reds表示红色 plt.cm.Greens表示绿色
    # 参数5 interpolation 插值法 一般有如下值
    #     nearest 最近邻插值法
    #     bilinear 双线性插值法
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    plt.imshow(cm, cmap=cmap, interpolation="nearest")
    plt.title(title)  # 标题
    plt.colorbar()  # 显示颜色的进度条
    tick_marks = np.arange(2)  # [0 1]
    plt.xticks(tick_marks, classes)  # 对x轴上分类进行标记
    plt.yticks(tick_marks, classes)  # 对y轴上分类进行标记

    thresh = np.mean(cm)
    for i in range(2):
        for j in range(2):
            plt.text(i,
                     j,
                     cm[j][i],
                     horizontalalignment='center',
                     color='white' if cm[i][j] >= thresh else 'black')

    plt.xlabel('预测值')
    plt.ylabel('真实值')
Example #21
0
def plot_confusion_matrix(cm,
                          classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues,
                          filename='viz\\confusion_matrix.png'):
    plt.figure()
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]

    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j,
                 i,
                 cm[i, j],
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.savefig(filename)
def plot_confusion_matrix(confusion_matrix,
                          class_labels,
                          normalize=False,
                          title='Confusion Matrix',
                          cmap=plt.cm.Blues):
    """ Code courtesy of Abinav Sagar: https://towardsdatascience.com/convolutional-neural-network-for-breast-cancer-classification-52f1213dcc9 """

    if normalize:
        confusion_matrix = confusion_matrix.astype(
            'float') / confusion_matrix.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    print(confusion_matrix)

    plt.imshow(confusion_matrix, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(class_labels))
    plt.xticks(tick_marks, class_labels, rotation=55)
    plt.yticks(tick_marks, class_labels)
    fmt = '.2f' if normalize else 'd'
    thresh = confusion_matrix.max() / 2.
    for i, j in itertools.product(range(confusion_matrix.shape[0]),
                                  range(confusion_matrix.shape[1])):
        plt.text(j,
                 i,
                 format(confusion_matrix[i, j], fmt),
                 horizontalalignment="center",
                 color="white" if confusion_matrix[i, j] > thresh else "black")

    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.tight_layout()
Example #23
0
def silhouette():
    if not os.path.exists("Stardust_results"):
        print(
            "The directory structure Stardust_results doest not exist. Please run run_stardust first"
        )
        sys.exit()
    if not os.path.exists("Stardust_results/analysis"):
        os.mkdir("Stardust_results/analysis")
    output_path = "Stardust_results/analysis/"
    from sklearn.metrics import silhouette_samples, silhouette_score
    data_df = pd.read_csv(
        'Stardust_results/visualization_output/3_pass/data.csv',
        delimiter=",",
        index_col=False)
    data_df.set_index('data', inplace=True)
    silhouette_avg = silhouette_score(data_df[['x', 'y']], data_df['cluster'])
    sample_silhouette_values = silhouette_samples(data_df[['x', 'y']],
                                                  data_df['cluster'])
    print("silhouette score ", silhouette_avg)

    y_lower = 10
    import matplotlib.cm as cm
    fig = plt.figure(figsize=(4, 7))
    n_clusters = len(list(data_df['cluster'].unique()))
    for i in range(n_clusters):
        # Aggregate the silhouette scores for samples belonging to
        # cluster i, and sort them
        ith_cluster_silhouette_values = \
            sample_silhouette_values[data_df['cluster'] == i]

        ith_cluster_silhouette_values.sort()

        size_cluster_i = ith_cluster_silhouette_values.shape[0]
        y_upper = y_lower + size_cluster_i

        color = cm.nipy_spectral(float(i) / n_clusters)
        plt.fill_betweenx(np.arange(y_lower, y_upper),
                          0,
                          ith_cluster_silhouette_values,
                          facecolor=color,
                          edgecolor=color,
                          alpha=0.7)

        # Label the silhouette plots with their cluster numbers at the middle
        plt.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))

        # Compute the new y_lower for next plot
        y_lower = y_upper + 10  # 10 for the 0 samples

    plt.title("The silhouette plot for the various clusters.")
    plt.xlabel("silhouette coefficient", fontsize=20)
    plt.ylabel("Cluster label", fontsize=20)
    plt.axvline(x=silhouette_avg, color="red", linestyle="--")

    plt.yticks([])  # Clear the yaxis labels / ticks
    plt.xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1])
    sns.despine(bottom=False, left=False)
    fig.savefig(output_path + "/silhouette.pdf", bbox_inches='tight', dpi=600)
    fig.savefig(output_path + "/silhouette.png", bbox_inches='tight', dpi=600)
Example #24
0
def plot_results(predicted, sp500, random25, test_months):
             technical = ’Cumulative Returns Comparison\n' + str(mom_range) + '-momentum'
             plt.title(technical,fontsize=18)
             plt.xlabel(’Test Months’,fontsize=18)
             plt.ylabel(’$\prod(1+r)$’,fontsize=20)
             xval = range(0,len(test_months))
             plt.xticks(xval,test_months,rotation=45)
             plt.plot(xval, predicted, ’rD-’,label=’Predicted’)
Example #25
0
 def fnctn(a,c):
     df2 = pd.DataFrame(data.groupby(a)[c].count())
     df2=df2.astype(float)
     plot1 = plt.plot(df2.index,df2[c])
     plt.xticks(fontsize=10, rotation=30)
     plt.savefig("./static/q18.jpg")
     plt.show()
     plt.show()
def plot_line(x, y, y_hat, line_color='blue'):
    # Plot outputs
    plt.scatter(x, y, color='black')
    plt.plot(x, y_hat, color=line_color, linewidth=3)
    plt.xticks(())
    plt.yticks(())

    plt.show()
Example #27
0
def char_positive():
    x_axis = Category
    y_axis = statistic_positive()
    y_pos = np.arange(len(y_axis))
    plt.figure(figsize=(10, 5))
    plt.bar(y_pos, y_axis)
    plt.xticks(y_pos, x_axis)
    plt.title('What categories we choose the most')
    plt.show()
Example #28
0
def confused_pic(class_indices, y, prediction, decision_matrix,testData):
   wrong_classify = y != prediction
   index_wrong = np.argwhere(wrong_classify == True)  # indices for misclassified example
   index_wrong= index_wrong[:, 0]
   y_wrong = y[wrong_classify]  # belonged class for the misclassified
   prediction_wrong = prediction[wrong_classify]  # the predicted class for the misclassified examples
   wrong_decision_matrix = decision_matrix[wrong_classify, :]  # only the rows that misclassified

   # mapping class to index -> the first class will map to 0 the second to 1 and go on...
   j = 0  # counter
   y_wrong_mapping = np.copy(y_wrong)
   prediction_wrong_mapping = np.copy(prediction_wrong)
   for i in class_indices:
       y_wrong_mapping[y_wrong_mapping == i] = j
       prediction_wrong_mapping[prediction_wrong_mapping == i] = j
       j = j + 1
   y_wrong_mapping = y_wrong_mapping.astype(int)
   prediction_wrong_mapping = prediction_wrong_mapping.astype(int)

   # create vector with the mistake value to the correct class from the predicted class
   mistakes_values = np.asarray([])
   for i in range(y_wrong.shape[0]):  # loop over each row of wrong_decision_matrix, all the misclassified
       mistake = wrong_decision_matrix[i, y_wrong_mapping[i]] - wrong_decision_matrix[i, prediction_wrong_mapping[i]]
       mistakes_values = np.append(mistakes_values, mistake)

   # combine mistake, belonged class, original index to one matrix
   combine = np.asarray([mistakes_values, y_wrong, index_wrong])
   combine = np.transpose(combine)
   # sorting the combined matrix by the mistake
   combine = combine[combine[:, 0].argsort()[::-1]]
   # sorting the combined matrix by the mistake and then by class
   combine = combine[combine[:, 1].argsort()]

   # find 2 largest mistakes
   example_idx = np.asarray([])
   belonged_class = np.asarray([])
   for i in range(combine.shape[0]):
       if example_idx.shape[0] >= 2:
           if belonged_class[-1] == combine[i, 1] and belonged_class[-2] == combine[i, 1]:
               continue
           else:
               example_idx = np.append(example_idx, combine[i, 2])
               belonged_class = np.append(belonged_class, combine[i, 1])
       else:
           example_idx = np.append(example_idx, combine[i, 2])
           belonged_class = np.append(belonged_class, combine[i, 1])

   # show the images
   for i in range(example_idx.shape[0]):
       cv2.imshow('',testData[example_idx.astype(int)][i])
       cv2.waitKey()
       cv2.destroyAllWindows()
       plt.imshow(testData[example_idx.astype(int)][i], cmap = 'gray')
       plt.xticks([]), plt.yticks([])  # to hide tick values on X and Y axis
       plt.show()
   return
Example #29
0
 def fnctn(a,c):
     #os.remove(filename)
     df2 = pd.DataFrame(data.groupby(a)[c].sum())
     df2=df2.astype(float)
     plot1 = plt.plot(df2.index,df2[c])
     plt.xticks(fontsize=10, rotation=30)
     #plt.set_size_inches(8, 6)
     plt.savefig("./static/q18.jpg")
     plt.close()
     plt.show()
Example #30
0
def plot_gallery(images, titles, h, w, n_row=3, n_col=4):
    """Helper function to plot a gallery of portraits"""
    pl.figure(figsize=(1.8 * n_col, 2.4 * n_row))
    pl.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35)
    for i in range(n_row * n_col):
        pl.subplot(n_row, n_col, i + 1)
        pl.imshow(images[i].reshape((h, w)), cmap=pl.cm.gray)
        pl.title(titles[i], size=12)
        pl.xticks(())
        pl.yticks(())
Example #31
0
def plot_sample(x, title="", width=28, fName=None):
    fig = plt.figure()
    sample = x.reshape(width, width)
    # interploation can be 'nearest' to put grid at the center the pixels
    plt.imshow(sample, interpolation='None', cmap='gray')
    plt.title(title)
    plt.xticks([])
    plt.yticks([])
    if fName != None:
        savefig(fName, bbox_inches='tight')
    plt.show()
Example #32
0
def cm_plot(original_label, predict_label, kunm, pic=None):

    prec_score = precision_score(original_label, predict_label, average=None)
    recall = recall_score(original_label, predict_label, average=None)
    f1 = f1_score(original_label, predict_label, average=None)
    cm = confusion_matrix(original_label, predict_label)
    cm_new = np.empty(shape=[5, 5])
    for x in range(5):
        t = cm.sum(axis=1)[x]
        for y in range(5):
            cm_new[x][y] = round(cm[x][y] / t * 100, 2)
    plt.figure()
    plt.matshow(cm_new, cmap=plt.cm.Blues)
    plt.colorbar()
    x_numbers = []
    y_numbers = []
    cm_percent = []
    for x in range(5):
        y_numbers.append(cm.sum(axis=1)[x])
        x_numbers.append(cm.sum(axis=0)[x])
        for y in range(5):
            percent = format(cm_new[x, y] * 100 / cm_new.sum(axis=1)[x], ".2f")
            cm_percent.append(str(percent))
            plt.annotate(format(cm_new[x, y] * 100 / cm_new.sum(axis=1)[x],
                                ".2f"),
                         xy=(y, x),
                         horizontalalignment='center',
                         verticalalignment='center',
                         fontsize=10)
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.title('confusion matrix')

    y_stage = [
        "W\n(" + str(y_numbers[0]) + ")", "N1\n(" + str(y_numbers[1]) + ")",
        "N2\n(" + str(y_numbers[2]) + ")", "N3\n(" + str(y_numbers[3]) + ")",
        "REM\n(" + str(y_numbers[4]) + ")"
    ]
    x_stage = [
        "W\n(" + str(x_numbers[0]) + ")", "N1\n(" + str(x_numbers[1]) + ")",
        "N2\n(" + str(x_numbers[2]) + ")", "N3\n(" + str(x_numbers[3]) + ")",
        "REM\n(" + str(x_numbers[4]) + ")"
    ]
    y = [0, 1, 2, 3, 4]
    plt.xticks(y, x_stage)
    plt.yticks(y, y_stage)
    #sns.heatmap(cm_percent, fmt='g', cmap="Blues", annot=True, cbar=False, xticklabels=x_stage, yticklabels=y_stage)  # 画热力图,annot=True 代表 在图上显示 对应的值, fmt 属性 代表输出值的格式,cbar=False, 不显示 热力棒

    plt.savefig(savepath + "matrix" + str(kunm) + ".svg")
    #plt.show()
    plt.show()
    plt.close()
    # plt.savefig("/home/data_new/zhangyongqing/flx/pythoncode/"+str(knum)+"matrix.jpg")
    return kappa(cm), classification_report(original_label, predict_label)
Example #33
0
def viz_losses(filename, losses):
  if '.' not in filename: filename += '.png'

  x = history['epoch']
  legend = losses.keys

  for v in losses.values: plt.plot(np.arange(len(v)) + 1, v, marker='.')

  plt.title('Loss over epochs')
  plt.xlabel('Epochs')
  plt.xticks(history['epoch'], history['epoch'])
  plt.legend(legend, loc = 'upper right')
  plt.savefig(filename)
def plot_confusion_matrix(cm, labels, title='Confusion matrix', cmap=plt.cm.Blues, save=False):
    plt.figure()
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(labels))
    plt.xticks(tick_marks, labels, rotation=45)
    plt.yticks(tick_marks, labels)
    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.show()
    if save:
        plt.savefig(save)
Example #35
0
def stacked_bar_plot_single_sample(data, show_value, output):
    """
    Plot a single taxonomic data set.
    Require matplotlib and numpy
    :param data: The data set to plot
    :param show_value: Bool. True if you want to show values over each bar
    :return: Nothing but will open a plot window.
    """
    number_of_sample = len(data)
    taxon_name = []
    taxon_value = []
    for taxon in data:
        taxon_name.append(taxon)
        taxon_value.append(data[taxon])
    ind = np.arange(number_of_sample)
    width = 0.75    # could be optimized
    plot = ppl.bar(ind, taxon_value, width, color='g')
    ppl.ylabel("Proportion")
    ppl.title("Taxonomic repartition")
    locs, labels = mpl.xticks(ind+width/2., taxon_name)
    ppl.setp(labels, rotation=90)
    ppl.yticks(np.arange(0, max(taxon_value), max(taxon_value)/10))
    if mpl.__version__ >="1.3.1":
        ppl.tight_layout()
    if show_value:
        for pos, value in zip(ind, taxon_value):
            ppl.text(pos + 0.5*width, value, str(value)[0:6], ha='center', va='bottom', rotation=90)
    if output is None:
        ppl.show()
    else:
        ppl.savefig(output)
Example #36
0
def plot_confusion_matrix(cm, classes,
    normalize=False, title='Confusion matrix',
    cmap=plt.cm.Blues, filename='viz\\confusion_matrix.png'):
  plt.figure()
  plt.imshow(cm, interpolation='nearest', cmap=cmap)
  plt.title(title)
  plt.colorbar()
  tick_marks = np.arange(len(classes))
  plt.xticks(tick_marks, classes, rotation=45)
  plt.yticks(tick_marks, classes)

  if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]

  thresh = cm.max() / 2.
  for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
      plt.text(j, i, cm[i, j], horizontalalignment="center", color="white" if cm[i, j] > thresh else "black")

  plt.tight_layout()
  plt.ylabel('True label')
  plt.xlabel('Predicted label')
  plt.savefig(filename)
def plotDisparityMap(network=None, disparity=0):
    
    assert network is not None, "Network is not initialised! Visualising failed."
    assert disparity >= 0 and disparity <= maxDisparity, "No such disparity map in the network."
    import matplotlib.pyplot as plt
    from matplotlib import animation
    from NetworkBuilder import sameDisparityInd
    
    print "Visualising results for disparity value {0}...".format(disparity) 
    
    cellsOut = [network[x][2] for x in sameDisparityInd[disparity]]

    spikes = [x.getSpikes() for x in cellsOut]
#     print spikes
    
    sortedSpikes = sortSpikes(spikes)
#     print sortedSpikes
    
    framesOfSpikes = generateFrames(sortedSpikes)
#     print framesOfSpikes
    
    x = range(0, dimensionRetinaX)
    y = range(0, dimensionRetinaY)
    from numpy import meshgrid
    rows, pixels = meshgrid(x,y)
    
    fig = plt.figure()
    
    initialData = createInitialisingData()
#     print initialData
    imNet = plt.imshow(initialData, cmap='gray', interpolation='none', origin='upper')
    
    plt.xticks(range(0, dimensionRetinaX)) 
    plt.yticks(range(0, dimensionRetinaY))
    plt.title("Disparity Map {0}".format(disparity))
    args = (framesOfSpikes, imNet)
    anim = animation.FuncAnimation(fig, animate, fargs=args, frames=int(simulationTime)*10, interval=30)
          
    plt.show()
    counts = lines.map(lambda date: date.split('\t')[2]) \
                  .map(lambda month:month[0:7])  \
		  .map(lambda x: (x,1))  \
                  .reduceByKey(add)
    month_sorted = counts.sortBy(lambda x: x[0]).collect()


    ## YOUR CODE GOES HERE
    ## PUT YOUR RESULTS IN counts


    with open("wikipedia_by_month.txt","w") as fout:
        for (date, count) in month_sorted:
            fout.write("{}\t{}\n".format(date,count))
    
    ## 
    ## Terminate the Spark job
    ##
    #############
    # plot
    #############
    data = pandas.read_csv("wikipedia_by_month.txt", sep='\t', header = None, names=['date', 'count'])
    fig = pyplot.figure()
    index = np.arange(len(data[0]))
    pyplot.bar(index, data['count'], width = width)
    fig.autofmt_xdate()
    plt.xticks(index, data['date'], rotation = 'vertical')
    plt.savefig("figure.pdf")
    
    sc.stop()
Example #39
0
plt.loglog(xr05/10,Nr05,'d',markersize=8,color=c1,label=r'$\sigma=0.05h_0$')
plt.loglog(xr10/10,Nr10,'o',markersize=8,color=c1,label=r'$\sigma=0.10h_0$')
plt.loglog(xr20/10,Nr20,'s',markersize=8,color=c1,label=r'$\sigma=0.20h_0$')
plt.loglog(xr25/10,Nr25,'^',markersize=8,color=c1,label=r'$\sigma=0.25h_0$')
plt.loglog(xr30/10,Nr30,'v',markersize=8,color=c1,label=r'$\sigma=0.30h_0$')
plt.loglog(xr40/10,Nr40,'<',markersize=8,color=c1,label=r'$\sigma=0.40h_0$')
plt.loglog(xr50/10,Nr50,'>',markersize=8,color=c1,label=r'$\sigma=0.50h_0$')
plt.loglog(xg2/10,Ng2,'d',markersize=8,color=c2,label=r'$\gamma=0.2l_p$')
plt.loglog(xg4/10,Ng4,'o',markersize=8,color=c2,label=r'$\gamma=0.4l_p$')
plt.loglog(xg10/10,Ng10,'s',markersize=8,color=c2,label=r'$\gamma=l_p$')
plt.loglog(xg20/10,Ng20,'^',markersize=8,color=c2,label=r'$\gamma=2l_p$')
plt.loglog(xg40/10,Ng40,'v',markersize=8,color=c2,label=r'$\gamma=4l_p$')
plt.loglog(xg100/10,Ng100,'<',markersize=8,color=c2,label=r'$\gamma=10l_p$')
plt.loglog(xg1000/10,Ng1000,'>',markersize=8,color=c2,label=r'$\gamma=100l_p$')
plt.legend(loc='upper right',prop={'size':17})
plt.xticks((10**0, 10**1, 10**2), (r'$10^{0}$', r'$10^{1}$', r'$10^{2}$'), fontsize=24)
plt.yticks((10**0, 10**1, 10**2, 10**3), (r'$10^{0}$', r'$10^{1}$', r'$10^{2}$', r'$10^{3}$'), fontsize=24)
ax = plt.gca()
ax.tick_params(axis='both',reset=False,which='both',length=10,width=2,direction='bottom')
ax.yaxis.set_tick_params(length=20,width=2,direction='bottom')
ax.xaxis.set_tick_params(length=20,width=2,direction='bottom')
ax.tick_params(axis='both',reset=False,which='minor',length=10,width=1,direction='bottom')
ax.xaxis.set_tick_params(length=20,width=1,direction='bottom')
ax.yaxis.set_tick_params(length=20,width=1,direction='bottom')
plt.annotate(r'$N_{LSA}=173$', fontsize=24, xy=(6, 173), xytext=(9,173), horizontalalignment='left', verticalalignment='center', arrowprops=dict(facecolor='black', shrink=0.05))
plt.xlabel(r'$\mathit{L_w/l_p}$',fontsize=24)
plt.ylabel(r'$\mathit{N(L_{w})}$',fontsize=24)
l1 = [3,80]
l2 = [80,3]
scatter(l1,l2)
plot(l1,l2,color='black',linewidth=4)
    ## Run WordCount on Spark
    ##

    sc     = SparkContext( appName="Wikipedia Count" )
    lines = sc.textFile(infile)
<<<<<<< HEAD
    
    counts = lines.map(lambda line:line.split('\t')[2]).map(lambda x:(x[0:7],1)).reduceByKey(add)
    counts_by_month = counts.sortBy(lambda x: x[0])

    length = counts_by_month.count()
    x = range(0, length)
    lables = counts_by_month.map(lambda x : x[0]).collect()
    y = counts_by_month.map(lambda x : x[1]).collect()
    plt.plot(np.array(x),np.array(y))
    plt.xticks(x,lables,rotation = 'vertical')
    plt.savefig("counts_by_month.pdf")

    counts_by_month.collect()
=======
    counts = lines.map()
    
>>>>>>> 65a15a888eef7c1f146383d61b9f57882504af41
    ## YOUR CODE GOES HERE
    ## PUT YOUR RESULTS IN counts


    """with open("wikipedia_by_month.txt","w") as fout:
        for (date, count) in counts_by_month:
            fout.write("{}\t{}\n".format(date,count))"""    
Example #41
0
diabetes_y_train = diabetes.target[:-20]
diabetes_y_test  = diabetes.target[-20:]


regr = linear_model.LinearRegression()
regr.fit(diabetes_X_train, diabetes_y_train)

# >> LinearRegression(copy_X=True, fit_intercept=True, normalize=False)
print regr.coef_

# The mean square error
np.mean((regr.predict(diabetes_X_test)-diabetes_y_test)**2)

# Explained variance score: 1 is perfect prediction
# and 0 means that there is no linear relationship
# between X and Y.
regr.score(diabetes_X_test, diabetes_y_test) 

# Plot results

pl.clf()          # Clear plots

pl.plot(diabetes_X_test, regr.fit(diabetes_X_train, diabetes_y_train));

pl.title('Linear regression of sample diabetes data\n'
         'Centroids are marked with white cross')
pl.xlim(x_min, x_max)
pl.ylim(y_min, y_max)
pl.xticks(())
pl.yticks(())
pl.show()
Example #42
0
import matplotlib as plt
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import datetime    


Data = pd.read_csv("wikipedia_by_month.txt", sep='\t', header = None, names=['Date', 'Count'])

fig = plt.figure()
ind = np.arange(len(Data['Date']))
plt.bar(ind, Data['Count'])
fig.autofmt_xdate()
plt.xticks(ind, Data['Date'], rotation = 'vertical')
plt.savefig("figure.pdf")
fig.set_size_inches(16, 10)

count_by_occupation = user_fields.map(lambda fields: (fields[3], 1)).reduceByKey(lambda x, y: x + y).collect()
x_axis1 = np.array([c[0] for c in count_by_occupation])
y_axis1 = np.array([c[1] for c in count_by_occupation])

x_axis = x_axis1[np.argsort(y_axis1)]
y_axis = y_axis1[np.argsort(y_axis1)]

pos = np.arange(len(x_axis))
width = 1.0
ax = plt.axes()
ax.set_xticks(pos + (width / 2))
ax.set_xticklabels(x_axis)
plt.bar(pos, y_axis, width, color='lightblue')
plt.xticks(rotation=30)
fig = plt.pyplot.gcf()
fig.set_size_inches(16, 10)

count_by_occupation2 = user_fields.map(lambda fields: fields[3]).countByValue()
print "Map-reduce approach:"
print dict(count_by_occupation2)
print ""
print "countByValue approach:"
print dict(count_by_occupation)

'''
    explore movie data
'''

movie_data = sc.textFile("../../../../resource/u.item")
Example #44
0
def create_figure_surface(figid, aspect, xx, yy, cmin, cmax, levels, slices, v3d):
    ''' creates a plot of the surface of a tracer data
    Parameters
    ----------
    figid : int  
            id of figure
    aspect: float
            aspect ratio of figure
    xx    : array 
            scale of x axis
    yy    : array 
            scale of y axis     
    cmin,cmax : array
                minimum and maxminm of the color range
    levels : array
            range of contourlines
    slices : array
            location of slices
    v3d    : vector data in geometry format
    Returns
    -------
    plot :  of surface data
    '''
    # prepare matplotlib
    import matplotlib
    matplotlib.rc("font",**{"family":"sans-serif"})
    matplotlib.rc("text", usetex=True)
    #matplotlib.use("PDF")
    import matplotlib.pyplot as plt
    # basemap
    from mpl_toolkits.basemap import Basemap
    # numpy
    import numpy as np

    # data
    vv = v3d[0,:,:,0]
    # shift
    vv = np.roll(vv, 64, axis=1)

    # plot surface
    plt.figure(figid)
    # colormap
    cmap = plt.cm.bone_r
    # contour fill
    p1 = plt.contourf(xx, yy, vv, cmap=cmap, levels=levels, origin="lower")#, hold="on")
    plt.clim(cmin, cmax)
    # contour lines
    p2 = plt.contour(xx, yy, vv, levels=levels, linewidths = (1,), colors="k")#, hold="on")
    plt.clabel(p2, fmt = "%2.1f", colors = "k", fontsize = 14)
    #plt.colorbar(p2,shrink=0.8, extend='both')
    # slices
    #s1 = xx[np.mod(slices[0]+64, 128)]
    #s2 = xx[np.mod(slices[1]+64, 128)]
    #s3 = xx[np.mod(slices[2]+64, 128)]
#    print s1, s2, s3
    #plt.vlines([s1, s2, s3], -90, 90, color='k', linestyles='--')
    # set aspect ratio of axes
    plt.gca().set_aspect(aspect)

    # basemap
    m = Basemap(projection="cyl")
    m.drawcoastlines(linewidth = 0.5)

    # xticks
    plt.xticks(range(-180, 181, 45), range(-180, 181, 45))
    plt.xlim([-180, 180])
    plt.xlabel("Longitude [degrees]", labelpad=8)
    # yticks
    plt.yticks(range(-90, 91, 30), range(-90, 91, 30))
    plt.ylim([-90, 90])
    plt.ylabel("Latitude [degrees]")


    # write to file
    plt.savefig("solution-surface", bbox_inches="tight")
    plt.show()
audio = MonoLoader(filename = filename, sampleRate=sampleRate)()
audio = EqualLoudness()(audio)
pitch, confidence = run_predominant_melody(audio)


n_frames = len(pitch)
print "number of frames:", n_frames

# Visualize output pitch values
fig = plt.figure()
plot(range(n_frames), pitch, 'b')
n_ticks = 10
xtick_locs = [i * (n_frames / 10.0) for i in range(n_ticks)]
xtick_lbls = [i * (n_frames / 10.0) * hopSize / sampleRate for i in range(n_ticks)]
xtick_lbls = ["%.2f" % round(x,2) for x in xtick_lbls]
plt.xticks(xtick_locs, xtick_lbls)
ax = fig.add_subplot(111)
ax.set_xlabel('Time (s)')
ax.set_ylabel('Pitch (Hz)')
suptitle("Predominant melody pitch")

# Visualize output pitch confidence
fig = plt.figure()
plot(range(n_frames), confidence, 'b')
n_ticks = 10
xtick_locs = [i * (n_frames / 10.0) for i in range(n_ticks)]
xtick_lbls = [i * (n_frames / 10.0) * hopSize / sampleRate for i in range(n_ticks)]
xtick_lbls = ["%.2f" % round(x,2) for x in xtick_lbls]
plt.xticks(xtick_locs, xtick_lbls)
ax = fig.add_subplot(111)
ax.set_xlabel('Time (s)')
implot = plt.imshow(im)

x = (df['west'] - df['west'].min())*477/(df['east'].max() - df['west'].min())
y = 798-(df['north'] - df['south'].min())*798/(df['north'].max() - df['south'].min())
s = df['currentspeed'] / df['currentspeed'].max()
plt.scatter(x,y,c=s,linewidth=0,s=1000,alpha=0.1)

#x0 = (df.ix[0]['west'] - df['west'].min())*477/(df['east'].max() - df['west'].min())
#y0 = 798-(df.ix[0]['north'] - df['south'].min())*798/(df['north'].max() - df['south'].min())
#plt.scatter(x0,y0,c='r',s=2000)
#x0 = (df.ix[0]['east'] - df['west'].min())*477/(df['east'].max() - df['west'].min())
#y0 = 798-(df.ix[0]['south'] - df['south'].min())*798/(df['north'].max() - df['south'].min())
#plt.scatter(x0,y0,c='r',s=2000)
plt.xlim(0,477)
plt.ylim(798,0)
plt.xticks([])
plt.yticks([])
#plt.plot([df['west'],df['west'],df['east'],df['east'],df['west']],[df['south'],df['north'],df['north'],df['south'],df['south']],linewidth=20,alpha=0.2)

# <codecell>

plt.figure(figsize=(15,15))

patches = []
verts = [(df['west'],df['south']),
    (df['west'],df['north']),
    (df['east'],df['north']),
    (df['east'],df['south']),
    (df['west'],df['south'])]

codes = [Path.MOVETO,