def plot_confusion_matrix(cm, fig, counter, num_plots, title='Confusion matrix', cmap=plt.cm.Blues):
    ax = fig.add_subplot(1, num_plots, counter+1)
    ax.imshow(cm, interpolation='nearest', cmap=cmap)
    ax.set_title(title)
    tick_marks = np.arange(len(np.unique(test_labels_df['cat'])))
    plt.set_xticks(tick_marks, np.unique(test_labels_df['cat']), rotation=45)
    plt.set_yticks(tick_marks, np.unique(test_labels_df['cat']))
    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
Exemplo n.º 2
0
def plot_boxplots(data):
    """

    :param data:
    :return:
    """
    all_data = data.values
    labels = data.columns
    plt.boxplot(all_data)
    plt.set_title('box plot')
    plt.yaxis.grid(True)
    plt.set_xticks([y + 1 for y in range(len(all_data))])
    plt.set_xlabel('feature')
    plt.set_ylabel('ylabel')
    plt.setp(xticks=[y + 1 for y in range(len(all_data))], xticklabels=labels)
    plt.show()
Exemplo n.º 3
0
def plot_2D_scores(plt,fig,filename_data_pos,filename_data_neg,filename_data_grid,filename_scores_grid,th,noice_needed=0,caption='',filename_out=None):
    if not os.path.isfile(filename_data_pos): return
    if not os.path.isfile(filename_data_neg): return
    if not os.path.isfile(filename_data_grid): return

    data = tools_IO.load_mat(filename_scores_grid, dtype=numpy.chararray, delim='\t')
    data = data[1:,:]
    grid_scores = data[:, 1:].astype('float32')

    data = tools_IO.load_mat(filename_data_grid, dtype=numpy.chararray, delim='\t')
    data_grid = data[:,1:].astype('float32')

    data = tools_IO.load_mat(filename_data_pos, dtype=numpy.chararray, delim='\t')
    l1 = (data[:, 0]).astype('float32')
    x1 = data[:,1:].astype('float32')

    data = tools_IO.load_mat(filename_data_neg, dtype=numpy.chararray, delim='\t')
    l2 = (data[:, 0]).astype('float32')
    x2 = data[:,1:].astype('float32')

    X = numpy.vstack((x1,x2))
    labels = numpy.hstack((l1, l2)).astype(int)

    X1 = X[labels >  0]
    X0 = X[labels <= 0]

    #'''
    max = numpy.max(grid_scores)
    min = numpy.min(grid_scores)
    for i in range(0,grid_scores.shape[0]):
        if(grid_scores[i]>th):
            grid_scores[i]=(grid_scores[i]-th)/(max-th)
        else:
            grid_scores[i] = (grid_scores[i] - th) / (th-min)
    #'''

    S=int(math.sqrt(grid_scores.shape[0]))
    grid_scores=numpy.reshape(grid_scores,(S,S))

    minx=numpy.min(data_grid[:, 0])
    maxx=numpy.max(data_grid[:, 0])
    miny=numpy.min(data_grid[:, 1])
    maxy=numpy.max(data_grid[:, 1])


    if noice_needed>0:
        noice1 = 0.05-0.2*numpy.random.random_sample(X1.shape)
        noice0 = 0.05-0.2*numpy.random.random_sample(X0.shape)
        X1+=noice1
        X0+=noice0

    plt.set_title(caption)

    xx, yy = numpy.meshgrid(numpy.linspace(minx, maxx, num=S), numpy.linspace(miny, maxy,num=S))

    plt.contourf(xx, yy, numpy.flip(grid_scores,0), cmap=cm.coolwarm, alpha=.8)
    #plt.imshow(grid_scores, interpolation='bicubic',cmap=cm.coolwarm,extent=[minx,maxx,miny,maxy],aspect='auto')

    plt.plot(X0[:, 0], X0[:, 1], 'ro', color='blue', alpha=0.4)
    plt.plot(X1[: ,0], X1[:, 1], 'ro' ,color='red' , alpha=0.4)
    plt.grid()
    plt.set_xticks(())
    plt.set_yticks(())
    #fig.subplots_adjust(hspace=0.001,wspace =0.001)
    if filename_out is not None:
        plt.savefig(filename_out)

    return
Exemplo n.º 4
0
Arquivo: BI.py Projeto: Manuste2m/Test
    def Plot(self):
        self.delPlot()
        listSalePlot = []
        listLabel = []
        listDate = []

        tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120),
                     (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150),
                     (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148),
                     (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199),
                     (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)]

        for i in range(len(tableau20)):
            r, g, b = tableau20[i]
            tableau20[i] = (r / 255., g / 255., b / 255.)

        if (len(self.listDimensionsPlot)) == 1 :
            listInDimensions = self.read_CSV_InDimensions(self.listHeadShow[0])
            for i in range(len(listInDimensions)):
                filename = listInDimensions[i]
                listLabel.append(filename)
                ##เพิ่ม Date ตรงนี้
                with open(""+str(self.listDatePlot[0])+str(filename)+str(self.listMeasuresPlot[0])+".csv", newline='') as f:
                    reader = csv.reader(f)
                    row1 = next(reader)
                    row2 = next(reader)
                listSalePlot.append(row2)
            listDate = row1
        elif (len(self.listDimensionsPlot)) == 0:
            for i in range(len(self.listInDimensionsPlot)):
                filename = self.listInDimensionsPlot[i]
                listLabel.append(filename)
                with open(""+str(self.listDatePlot[0])+str(filename)+str(self.listMeasuresPlot[0])+".csv", newline='') as f:
                    reader = csv.reader(f)
                    row1 = next(reader)
                    row2 = next(reader)
                listSalePlot.append(row2)
            listDate = row1
        print (listDate)
        print (listLabel)
        print (listSalePlot)

        canvasPlot = 0
        print (len(self.canvas))
        for plot in range(len(self.plotType)):
            self.canvas.append("canvas"+str(plot))
            if (self.plotType[plot]=="Plot"):
                if (len(self.listMeasuresPlot)==1) and (len(self.listDatePlot)==1):
                    f = Figure(figsize=(6, 5), dpi=80)
                    f.set_facecolor("w")
                    plt = f.add_subplot(111)
                    for i in range(len(listSalePlot)):
                        print (listSalePlot[i])
                        plt.plot(listDate,listSalePlot[i],lw=2.5,color=tableau20[i],label=listLabel[i])
                    minX = (int(min(listDate)))
                    maxX = (int(max(listDate)))
                    x = range(minX, (maxX+1))
                    plt.set_xticks(x)
                    plt.set_xticklabels(listDate)
                    plt.set_title(str(self.listMeasuresPlot[0]))
                    plt.legend(loc='upper left', bbox_to_anchor=(0, 1),ncol=2, fancybox=True, shadow=True)
                    self.canvas[plot] = FigureCanvasTkAgg(f, master=self.f2)
                    self.canvas[plot].show()
                    self.canvas[plot].get_tk_widget().place(x = 300*canvasPlot + 350, y = 10)
                    self.canvas[plot]._tkcanvas.place(x = 300*canvasPlot + 350, y = 10)

            elif (self.plotType[plot]=="Pie"):
                if (len(self.listMeasuresPlot)==1) and (len(self.listDatePlot)==1):
                    f = Figure(figsize=(6, 5), dpi=80)
                    f.set_facecolor("w")
                    plt = f.add_subplot(111)
                    plt.set_title(str(self.listMeasuresPlot[0]))
                    saleCounty = []
                    colors = []
                    for i in range(len(listSalePlot)):
                        saleCountySum = 0
                        colors.append(tableau20[i])
                        for j in range(len(listSalePlot[i])):
                            saleCountySum = saleCountySum + float(listSalePlot[i][j])
                        saleCounty.append(saleCountySum)
                    print (saleCounty)
                    plt.pie(saleCounty, labels=listLabel, colors=colors,
                                autopct='%1.1f%%', shadow=True, startangle=90)
                    plt.axis('equal')
                    self.canvas[plot] = FigureCanvasTkAgg(f, master=self.f2)
                    self.canvas[plot].show()
                    self.canvas[plot].get_tk_widget().place(x = 300*canvasPlot + 350, y = 10)
                    self.canvas[plot]._tkcanvas.place(x = 300*canvasPlot + 350, y = 10)

            elif (self.plotType[plot]=="Bar"):
                if (len(self.listMeasuresPlot)==1) and (len(self.listDatePlot)==1):
                    f = Figure(figsize=(6, 5), dpi=80)
                    f.set_facecolor("w")
                    plt = f.add_subplot(111)

                    print (len(listDate))
                    width = 0.2
                    ind = np.arange(len(listDate))

                    for i in range(len(listSalePlot)):
                        listSalePlot[i] = [float(j) for j in listSalePlot[i]]
                        plt.bar(ind+(i*width),listSalePlot[i],width,color=tableau20[i],label=listLabel[i])
                    plt.set_xticks(ind+((width/2)*(len(listSalePlot))))
                    plt.set_xticklabels(listDate)
                    plt.set_title(str(self.listMeasuresPlot[0]))
                    plt.legend(loc='upper left', bbox_to_anchor=(0, 1),ncol=2, fancybox=True, shadow=True)
                    self.canvas[plot] = FigureCanvasTkAgg(f, master=self.f2)
                    self.canvas[plot].show()
                    self.canvas[plot].get_tk_widget().place(x = 300*canvasPlot + 350, y = 10)
                    self.canvas[plot]._tkcanvas.place(x = 300*canvasPlot + 350, y = 10)
            canvasPlot = canvasPlot + 1.5
            self.plotTypeOlt.append(canvasPlot)
plt.legend
plt.show()

#Kernel Density Estimate (KDE). KDE is a fundamental data smoothing problem where inferences about 
#the population are made, based on a finite data sample. 
#It helps generate estimations of the overall distributions.

#estimations of the overall distributions
pd.plotting.scatter_matrix(retscomp, diagonal='kde', figsize=(10,10));

#heat maps to visualize the correlation ranges among the competing stocks. 
#The lighter the color, the more correlated the two stocks are
mk=plt.subplot()
plt.imshow(corr, cmap='hot', interpolation='none')
plt.colorbar()
plt.set_xticks(range(len(corr)), corr.columns)
plt.set_yticks(range(len(corr)), corr.columns)
plt.show()

#this might not show causality, and could just show the trend in the technology 
#industry rather than show how competing stocks

#Stock RETURNS n RISKS
#average of returns (Return Rate) and the standard deviation of returns (Risk).
plt.scatter(retscomp.mean(), retscomp.std())
plt.xlabel("Expected returns")
plt.ylabel("Risk")
plt.legend

for label, x, y in zip(retscomp.columns, retscomp.mean(), retscomp.std()):
    plt.annotate(
Exemplo n.º 6
0
#ax = fig.add_subplot(131)

#rects1 = ax.bar(x, stand_alone, width, label='Stand Alone')
#rects1 = ax.bar(x - width/2, stand_alone, width, color='cornflowerblue')
#rects1 = ax.bar(x,time, width)
rects1 = ax.bar(x, read, width, hatch='....', color='white', edgecolor='black')
#rects1 = ax.bar(x - width/2, stand_alone, width, label='Stand Alone')
#rects2 = ax.bar(x, collocated, width, label='Collocated')
#rects2 = ax.bar(x + width/2, collocated, width, color='orange')
#rects2 = ax.bar(x + width/2, collocated, width, label='Collocated')

# Add some text for labels, title and custom x-axis tick labels, etc.
plt.set_ylabel('Traffic in Million', fontsize=12)
plt.set_title('Read', fontsize=14)
plt.set_xticks(x)
plt.set_xticklabels(
    labels,
    fontsize=12,
)
#ax.set_xticklabels(labels, fontsize=12, rotation='vertical')
#ax.legend(loc=1, bbox_to_anchor=(0.5, 0., 0.5, 0.99))
plt.set_yticks(np.arange(0, max(read) + 2, 3))

x = np.arange(len(labels))  # the label locations

fig.subplots_adjust(wspace=.5)
plt.tight_layout()
plt.show()
fig.savefig('method-stream.png', dpi=100)
Exemplo n.º 7
0
    print('Done users matrix')

ticks = [0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0]

colours = ['r', 'g', 'b', 'y']
shapes = ['+', 'o', 'x']
print(colours)

with open('pickles/precisions_map.pickle', 'wb') as handle:
    pickle.dump(precisions_map, handle, protocol=pickle.HIGHEST_PROTOCOL)

with open('pickles/super_result.pickle', 'wb') as handle:
    pickle.dump(super_result, handle, protocol=pickle.HIGHEST_PROTOCOL)

fig = plt.figure(figsize=(10, 15))
#fig.subplots_adjust(bottom = 10,  top =20  ,wspace = 50 ,hspace = 50
for i, key in enumerate(precisions_map.keys()):
    plt.plot(ticks,
             precisions_map[key],
             str(colours[i % len(colours)]) + str(shapes[i % 3]),
             label=str(key))

plt.set_xticklabels(ticks)
plt.set_xticks([0.5 * a for a in range(len(ticks))])
plt.set_title('Precision for different distance metrics')
plt.legend(loc='lower left')
plt.grid(axis='both')
plt.savefig('figs/comparsion.jpg')
plt.clf()
plt.cla()
def make_figure_markers(means_mo, stddevs_mo, \
                        means_ma, stddevs_ma, \
                        means_w0, stddevs_w0, \
                        means_w1, stddevs_w1, \
                        means_w2, stddevs_w2, \
                        means_w3, stddevs_w3, \
                        means_w4, stddevs_w4, \
                        means_w5, stddevs_w5, \
                        title, xlabel, ylabel, ylim):
    fig1 = plt.figure(figsize=(10, 10))
    #plt.title(title)
    plt.ylabel(xlabel)
    plt.xlabel(ylabel)
    plt.ylim(ylim)
    start, end = plt.get_xlim()
    plt.set_xticks(np.arange(start, end, 0.1))
    plt.errorbar(range(len(means_mo)),
                 means_mo,
                 stddevs_mo,
                 capsize=5,
                 errorevery=2,
                 label='no attenuation')
    plt.errorbar(range(len(means_ma)),
                 means_ma,
                 stddevs_ma,
                 capsize=5,
                 errorevery=3,
                 label='model')
    plt.errorbar(range(len(means_w0)),
                 means_w0,
                 stddevs_w0,
                 capsize=5,
                 errorevery=4,
                 label='w0 set')
    plt.errorbar(range(len(means_w1)),
                 means_w1,
                 stddevs_w1,
                 capsize=5,
                 errorevery=5,
                 label='w1 set')
    plt.errorbar(range(len(means_w2)),
                 means_w2,
                 stddevs_w2,
                 capsize=5,
                 errorevery=6,
                 label='w2 set')
    plt.errorbar(range(len(means_w3)),
                 means_w3,
                 stddevs_w3,
                 capsize=5,
                 errorevery=7,
                 label='w3 set')
    plt.errorbar(range(len(means_w4)),
                 means_w4,
                 stddevs_w4,
                 capsize=5,
                 errorevery=8,
                 label='w4 set')
    plt.errorbar(range(len(means_w5)),
                 means_w5,
                 stddevs_w5,
                 capsize=5,
                 errorevery=9,
                 label='w5 set')
    plt.legend(ncol=2, loc='lower right')
    filename = title + '.jpg'
    plt.savefig(filename)
    plt.close()

    _table_stats = []
    _table_p = []
    _line_s = []
    _line_p = []

    _line_s.append('MO')
    _line_p.append('MO')
    _line_s.append('-')
    _line_p.append('-')
    stat, p = stats.ttest_ind(means_mo, means_ma)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_mo, means_w0)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_mo, means_w1)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_mo, means_w2)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_mo, means_w3)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_mo, means_w4)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_mo, means_w5)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    _table_stats.append(_line_s)
    _table_p.append(_line_p)
    _line_s = []
    _line_p = []

    _line_s.append('MA')
    _line_p.append('MA')
    stat, p = stats.ttest_ind(means_ma, means_mo)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    # ma ma
    _line_s.append('-')
    _line_p.append('-')
    stat, p = stats.ttest_ind(means_ma, means_w0)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_ma, means_w1)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_ma, means_w2)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_ma, means_w3)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_ma, means_w4)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_ma, means_w5)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    _table_stats.append(_line_s)
    _table_p.append(_line_p)
    _line_s = []
    _line_p = []

    _line_s.append('W0')
    _line_p.append('W0')
    stat, p = stats.ttest_ind(means_w0, means_mo)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w0, means_ma)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    # w0 w0
    _line_s.append('-')
    _line_p.append('-')
    stat, p = stats.ttest_ind(means_w0, means_w1)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w0, means_w2)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w0, means_w3)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w0, means_w4)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w0, means_w5)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    _table_stats.append(_line_s)
    _table_p.append(_line_p)
    _line_s = []
    _line_p = []

    _line_s.append('W1')
    _line_p.append('W1')
    stat, p = stats.ttest_ind(means_w1, means_mo)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w1, means_ma)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w1, means_w0)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    # w1 w1
    _line_s.append('-')
    _line_p.append('-')
    stat, p = stats.ttest_ind(means_w1, means_w2)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w1, means_w3)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w1, means_w4)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w1, means_w5)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    _table_stats.append(_line_s)
    _table_p.append(_line_p)
    _line_s = []
    _line_p = []

    _line_s.append('W2')
    _line_p.append('W2')
    stat, p = stats.ttest_ind(means_w2, means_mo)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w2, means_ma)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w2, means_w0)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w2, means_w1)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    # w2 w2
    _line_s.append('-')
    _line_p.append('-')
    stat, p = stats.ttest_ind(means_w2, means_w3)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w2, means_w4)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w2, means_w5)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    _table_stats.append(_line_s)
    _table_p.append(_line_p)
    _line_s = []
    _line_p = []

    _line_s.append('W3')
    _line_p.append('W3')
    stat, p = stats.ttest_ind(means_w3, means_mo)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w3, means_ma)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w3, means_w0)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w3, means_w1)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w3, means_w2)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    # w3 w3
    _line_s.append('-')
    _line_p.append('-')
    stat, p = stats.ttest_ind(means_w3, means_w4)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w3, means_w5)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    _table_stats.append(_line_s)
    _table_p.append(_line_p)
    _line_s = []
    _line_p = []

    _line_s.append('W4')
    _line_p.append('W4')
    stat, p = stats.ttest_ind(means_w4, means_mo)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w4, means_ma)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w4, means_w0)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w4, means_w1)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w4, means_w2)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w4, means_w3)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    # w4 w4
    _line_s.append('-')
    _line_p.append('-')
    stat, p = stats.ttest_ind(means_w4, means_w5)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    _table_stats.append(_line_s)
    _table_p.append(_line_p)
    _line_s = []
    _line_p = []

    _line_s.append('W5')
    _line_p.append('W5')
    stat, p = stats.ttest_ind(means_w5, means_mo)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w5, means_ma)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w5, means_w0)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w5, means_w1)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w5, means_w2)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w5, means_w3)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    stat, p = stats.ttest_ind(means_w5, means_w4)
    _line_s.append(round(stat, 1))
    _line_p.append(round(p, 4))
    # w5 w5
    _line_s.append('-')
    _line_p.append('-')
    _table_stats.append(_line_s)
    _table_p.append(_line_p)
    _line_s = []
    _line_p = []

    # print('Statistics=%.3f, p=%.3f' % (stat, p))
    headers = ['', 'MO', 'MA', 'W0', 'W1', 'W2', 'W3', 'W4', 'W5']
    np.savetxt(
        title + '_stat.txt',
        ["%s" % tabulate.tabulate(_table_stats, headers, tablefmt="latex")],
        fmt='%s')
    np.savetxt(title + '_p.txt',
               ["%s" % tabulate.tabulate(_table_p, headers, tablefmt="latex")],
               fmt='%s')
Exemplo n.º 9
0
        dir_path, "kitti_squeezeDet_config.json")
    base_dir = json.load(open(args["ext_config_file_path"]))["BASE_DIR"]
    if not os.path.exists(base_dir):
        os.makedirs(base_dir)
    start(args)

    # get training directory
    train_dir = os.path.join(base_dir, "train")

    # plot results
    with open(os.path.join(train_dir, "step_times.json"), "r") as f:
        J = json.load(f)
        steps = np.arange(J["MAX_STEPS"])
        times = np.array(J["TIMES"])

    fig = plt.figure()
    plt.plot(steps, times, color="xkcd:green", linewidth=2)
    """
    For comparison export sec/batch of the [old implementation](https://github.com/BichenWuUCB/squeezeDet/blob/master/src/train.py)
    and plot it for the same number of steps with the same way
    with color "xkcd:purple".
  """

    plt.grid()
    plt.set_xticks(np.arange(0, J["MAX_STEPS"], 5000))
    plt.set_xlabel("steps")
    plt.set_ylabel("total_time")

    # save figure and plot it
    plt.savefig(SAVE_FIG_TO_PATH)
    plt.show()
Exemplo n.º 10
0
def Pilot_Plot():
    # Creating big figure to hold all
    fig = plt.figure(figsize=(20, 16))

    # setting font size
    plt.rcParams.update({'font.size': 8})

    # # Turn off axis lines and ticks of the big subplot
    # ax.spines['top'].set_color('none')
    # ax.spines['bottom'].set_color('none')
    # ax.spines['left'].set_color('none')
    # ax.spines['right'].set_color('none')

    # Plotting estimated mu vs. response mu
    ax0 = fig.add_subplot(231)
    ax0.scatter(res_mu, est_mu, marker='.', label=f'n={len(res_mu)}')
    ax0.legend()
    ax0.set_title(
        'FOR VALIDATION: Participant response as a function of estimated mu')
    ax0.set_xlabel('response mu (radians)')
    ax0.set_ylabel('estimated mu (radians)')
    plt.set_xticks(card_direc)
    plt.set_yticks(card_direc)

    # Plotting MSE across presentation times
    ax1 = fig.add_subplot(232)
    ax1.set_title('MSE across stimulus presentation times')
    ax1.set_xlabel('Presentation Times (ms)')
    ax1.set_ylabel('MSE')
    # plt.bar(np.arange(8), durMSE, width=0.2)
    ax1.plot(np.arange(8), durMSE)
    ax1.set_xticks(np.arange(8), labels=durVal)

    #######################################################################################################
    # # Plotting response time vs. estimated mu, vs. response_mu
    # plt.figure(figsize=(13,6))
    #
    # plt.subplot(211)
    # plt.scatter(est_mu, data[colnames.index('keyRT')], marker='.', label=f'n={len(est_mu)}')
    # plt.legend()
    # plt.title('Response time as a function of estimated mean location')
    # plt.xlabel('est_mu (radians)')
    # plt.ylabel('response time (ms)')
    #
    # plt.subplot(212)
    # plt.scatter(res_mu, data[colnames.index('keyRT')], marker='.',label=f'n={len(res_mu)}')
    # plt.legend()
    # plt.title('Response time as a function of participant-observed mean location')
    # plt.xlabel('response mu (radians)')
    # plt.ylabel('response time (ms)')
    #
    # plt.tight_layout()
    # plt.show()

    # #######################################################################################################
    # ## Plotting cardinal vs. oblique MSE
    # plt.figure(figsize=(4,3))
    # plt.title('MSE, by orientation of MSE \n(each direction padded by pi/8 radians')
    # plt.bar([0, 1], [card_MSE, obli_MSE])
    # plt.ylabel('MSE')
    # plt.xticks([0,1], ('cardinal','oblique'))
    # plt.show()

    #######################################################################################################
    ## Plotting relationship of accuracy with RT and PT
    ## TODO: Plot SAT curve after fitting logistic function
    plt.figure(figsize=(14, 4))
    plt.rcParams.update({'font.size': 6})

    ax2 = fig.add_subplot(233)
    # plt.title('Response time-Accuracy')
    # plt.xlabel('Response time (ms)')
    # plt.ylabel('Accuracy (percent distance of response mu from est_mu)')
    # plt.scatter(keyRT, ERxTrials * 100, marker='.', s=1)
    # plt.xticks(durVal, labels=durVal)

    ax2.set_title('Presentation Time vs. Accuracy')
    ax2.set_xlabel('Presentation time (ms)')
    ax2.set_ylabel('Accuracy (percent distance of response mu from est_mu)')
    ax2.scatter(vizDur, res_acc * 100)
    ax2.set_xticks(durVal, labels=durVal)

    # Boxplot, Response time median, mean, IQR for each stimulus duration
    ax3 = fig.add_subplot(234)
    ax3.set_title(
        'Response time, by stimulus duration \n(orange = median, green = mean)'
    )
    ax3.set_ylabel('Response time (ms)')
    ax3.set_xlabel('Presentation duration (ms)')
    ax3.boxplot(dur_RT, meanline=True, showmeans=True)
    ax3.set_xticks(np.arange(1, len(durVal) + 1), labels=durVal)

    #######################################################################################################
    # ## Accuracy as a function of distance of initial probe to (1) response mu and (2) estimated mu
    # fig = plt.figure(figsize=(10,5))
    #
    # ax = fig.add_subplot(111)  # The big subplot
    # ax1 = fig.add_subplot(211)
    # ax2 = fig.add_subplot(212)
    #
    # # Turn off axis lines and ticks of the big subplot
    # ax.spines['top'].set_color('none')
    # ax.spines['bottom'].set_color('none')
    # ax.spines['left'].set_color('none')
    # ax.spines['right'].set_color('none')
    # ax.tick_params(labelcolor='w', top='off', bottom='off', left='off', right='off')
    # ax.set_ylabel('Trial Accuracy')
    #
    # # fig.suptitle('Accuracy vs. probe locations')
    # ax1.scatter(probe2est, ERxTrials, marker='.', s=1)
    # ax1.set_xlabel('distance from initial probe to estimated mu (radians)')
    # ax2.scatter(probe2res, ERxTrials, marker='.', s=1)
    # ax2.set_xlabel('distance from initial probe to response mu (radians)')
    # plt.tight_layout()
    #
    # plt.figure(figsize=(14, 4))
    # plt.rcParams.update({'font.size': 6})

    ax4 = fig.add_subplot(235)
    plt.title('Presentation Time-Accuracy Curve')
    plt.xlabel('Presentation time (ms)')
    plt.ylabel('Accuracy (percent distance of response mu from est_mu)')
    plt.scatter(vizDur, res_acc * 100)
    plt.xticks(durVal, labels=durVal)

    plt.title('Error vs. Propmix')
    plt.xlabel('Response time (ms)')
    plt.ylabel('Accuracy (percent distance of response mu from est_mu)')
    plt.scatter(keyRT, res_acc * 100, marker='.', s=1)
    # plt.xticks(durVal, labels=durVal)

    plt.figure(figsize=(12, 4))
    plt.rcParams.update({'font.size': 12})
    plt.suptitle('Parameter dependency on response time')
    plt.rcParams.update({'font.size': 8})
    plt.subplot(121)
    plt.title(
        'Mean response time as a function of kappa (concentration) of stimulus'
    )
    for i, x in enumerate(propVal):
        plt.plot(kpVal[i], kp_RT_mean[i], label=f'propmix = {x}')
    plt.legend()
    plt.xlabel('estimated kappa')
    plt.ylabel('mean RT (ms)')
    plt.title('RT by kappa')

    ## All kappa
    # plt.plot(kapVal, kap_RT_mean)
    # plt.xlabel('kappa')
    # plt.ylabel('mean RT (ms)')

    plt.subplot(122)
    plt.bar(propVal, prop_RT_mean)
    plt.title('Mean response time as a function of noise present')
    plt.xlabel(
        'Proportion of uniform noise to von Mises distribution in stimulus')
    plt.ylabel('mean RT (ms)')
    plt.xticks(propVal)