コード例 #1
0
def srcdiff_plot(env, model, **kwargs):
    obj_index       = kwargs.pop('obj_index', 0)
    src_index       = kwargs.pop('src_index', 0)
    with_colorbar   = kwargs.pop('with_colorbar', False)
    xlabel          = kwargs.pop('xlabel', r'arcsec')
    ylabel          = kwargs.pop('ylabel', r'arcsec')

    obj, data = model['obj,data'][obj_index]
    S = obj.basis.subdivision
    R = obj.basis.mapextent

    g = obj.basis.srcdiff_grid(data)[src_index]
    vmin = np.log10(np.amin(g[g>0]))
    g = g.copy() + 1e-10
    kw = default_kw(R, kwargs) #, vmin=vmin, vmax=vmin+2)

    #loglev = logspace(1, log(amax(g)-amin(g)), 20, base=math.e) + amin(g)
    pl.matshow(np.log10(g), **kw)
    matplotlib.rcParams['contour.negative_linestyle'] = 'solid'
    if with_colorbar: glspl.colorbar()
#   pl.over(contour, g, 50,  colors='w',               linewidths=1, 
#        extent=[-R,R,-R,R], origin='upper', extend='both')
    #pl.grid()

    pl.xlabel(xlabel)
    pl.ylabel(ylabel)
コード例 #2
0
ファイル: plots.py プロジェクト: stefanSchinkel/crpy
def showDistMatrix(distMatrix):		
	pylab.matshow(distMatrix)
 	ax = pylab.gca() 
 	bottom, top = ax.get_ylim()
	ax.set_ylim(top, bottom)		
	pylab.colorbar() 
	pylab.show()
コード例 #3
0
ファイル: plots.py プロジェクト: jpcoles/glass
def srcdiff_plot(env, model, **kwargs):
    obj_index = kwargs.pop('obj_index', 0)
    src_index = kwargs.pop('src_index', 0)
    with_colorbar = kwargs.pop('with_colorbar', False)
    xlabel = kwargs.pop('xlabel', r'arcsec')
    ylabel = kwargs.pop('ylabel', r'arcsec')

    obj, data = model['obj,data'][obj_index]
    S = obj.basis.subdivision
    R = obj.basis.mapextent

    g = obj.basis.srcdiff_grid(data)[src_index]
    vmin = np.log10(np.amin(g[g > 0]))
    g = g.copy() + 1e-10
    kw = default_kw(R, kwargs)  #, vmin=vmin, vmax=vmin+2)

    #loglev = logspace(1, log(amax(g)-amin(g)), 20, base=math.e) + amin(g)
    pl.matshow(np.log10(g), **kw)
    matplotlib.rcParams['contour.negative_linestyle'] = 'solid'
    if with_colorbar: glspl.colorbar()
    #   pl.over(contour, g, 50,  colors='w',               linewidths=1,
    #        extent=[-R,R,-R,R], origin='upper', extend='both')
    #pl.grid()

    pl.xlabel(xlabel)
    pl.ylabel(ylabel)
コード例 #4
0
ファイル: __init__.py プロジェクト: Terradue/adore-doris
def transect(x,y,z,x0,y0,x1,y1,plots=0):
    #convert coord to pixel coord
    d0=sqrt( (x-x0)**2+ (y-y0)**2 );
    i0=d0.argmin();
    x0,y0=unravel_index(i0,x.shape); #overwrite x0,y0
    
    d1=plt.np.sqrt( (x-x1)**2+ (y-y1)**2 );
    i1=d1.argmin();
    x1,y1=unravel_index(i1,x.shape); #overwrite x1,y1    
    #-- Extract the line...    
    # Make a line with "num" points...
    length = int(plt.np.hypot(x1-x0, y1-y0))
    xi, yi = plt.np.linspace(x0, x1, length), plt.np.linspace(y0, y1, length) 
       
    # Extract the values along the line
    #y is the first dimension and x is the second, row,col
    zi = z[xi.astype(plt.np.int), yi.astype(plt.np.int)]
    mz=nonaninf(z.ravel()).mean()
    sz=nonaninf(z.ravel()).std()
    if plots==1:
        plt.matshow(z);plt.clim([mz-2*sz,mz+2*sz]);plt.colorbar();plt.title('transect: (' + str(x0) + ',' + str(y0) + ') (' +str(x1) + ',' +str(y1) + ')' );
        plt.scatter(yi,xi,5,c='r',edgecolors='none')
        plt.figure();plt.scatter(sqrt( (xi-xi[0])**2 + (yi-yi[0])**2 ) , zi)
        #plt.figure();plt.scatter(xi, zi)
        #plt.figure();plt.scatter(yi, zi)

    return (xi, yi, zi);
コード例 #5
0
ファイル: plots.py プロジェクト: jpcoles/glass
def potential_plot(env,
                   model,
                   obj_index,
                   src_index,
                   with_colorbar=True,
                   with_contours=False):
    obj, data = model['obj,data'][obj_index]
    R = obj.basis.mapextent
    grid = obj.basis.potential_grid(data)
    levs = obj.basis.potential_contour_levels(data)
    #   pl.matshow(grid, fignum=False, extent=[-R,R,-R,R], interpolation='nearest')
    pl.matshow(grid,
               fignum=False,
               cmap=cm.bone,
               extent=[-R, R, -R, R],
               interpolation='nearest')
    if with_colorbar: glspl.colorbar()
    #   pl.contour(grid, extent=[-R,R,-R,R], origin='upper')
    #print levs
    if with_contours:
        for i, lev in enumerate(levs):
            pl.over(contour,
                    grid,
                    lev,
                    colors=system_color(i),
                    extent=[-R, R, -R, R],
                    origin='upper',
                    extend='both')

    pl.xlabel('arcsec')
    pl.ylabel('arcsec')
コード例 #6
0
ファイル: plots.py プロジェクト: stefanSchinkel/crpy
def showDistMatrix(distMatrix):
    pylab.matshow(distMatrix)
    ax = pylab.gca()
    bottom, top = ax.get_ylim()
    ax.set_ylim(top, bottom)
    pylab.colorbar()
    pylab.show()
コード例 #7
0
def benchmark(clf_class, params, name):
    print "parameters:", params
    t0 = time()
    clf = clf_class(**params).fit(X_train, y_train)
    print "done in %fs" % (time() - t0)

    if hasattr(clf, 'coef_'):
        print "Percentage of non zeros coef: %f" % (
          np.mean(clf.coef_ != 0) * 100)

    print "Predicting the outcomes of the testing set"
    t0 = time()
    pred = clf.predict(X_test)
    print "done in %fs" % (time() - t0)

    print "Classification report on test set for classifier:"
    print clf
    print
    print classification_report(y_test, pred,
       target_names=news_test.target_names)

    cm = confusion_matrix(y_test, pred)
    print "Confusion matrix:"
    print cm

    # Show confusion matrix
    pl.matshow(cm)
    pl.title('Confusion matrix of the %s classifier' % name)
    pl.colorbar()
コード例 #8
0
def gradient_grid_plot(env, model, obj_index):
    obj, data = model['obj,data'][obj_index]
    b = obj.basis
    kappa = data['kappa']
    grid = np.zeros_like(kappa)

    #wght = lambda x: 1.0 / len(x) if len(x) else 0
    wght = lambda x: b.cell_size[x]**2 / np.sum(b.cell_size[x]**2)
    for i, r in enumerate(b.ploc):
        n, e, s, w = b.nbrs3[i][2]

        dx = np.sum(kappa[w] * wght(w)) - np.sum(kappa[e] * wght(e))
        dy = np.sum(kappa[s] * wght(s)) - np.sum(kappa[n] * wght(n))

        dx *= -1
        dy *= -1

        #print dx, dy

        dr = np.sqrt(dx**2 + dy**2)
        grid[i] = dr

    grid = grid
    kw = default_kw(b.mapextent, vmin=np.amin(grid), vmax=np.amax(grid))
    grid = b._to_grid(grid, b.subdivision)
    pl.matshow(grid, **kw)
    glscolorbar()
コード例 #9
0
def benchmark(clf_class, params, name):
    print("parameters:", params)
    t0 = time()
    clf = clf_class(**params).fit(X_train, y_train)
    print("done in %fs" % (time() - t0))

    if hasattr(clf, 'coef_'):
        print("Percentage of non zeros coef: %f"
              % (np.mean(clf.coef_ != 0) * 100))
    print("Predicting the outcomes of the testing set")
    t0 = time()
    pred = clf.predict(X_test)
    print("done in %fs" % (time() - t0))

    print("Classification report on test set for classifier:")
    print(clf)
    print()
    print(classification_report(y_test, pred,
                                target_names=news_test.target_names))

    cm = confusion_matrix(y_test, pred)
    print("Confusion matrix:")
    print(cm)

    # Show confusion matrix
    pl.matshow(cm)
    pl.title('Confusion matrix of the %s classifier' % name)
    pl.colorbar()
コード例 #10
0
def grad_kappa_plot(env, model, obj_index, which='x', with_contours=False, only_contours=False, clevels=30, with_colorbar=True):
    obj, data = model['obj,data'][obj_index]

    R = obj.basis.mapextent

    grid = obj.basis.kappa_grid(data)
    grid = grid.copy()

    kw = default_kw(R)
    kw['vmin'] = -1
    kw['vmax'] =  2

    if not only_contours:
        print '!!!!!!', grid.shape
        if which == 'x': grid = np.diff(grid, axis=1)
        if which == 'y': grid = np.diff(grid, axis=0)
        print '!!!!!!', grid.shape
        pl.matshow(grid, **kw)
        if with_colorbar: 
            glspl.colorbar()

    if with_contours:
        kw.pop('cmap')
        pl.over(contour, grid, clevels, extend='both', colors='k', alpha=0.7, **kw)

    pl.xlabel('arcsec')
    pl.ylabel('arcsec')
コード例 #11
0
def plotMatrix(cm):
    pl.matshow(cm)
    pl.title('Confusion matrix')
    pl.colorbar()
    pl.ylabel('True label')
    pl.xlabel('Predicted label')
    pl.show()
コード例 #12
0
def transect(x, y, z, x0, y0, x1, y1, plots=0):
    #convert coord to pixel coord
    d0 = sqrt((x - x0)**2 + (y - y0)**2)
    i0 = d0.argmin()
    x0, y0 = unravel_index(i0, x.shape)
    #overwrite x0,y0

    d1 = plt.np.sqrt((x - x1)**2 + (y - y1)**2)
    i1 = d1.argmin()
    x1, y1 = unravel_index(i1, x.shape)
    #overwrite x1,y1
    #-- Extract the line...
    # Make a line with "num" points...
    length = int(plt.np.hypot(x1 - x0, y1 - y0))
    xi, yi = plt.np.linspace(x0, x1, length), plt.np.linspace(y0, y1, length)

    # Extract the values along the line
    #y is the first dimension and x is the second, row,col
    zi = z[xi.astype(plt.np.int), yi.astype(plt.np.int)]
    mz = nonaninf(z.ravel()).mean()
    sz = nonaninf(z.ravel()).std()
    if plots == 1:
        plt.matshow(z)
        plt.clim([mz - 2 * sz, mz + 2 * sz])
        plt.colorbar()
        plt.title('transect: (' + str(x0) + ',' + str(y0) + ') (' + str(x1) +
                  ',' + str(y1) + ')')
        plt.scatter(yi, xi, 5, c='r', edgecolors='none')
        plt.figure()
        plt.scatter(sqrt((xi - xi[0])**2 + (yi - yi[0])**2), zi)
        #plt.figure();plt.scatter(xi, zi)
        #plt.figure();plt.scatter(yi, zi)

    return (xi, yi, zi)
コード例 #13
0
def matrix_picture(matrix):
    pl.matshow(matrix)
    pl.title('Confusion matrix')
    pl.colorbar()
    pl.ylabel('True label')
    pl.xlabel('Predicted label')
    pl.show()
コード例 #14
0
ファイル: confusion_matrix.py プロジェクト: AkiraKane/Python
def plotMatrix(cm):
    pl.matshow(cm)
    pl.title('Confusion matrix')
    pl.colorbar()
    pl.ylabel('True label')
    pl.xlabel('Predicted label')
    pl.show()
コード例 #15
0
ファイル: visualize.py プロジェクト: w470062742/mstar_public
def draw_astar_graph(obs_map, graph):
    """Debugging function which will show the current state of the m*
    graph
    """
    # Draw the obstacles
    pylab.hold(False)
    sizex = len(obs_map)
    sizey = len(obs_map[0])
    pylab.plot([-.5, sizex - .5, sizex - .5, -.5, -.5],
               [-.5, -.5, sizey - .5, sizey - .5, -.5], 'k')
    pylab.hold(True)
    pylab.matshow((1 - numpy.array(obs_map)).T, fignum=0)
    pylab.gray()
    pylab.clim(-2, 1)
    # Assemble the quiver
    X, Y, U, V = [[] for i in xrange(4)]
    for node in graph.graph.itervalues():
        x, y = node.coord
        u, v = map(lambda w, v: w - v, node.policy, node.coord)
        X.append(x)
        Y.append(y)
        U.append(u)
        V.append(v)
    pylab.quiver(X, Y, U, V)
    pylab.xlim([-.5, sizex - .5])
    pylab.ylim([-.5, sizey - .5])
    pylab.xticks([])
    pylab.yticks([])
    pylab.hold(False)
    pylab.show()
コード例 #16
0
def show_chains(rbm, state, dataset, num_particles=20, num_samples=20, show_every=10, display=True,
                figname='Gibbs chains', figtitle='Gibbs chains'):
    samples = gnp.zeros((num_particles, num_samples, state.v.shape[1]))
    state = state[:num_particles, :, :]

    for i in range(num_samples):
        samples[:, i, :] = rbm.vis_expectations(state.h)
        
        for j in range(show_every):
            state = rbm.step(state)

    npix = dataset.num_rows * dataset.num_cols
    rows = [vm.hjoin([samples[i, j, :npix].reshape((dataset.num_rows, dataset.num_cols)).as_numpy_array()
                      for j in range(num_samples)],
                     normalize=False)
            for i in range(num_particles)]
    grid = vm.vjoin(rows, normalize=False)

    if display:
        pylab.figure(figname)
        pylab.matshow(grid, cmap='gray', fignum=False)
        pylab.title(figtitle)
        pylab.gcf().canvas.draw()

    return grid
コード例 #17
0
def plot_mandelbot(xmin=-2.25,
                   xmax=0.75,
                   xres=3000,
                   ymin=-1.25,
                   ymax=1.25,
                   yres=2500,
                   maxiter=200,
                   horizon=2.0**40):

    z, n = mandelbrot_set(xmin, xmax, ymin, ymax, xres, yres, maxiter, horizon)

    # Plot the results... dig the fancy pylab skills!
    xaxis_res = int(xres / 20)
    yaxis_res = int(yres / 20)
    x_axis = np.linspace(xmin, xmax, num=xres)
    y_axis = np.linspace(ymin, ymax, num=yres)
    x_labels = []
    y_labels = []
    for i in range(0, len(x_axis), xaxis_res):
        x_labels.append(str(round(x_axis[i], 2)))
    for i in range(0, len(y_axis), yaxis_res):
        y_labels.append(str(round(y_axis[i], 2)))

    pylab.matshow(n, cmap=plt.cm.hot, interpolation='nearest')
    pylab.xticks(np.arange(0, xres, xaxis_res), x_labels)
    pylab.yticks(np.arange(0, yres, yaxis_res), y_labels)
    pylab.xticks(rotation=90)
    pylab.xlim(0, xres)
    pylab.ylim(yres, 0)
    pylab.xlabel('x')
    pylab.ylabel('y')
    ax = pylab.colorbar()
    ax.set_label('Iterations till divergence')
    pylab.draw()
コード例 #18
0
ファイル: SKFold.py プロジェクト: GiuliaCuttone/G-Repository
def calcola(X, y):
    for train_index, test_index in kf.split(X, y):
        #separa le variabili per l'addestramento da quelle per il test
        X_train, X_test = X[train_index], X[test_index]
        y_train, y_test = y[train_index], y[test_index]

        clf.fit(X_train, y_train)
        pred = clf.predict(X_test)

        score = accuracy_score(y_test, pred)

        MCC = matthews_corrcoef(y_test, pred)

        print("\n\nEtichette Corrette")
        print("TRAIN:", y_train, "\nTEST:", y_test)

        print("\nEtichette Predette")
        print("TEST:",
              pred)  #0 Setosa, 1 Versicolor, 2 Virginica   Etichette Predette

        cm = confusion_matrix(y_test, pred)
        pl.matshow(cm)
        pl.title('Matrice di confusione\n')
        pl.colorbar()
        pl.show()

        print(classification_report(y_test, pred))

        print("Accuracy:", score)
        print("Matthew Coefficient:", MCC)
コード例 #19
0
ファイル: plots.py プロジェクト: RafiKueng/glass
def gradient_grid_plot(env, model, obj_index):
    obj,data = model['obj,data'][obj_index]
    b = obj.basis
    kappa = data['kappa']
    grid = np.zeros_like(kappa)

    #wght = lambda x: 1.0 / len(x) if len(x) else 0
    wght = lambda x: b.cell_size[x]**2 / np.sum(b.cell_size[x]**2)
    for i,r in enumerate(b.ploc):
        n,e,s,w = b.nbrs3[i][2]

        dx = np.sum(kappa[w] * wght(w)) - np.sum(kappa[e] *  wght(e))
        dy = np.sum(kappa[s] * wght(s)) - np.sum(kappa[n] *  wght(n))

        dx*=-1
        dy*=-1

        #print dx, dy

        dr = np.sqrt(dx**2 + dy**2)
        grid[i] = dr 

    grid = grid
    kw = default_kw(b.mapextent, vmin=np.amin(grid), vmax=np.amax(grid))
    grid = b._to_grid(grid, b.subdivision)
    pl.matshow(grid, **kw)
    glscolorbar()
コード例 #20
0
def HarmonicResponseViewer(bw,harmonicResponse,title="",mode="COS_SIN"):
    #
    # okay I should make the matrix full of zeros and then set the values
    # as I go through the harmonicResponse

    #First we do regular bar charts plot

    #pprint(harmonicResponse)
    data=[[a,b,c,d] for (a,b),(c,d) in harmonicResponse]
    for mval in range(bw+1):
        HarmonicBarChart(mval,data,mchoiceMinusOne=False)
        HarmonicBarChart(mval,data,showPrime=True,mchoiceMinusOne=False)
    #Then the matrix plots

    
    mat_cos=zeros((bw,bw))
    mat_sin=mat_cos
    for (x,y),(c,s) in harmonicResponse:
        mat_cos[y][x]=c
        mat_sin[y][x]=s

    pylab.matshow(mat_cos)
    pylab.title(title+" cos")
    pylab.xlabel("n")
    pylab.ylabel("m")
    pylab.show()
    pylab.matshow(mat_sin)
    pylab.title(title+" sin")
    pylab.xlabel("n")
    pylab.ylabel("m")
    pylab.show()
コード例 #21
0
def networkPerformance(RX,test_inputs,labels_test):

        from sklearn.metrics import classification_report
        from sklearn.metrics import confusion_matrix
        import pylab as pl
        expected = labels_test
        t1 = time.clock()
        predicted = RX.compute_predictions(test_inputs)
        t2 = time.clock()
        print 'Ca nous a pris ', t2-t1, ' secondes pour calculer les predictions sur ', test_inputs.shape[0],' points de test'
        err = 1.0 - np.mean(labels_test==predicted)
        print "L'erreur de test est de ", 100.0 * err,"%"
        np.save('erreurTest_cae_full',100.0 * err)

        print "Classification report for classifier %s:\n%s\n" % (
               RX, classification_report(expected, predicted))
        cm=confusion_matrix(expected, predicted)
        print "Confusion matrix:\n%s" % cm
        # Show confusion matrix in a separate window
        pl.matshow(cm)
        pl.title('Confusion matrix')
        pl.colorbar()
        pl.ylabel('True label')
        pl.xlabel('Predicted label')
        pl.show()
        return
コード例 #22
0
ファイル: plots.py プロジェクト: RafiKueng/glass
def kappa_residual_grid_plot(env, model, base_model, obj_index, with_contours=False, only_contours=False, with_colorbar=True):
    obj0,data0 = base_model['obj,data'][obj_index]
    obj1,data1 = model['obj,data'][obj_index]

    kappa = data1['kappa'] - data0['kappa']
       
    grid = obj1.basis._to_grid(kappa, obj1.basis.subdivision)
    R = obj1.basis.mapextent

    kw = {'extent': [-R,R,-R,R],
          'interpolation': 'nearest',
          'aspect': 'equal',
          'origin': 'upper',
          'cmap': cm.gist_stern,
          'fignum': False}
          #'vmin': -1,
          #'vmax':  1}

    if not only_contours:
        pl.matshow(grid, **kw)
    if only_contours or with_contours:
        kw.update({'colors':'k', 'linewidths':1, 'cmap':None})
        pl.contour(grid, **kw)
        kw.update({'colors':'k', 'linewidths':2, 'cmap':None})
        pl.contour(grid, [0], **kw)

    if with_colorbar:
        glscolorbar()
    return
コード例 #23
0
def main():
    import pylab
    
    # Create the gaussian data
    Xin, Yin = pylab.mgrid[0:201, 0:201]
    data = gaussian(3, 100, 100, 20, 40)(Xin, Yin) + np.random.random(Xin.shape)
    
    pylab.matshow(data, cmap='gist_rainbow')
    
    params = fitgaussian(data)
    fit = gaussian(*params)
    
    pylab.contour(fit(*pylab.indices(data.shape)), cmap='copper')
    ax = pylab.gca()
    (height, x, y, width_x, width_y) = params
    
    pylab.text(0.95, 0.05, """
    x : %.1f
    y : %.1f
    width_x : %.1f
    width_y : %.1f""" %(x, y, width_x, width_y),
            fontsize=16, horizontalalignment='right',
            verticalalignment='bottom', transform=ax.transAxes)
    
    pylab.show()
コード例 #24
0
def train_model(trainset):
	word_vector = TfidfVectorizer(analyzer="word", ngram_range=(2,2), binary = False, max_features= 2000,min_df=1,decode_error="ignore")
#	print word_vector	
	print "works fine"
	char_vector = TfidfVectorizer(ngram_range=(2,3), analyzer="char", binary = False, min_df = 1, max_features = 2000,decode_error= "ignore")
	vectorizer =FeatureUnion([ ("chars", char_vector),("words", word_vector) ])
	corpus = []
	classes = []

	for item in trainset:
		corpus.append(item['text'])
		classes.append(item['label'])

	print "Training instances : ", 0.8*len(classes)
	print "Testing instances : ", 0.2*len(classes) 
	
	matrix = vectorizer.fit_transform(corpus)
	print "feature count : ", len(vectorizer.get_feature_names())
	print "training model"
	X = matrix.toarray()
	y = numpy.asarray(classes)
	model =LinearSVC()
	X_train, X_test, y_train, y_test= train_test_split(X,y,train_size=0.8,test_size=.2,random_state=0)
	y_pred = OneVsRestClassifier(model).fit(X_train, y_train).predict(X_test)
	#y_prob = OneVsRestClassifier(model).fit(X_train, y_train).decision_function(X_test)
	#print y_prob
	#con_matrix = []
	#for row in range(len(y_prob)):
	#	temp = [y_pred[row]]	
	#	for prob in y_prob[row]:
	#		temp.append(prob)
	#	con_matrix.append(temp)
	#for row in con_matrix:
	#	output.write(str(row)+"\n")
	#print y_pred		
	#print y_test
	
	res1=[i for i, j in enumerate(y_pred) if j == 'anonEdited']
	res2=[i for i, j in enumerate(y_test) if j == 'anonEdited']
	reset=[]
	for r in res1:
		if y_test[r] != "anonEdited":
			reset.append(y_test[r])
	for r in res2:
		if y_pred[r] != "anonEdited":
			reset.append(y_pred[r])
	
	
	output=open(sys.argv[2],"w")
	for suspect in reset:
		output.write(str(suspect)+"\n")	
	cm = confusion_matrix(y_test, y_pred)
	print(cm)
	pl.matshow(cm)
	pl.title('Confusion matrix')
	pl.colorbar()
	pl.ylabel('True label')
	pl.xlabel('Predicted label')
	pl.show()
	print accuracy_score(y_pred,y_test)
コード例 #25
0
    def visualize(self):
        import pylab
        '''Generates visualizationss of the A and E matrices.'''
        # Construct a matrix that is upper-triangle flux and lower-triangle error
        fluxAndError = self.A.copy()
        for i in range(len(self.A)):
            fluxAndError[i, 0:i] = self.E[i, 0:i]

#        pylab.clf()
        pylab.matshow(fluxAndError, cmap=pylab.cm.gray)
        l = len(self.A)
        pylab.plot([0, l], [0, l])
        pylab.xlim(0, l)
        pylab.ylim(0, 1)
        pylab.gray()
        pylab.xlabel("Flux matrix: A(i,j)")
        #        pylab.ylabel("Error matrix: E(i,j)")
        # I'm abusing the 'title' attribute here just to get the x2label where I want it
        pylab.title("Error matrix: E(i,j)")
        print(self.dates)
        datelabels = self.mjd2date(self.dates)
        datelabels.reverse()
        pylab.yticks(arange(len(self.A), 0, -1), (datelabels))
        #        pylab.xticks(arange(len(self.A))+0.5,(datelabels), rotation='vertical')
        #        pylab.yticks(arange(len(self.A)),(self.gooddates))
        #        pylab.xticks(arange(len(self.A)),(self.gooddates))
        pylab.show()
コード例 #26
0
 def test_plot_dist_matrix(self):
     """
     Can we create and possibly plot a dist_matrix?
     """
     try:
         comm = create_comm_of_size(12)
     except InvalidCommSizeError:
         pass
     else:
         try:
             da = densedistarray.DistArray((10, 10),
                                           dist=('c', 'c'),
                                           comm=comm)
         except NullCommError:
             pass
         else:
             if False:
                 if comm.Get_rank() == 0:
                     import pylab
                     pylab.ion()
                     pylab.matshow(a)
                     pylab.colorbar()
                     pylab.draw()
                     pylab.show()
             comm.Free()
コード例 #27
0
def main():
    #from pylab import *
    import pylab

    # Create the gaussian data
    Xin, Yin = pylab.mgrid[0:201, 0:201]
    data = gaussian(3, 100, 100, 20, 40)(Xin, Yin) + np.random.random(
        Xin.shape)

    pylab.matshow(data, cmap='gist_rainbow')

    params = fitgaussian(data)
    fit = gaussian(*params)

    pylab.contour(fit(*pylab.indices(data.shape)), cmap='copper')
    ax = pylab.gca()
    (height, x, y, width_x, width_y) = params

    pylab.text(0.95,
               0.05,
               """
    x : %.1f
    y : %.1f
    width_x : %.1f
    width_y : %.1f""" % (x, y, width_x, width_y),
               fontsize=16,
               horizontalalignment='right',
               verticalalignment='bottom',
               transform=ax.transAxes)

    pylab.show()
コード例 #28
0
    def showConn(self,N,conns):
        matrix = np.zeros((N,N))

        for n in conns:
            matrix[int(n/N),np.remainder(n,N)]=1.0

        plt.matshow(matrix)
        plt.show()
コード例 #29
0
def visualize_row(g, nvis=196, nhid=20, title=''):
    ncols = np.sqrt(nvis).astype(int)

    title = 'vishid'
    vishid = g[nvis+nhid:].reshape((nvis, nhid))
    imgs = [vishid[:, j].reshape((ncols, ncols)) for j in range(nhid)]
    pylab.matshow(vm.pack(imgs), cmap='gray')
    pylab.title(title)
コード例 #30
0
ファイル: minihalo_twoE.py プロジェクト: alexji/chemmix
def plot_mh_ckk(prefix):
    k49max=10;k51max=10
    ckk = np.load('MMIXDISTR/'+prefix+'_cgrid.npy')
    plt.matshow(ckk)
    plt.colorbar()
    plt.xlabel(r'$k_{51}$')
    plt.ylabel(r'$k_{49}$')
    plt.savefig("PLOTS/"+prefix+'_ckk.png')
コード例 #31
0
ファイル: vine_utils.py プロジェクト: necroen/cxphasing
def showNetCDF(filename):
    
    """
    matshows the netcdf in filename
    """
    
    img=readNetCDF(filename,'intensity')
    pyl.matshow(img)
コード例 #32
0
def plot_dist_matrix(name, mec):
    mec.execute('_dm = %s.get_dist_matrix()' % name, 0)
    _dm = mec.zip_pull('_dm', 0)
    import pylab
    pylab.ion()
    pylab.matshow(_dm)
    pylab.colorbar()
    pylab.show()
コード例 #33
0
ファイル: climate-new.py プロジェクト: Freaken/DatVid
def show_gfx(world):
    if VISUAL:
        top=world.max()
        if top>50.0: cscheme=hot
        elif top>0.0: cscheme=temp
        else: cscheme=cold
        pylab.matshow(world, fignum=1, cmap=cscheme)
        pylab.draw()
コード例 #34
0
ファイル: proxy.py プロジェクト: MJones810/distarray
def plot_dist_matrix(name, mec):
    mec.execute('_dm = %s.get_dist_matrix()' % name, 0)
    _dm = mec.zip_pull('_dm', 0)
    import pylab
    pylab.ion()
    pylab.matshow(_dm)
    pylab.colorbar()
    pylab.show()
コード例 #35
0
ファイル: cs180functions.py プロジェクト: enjooblena/cs180mp
def displayResult(keypoints, currentImage):
	pl.ion()
	pl.gray()
	pl.matshow(currentImage)
	for feature in keypoints:
		print feature
		pl.plot(feature[0], feature[1], 'bo')
	pl.show()
コード例 #36
0
def plot_mat(mat, title_, xticks_, yticks_, label_x, label_y, xlabel_, ylabel_, min=None, max=None, type_plot="matshow", format_string="%.3f"):
    def reformat_labels(lab):
        print "label",lab
        print "len(lab)",len(lab)
#        if len(lab)>8:
        if len(lab)>10:
#            q = len(lab)/8 + 1
#            q = int(mdp.numx.ceil(len(lab)/8.))
#            q = int(mdp.numx.floor(len(lab)/8.))
#            q = int(mdp.numx.ceil(len(lab)/10.))
            q = int(mdp.numx.floor(len(lab)/10.))
#            q = int(mdp.numx.ceil(len(lab)/6.))
            print "q:",q
            print "returned:", str([lab[i] for i in range(len(lab)) if i%q==0])
            return ([lab[i] for i in range(len(lab)) if i%q==0],q)
        else:
            return (lab, 1)
    if type_plot=="imshow":
        pl.figure()
        pl.imshow(mat, interpolation='nearest', vmin=min, vmax=max)
    else:
        pl.matshow(mat, vmin=min, vmax=max)
    pl.title(title_+'\n')
    pl.xlabel(xlabel_)
    pl.ylabel(ylabel_)
    if xticks_ is not None:
        pl.xticks = xticks_
    if yticks_ is not None:
        pl.yticks = yticks_
    a = matplotlib.pyplot.gca()
    locs, labels = pl.xticks()
    print "locs, labels",locs, labels
    ## format values on x and y, so that they can be plotted entirely
#    if label_x[0] is float:
    if is_float(label_x[0]):
        label_x = [format_string % x for x in label_x]
    if is_float(label_y[0]):
        label_y = [format_string % x for x in label_y]
    (label_x_r, qx) = reformat_labels(label_x)
    (label_y_r, qy) = reformat_labels(label_y)
    if type_plot=="matshow":
#        l_tmp = [-99999]
#        l_tmp.extend(label_x)
#        l_tmp = label_x
#        print "l_tmp", l_tmp
#        a.set_xticklabels(l_tmp, fontdict=None, minor=False) # set values on x ticks
        pl.xticks( mdp.numx.arange(0.,len(label_x),float(qx)), label_x_r )
#        l_tmp = [-99999]
#        l_tmp.extend(label_y_r)
#        print "l_tmp", l_tmp
#        a.set_yticklabels(l_tmp, fontdict=None, minor=False) # set values on y ticks
        pl.yticks( mdp.numx.arange(0.,len(label_y),float(qy)), label_y_r )
    else:
        a.set_xticklabels(label_x, fontdict=None, minor=False) # set values on x ticks
        a.set_yticklabels(label_y, fontdict=None, minor=False) # set values on y ticks
#    a.xaxis.set_tick()
#    a.xaxis.set_ticklabels()
    pl.colorbar()
コード例 #37
0
ファイル: util.py プロジェクト: zoq/benchmarks
 def VisualizeConfusionMatrix(CM):
   import pylab as pl
   print(CM)
   pl.matshow(CM)
   pl.title('Confusion Matrix')
   pl.colorbar()
   pl.ylabel('True Label')
   pl.xlabel('Predicted Label')
   pl.show()
コード例 #38
0
 def VisualizeConfusionMatrix(CM):
   import pylab as pl
   print(CM)
   pl.matshow(CM)
   pl.title('Confusion Matrix')
   pl.colorbar()
   pl.ylabel('True Label')
   pl.xlabel('Predicted Label')
   pl.show()
コード例 #39
0
def rseed345_basis(info):
    basis = np.loadtxt("results/basis-RGBODGCN-r%s.txt" % info.rseed)
    pl.figure(4)
    pl.matshow(basis.dot(basis.T))
    pl.colorbar()
    pl.title("Similarity matrix.")
    pl.savefig("results/matshow-RGBODGCN-r%s.pdf" % info.rseed)
    #exit(1)
    return basis
コード例 #40
0
ファイル: control.py プロジェクト: ArsEmchik/course_project
 def draw_confusion_matrix(self, function, data_set):
     y_true, y_predict = self.calculate_entire_ds(function, data_set)
     cm = confusion_matrix(y_true, y_predict)
     pl.matshow(cm)
     pl.title('Confusion matrix')
     pl.colorbar()
     pl.ylabel('True label')
     pl.xlabel('Predicted label')
     pl.show()
コード例 #41
0
def decompPCA(data=None,comp=None):
    img = data[:,2:].T
    size = np.sqrt(img.shape[0])
    pca = PCA(n_components=20)
    imgNew = pca.fit_transform(img)
    pl.matshow(imgNew[:,comp-1].reshape(size,size))
    pl.title('The '+str(comp)+' PC')
    pl.colorbar()
    return pca.explained_variance_ratio_
コード例 #42
0
ファイル: gv_gael.py プロジェクト: aniv0s/My-Random-Notebooks
def plot_cor(mat, vmax=None, title=None):
    "Plot correlation matrix"
    if vmax is None:
        vmax = np.max(np.abs(diff))          
    pl.matshow(mat, vmin=-vmax, vmax=vmax, cmap=pl.cm.RdBu_r)
    pl.xticks(range(len(columns)), columns)
    pl.yticks(range(len(columns)), columns)
    if title:
        pl.title(title)
コード例 #43
0
def show_OneDigit(digits, index=0):
	if index>=digits.images.shape[0]:
		print 'index of out of %d' % (images.shape[0])
		return
	import pylab as pl
	print 'label =', digits.target[index]
	pl.gray()
	pl.matshow(digits.images[index])
	pl.show()
コード例 #44
0
ファイル: plots.py プロジェクト: stefanSchinkel/crpy
def showRP(RP):

	pylab.matshow(- RP)
 	ax = pylab.gca() 
 	bottom, top = ax.get_ylim()
	ax.set_ylim(top, bottom)
	pylab.axis('tight')
	pylab.gray()
	pylab.show()
コード例 #45
0
ファイル: plots.py プロジェクト: stefanSchinkel/crpy
def showRP(RP):

    pylab.matshow(-RP)
    ax = pylab.gca()
    bottom, top = ax.get_ylim()
    ax.set_ylim(top, bottom)
    pylab.axis('tight')
    pylab.gray()
    pylab.show()
コード例 #46
0
ファイル: analiza.py プロジェクト: brina123/sentianalysis
def confusion_matrik(y_rocni, y_program):
    cm = confusion_matrix(y_rocni, y_program)
    print cm    
    pl.matshow(cm)
    pl.title('Confusion matrix')
    pl.colorbar()
    pl.ylabel('True label')
    pl.xlabel('Predicted label')
    pl.show()
コード例 #47
0
def forwardTest():
    spikeTimes = spt = [26, 50, 84, 128, 199, 247, 355] 
    P = setupSimData(spt = spikeTimes )
    S = smc.forward(P.V, P)
    
    pylab.figure()
    pylab.plot(P.V.F)
    pylab.title('Simulated Fluorescence')
    

    cbar = numpy.zeros(P.V.T)
    nbar = numpy.zeros(P.V.T)
    
    for t in xrange(P.V.T):
        for i in xrange(P.V.Nparticles):
            weight = S.w_f[i,t]
            cbar[t] += weight * S.C[i,t]
            nbar[t] += weight * S.n[i,t]
    
    #cbar /= P.V.Nparticles
    #nbar /= P.V.Nparticles
    
    pylab.figure()
    pylab.hold(True)
    pylab.title('expected Ca vs arbitrary particles')
    pylab.plot(S.C[3,:], label='particle 3')
    pylab.plot(S.C[10,:], label='particle 10')
    pylab.plot(S.C[20,:], label='particle 20')
    pylab.plot(cbar, label='E[C]')
    pylab.plot(spikeTimes, 6+numpy.ones(len(spikeTimes)), 'k.', label='simulated spike times')

    pylab.legend()
    
    #print(nbar.shape)
    pylab.figure()
    pylab.hold(True)
    pylab.plot(nbar, label='expected spikes')
    pylab.plot(spikeTimes, 0.5*numpy.ones(len(spikeTimes)), 'k.', label='simulated spike times')
    pylab.legend()
    pylab.title('spike detection')
    

    #pylab.figure()
    pylab.matshow(S.w_f)
    pylab.title('min s.w_f %f , max s.w_f: %f'%(numpy.min(S.w_f), numpy.max(S.w_f)))
    
    
    pylab.figure()
    pylab.hold(True)
    pylab.plot(S.w_f[3,:], label='particle 3')
    pylab.plot(S.w_f[10,:], label='particle 10')
    pylab.plot(S.w_f[20,:], label='particle 20')
    pylab.legend()
    pylab.title('individual particle weights')
    
    pylab.show()
コード例 #48
0
def curve_densities(_data, bins=40):
    bins_mult = bins / _data.max()
    density_matrix = S.zeros((bins + 1, _data.shape[1]))
    for row in _data:
        for j in range(len(row)):
            density_matrix[S.floor(row[j] * bins_mult), j] += 1.0
    density_matrix[density_matrix == 0.0] = float("-inf")

    density_figure = pylab.figure()
    pylab.matshow(density_matrix[::-1])
コード例 #49
0
 def heatmap(self, N=None, standardize=True, log=False):
     if standardize:
         data_df = self.standardize_df(self.data_df, log=log)
     else:
         data_df = self.data_df
     if N is not None:
         plt.matshow(data_df[0:N])
     else:
         plt.matshow(data_df)
     plt.colorbar()
コード例 #50
0
 def test_plot_dist_matrix(self):
     """Can we create and possibly plot a dist_matrix?"""
     la = da.LocalArray((10,10), dist=('c','c'), comm=self.comm)
     if self.comm.Get_rank() == 0:
         import pylab
         pylab.ion()
         pylab.matshow(la)
         pylab.colorbar()
         pylab.draw()
         pylab.show()
コード例 #51
0
ファイル: viz_vidtools.py プロジェクト: brantp/video_analysis
def get_crop_config_show(vid,fignum=1):
	'''given a video, display crop keyframe and return empty cropdict'''
	fr = vidtools.extract_keyframe(vid)
	pylab.close(fignum)
	pylab.matshow(fr,fignum=fignum)
	these_inds = re.split('[-_](\d)[-_]',os.path.basename(os.path.dirname(vid)))
	print >> sys.stderr, '\nZoom on antfarms and store crops, e.g.'
	for af,ind in zip(these_inds[1::2],these_inds[2::2]):
		print >> sys.stderr, "antfarm %s: cropsdict['%s'] = viz_vidtools.current_view_crop(%s,fr.shape)" % (af,ind,fignum)
	return {},fr
コード例 #52
0
    def visualize_components(self, title=None):
        """Visualize the learned components. Each of the images shows the Bernoulli parameters
        (probability of the pixel being 1) for one of the mixture components."""

        pylab.figure('Mixture components')
        pylab.matshow(util.arrange(self.params.theta.reshape((-1, IMAGE_DIM, IMAGE_DIM))),
                      fignum=False, cmap='gray')
        if title is None:
            title = 'Mixture components'
        pylab.title(title)
        pylab.draw()
コード例 #53
0
def plotsolution(post):
    import pylab
    X = np.unique(post[0])
    Y = np.unique(post[1])
    Z = np.zeros((len(X), len(Y)))
    sparseZ = dict(zip(map(tuple, post[:2].T), post[2]))
    for x in range(len(X)):
        for y in range(len(Y)):
            if (X[x], Y[y]) in sparseZ.keys():
                Z[x, y] = sparseZ[(X[x], Y[y])]
    pylab.matshow(Z)
コード例 #54
0
def test_results(y, y_res, lbl, algo = ''):
    cm = confusion_matrix(y, y_res, labels=lbl)
    cm = cm / cm.astype(np.float).sum(axis=1)
    print classification_report(y, y_res, labels=lbl)

    # Show confusion matrix in a separate window
    pl.matshow(cm)
    pl.title('Confusion matrix')
    pl.colorbar()
    pl.ylabel('True label')
    pl.xlabel('Predicted label')
    pl.savefig('/home/rolf/Desktop/Assignment 6/plots/matching/%s.pdf' % algo)