当前位置: 首页>>代码示例>>Python>>正文


Python pylab.close方法代码示例

本文整理汇总了Python中pylab.close方法的典型用法代码示例。如果您正苦于以下问题:Python pylab.close方法的具体用法?Python pylab.close怎么用?Python pylab.close使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pylab的用法示例。


在下文中一共展示了pylab.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: output_groups

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import close [as 别名]
def output_groups(tcs, alpha, mis, column_label, direction, thresh=0, prefix=''):
    f = safe_open(prefix + '/groups.txt', 'w+')
    h = safe_open(prefix + '/topics.txt', 'w+')
    m, nv = mis.shape
    annotate = lambda q, s: q if s >= 0 else '~' + q
    for j in range(m):
        f.write('Group num: %d, TC(X;Y_j): %0.3f\n' % (j, tcs[j]))
        # inds = np.where(alpha[j] * mis[j] > thresh)[0]
        inds = np.where(alpha[j] >= 1.)[0]
        inds = inds[np.argsort(-alpha[j, inds] * mis[j, inds])]
        for ind in inds:
            f.write(column_label[ind] + u', %0.3f, %0.3f, %0.3f\n' % (
                mis[j, ind], alpha[j, ind], mis[j, ind] * alpha[j, ind]))
        #h.write(unicode(j) + u':' + u','.join([annotate(column_label[ind], direction[j,ind]) for ind in inds[:10]]) + u'\n')
        h.write(str(j) + u':' + u','.join(
            [annotate(column_label[ind], direction[j, ind]) for ind in inds[:10]]) + u'\n')
    f.close()
    h.close() 
开发者ID:gregversteeg,项目名称:corex_topic,代码行数:20,代码来源:vis_topic.py

示例2: save_PTZ_metric2disk

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import close [as 别名]
def save_PTZ_metric2disk(metrics,save_path):

    import json
    #metric_dict= {}
    recall_ = list(metrics['metric']['recall'])
    precision_ = list(metrics['metric']['precision'])
    f_score = metrics['metric']['MaxF']
    try:
        iu = metrics['metric']['iu']
    except KeyError:
        iu = 0.0
    cont_embedding = metrics['contrast_embedding']
    metric_ = {'recall':recall_,'precision':precision_,'f-score':f_score,'iu':iu,
               'contrast_embedding':cont_embedding}
    file_ = open(save_path + '/metric.json', 'w')
    file_.write(json.dumps(metric_, ensure_ascii=False, indent=2))
    file_.close() 
开发者ID:gmayday1997,项目名称:SceneChangeDet,代码行数:19,代码来源:metric.py

示例3: save_metric2disk

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import close [as 别名]
def save_metric2disk(metrics,save_path):

    import json
    length = len(metrics)
    metric_dict= {}
    for i in range(length):
        recall_ = list(metrics[i]['metric']['recall'])
        name = metrics[i]['name']
        precision_ = list(metrics[i]['metric']['precision'])
        f_score = metrics[i]['metric']['MaxF']
        try:
            iu = metrics[i]['metric']['iu']
        except KeyError:
            iu = 0.0
        metric_ = {'name':name,'recall':recall_,'precision':precision_,'f-score':f_score,'iu':iu}
        metric_dict.setdefault(i,metric_)

    file_ = open(save_path + '/metric.json', 'w')
    file_.write(json.dumps(metric_dict, ensure_ascii=False, indent=2))
    file_.close() 
开发者ID:gmayday1997,项目名称:SceneChangeDet,代码行数:22,代码来源:metric.py

示例4: on_epoch_end

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import close [as 别名]
def on_epoch_end(self, epoch, logs={}):
        self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch)))
        self.show_edit_distance(256)
        word_batch = next(self.text_img_gen)[0]
        res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])
        if word_batch['the_input'][0].shape[0] < 256:
            cols = 2
        else:
            cols = 1
        for i in range(self.num_display_words):
            pylab.subplot(self.num_display_words // cols, cols, i + 1)
            if K.image_data_format() == 'channels_first':
                the_input = word_batch['the_input'][i, 0, :, :]
            else:
                the_input = word_batch['the_input'][i, :, :, 0]
            pylab.imshow(the_input.T, cmap='Greys_r')
            pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
        fig = pylab.gcf()
        fig.set_size_inches(10, 13)
        pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch)))
        pylab.close() 
开发者ID:hello-sea,项目名称:DeepLearning_Wavelet-LSTM,代码行数:23,代码来源:image_ocr.py

示例5: save

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import close [as 别名]
def save(GUI):
    global txtResultPath
    if GUI:
        import pylab as pl
        import nest.raster_plot
        import nest.voltage_trace
        logger.debug("Saving IMAGES into {0}".format(SAVE_PATH))
        for key in spikedetectors:
            try:
                nest.raster_plot.from_device(spikedetectors[key], hist=True)
                pl.savefig(f_name_gen(SAVE_PATH, "spikes_" + key.lower()), dpi=dpi_n, format='png')
                pl.close()
            except Exception:
                print(" * * * from {0} is NOTHING".format(key))
    txtResultPath = SAVE_PATH + 'txt/'
    logger.debug("Saving TEXT into {0}".format(txtResultPath))
    if not os.path.exists(txtResultPath):
        os.mkdir(txtResultPath)
    for key in spikedetectors:
        save_spikes(spikedetectors[key], name=key)
    with open(txtResultPath + 'timeSimulation.txt', 'w') as f:
        for item in times:
            f.write(item) 
开发者ID:research-team,项目名称:NEUCOGAR,代码行数:25,代码来源:func.py

示例6: save_voltage

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import close [as 别名]
def save_voltage(multimeters):
    import h5py

    print "Write to HDF5 file"
    filename = "voltage.hdf5"
    timestamp = datetime.datetime.now()

    with h5py.File(filename, "w") as f:
        f.attrs['default'] = 'entry'
        f.attrs['file_name'] = filename
        f.attrs['file_time'] = str(timestamp)

        f.create_dataset(key, data=nest.GetStatus(multimeters[key], "events")[0]["V_m"])
        f.close()
    print "wrote file:", filename
    # title = "Membrane potential"
    # ev = nest.GetStatus(detec, "events")[0]
    # with open("{0}@voltage_{1}.txt".format(txt_result_path, name), 'w') as f:
    #    f.write("Name: {0}, Title: {1}\n".format(name, title))
    #    print int(T / multimeter_param['interval'])
    #    for line in range(0, int(T / multimeter_param['interval'])):
    #        for index in range(0, N_volt):
    #            print "{0} {1} ".format(ev["times"][line], ev["V_m"][line])
    #        #f.write("\n")
    #        print "\n" 
开发者ID:research-team,项目名称:NEUCOGAR,代码行数:27,代码来源:output.py

示例7: save_voltage

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import close [as 别名]
def save_voltage(multimeters):
    import h5py

    print "Write to HDF5 file"
    filename = "voltage.hdf5"
    timestamp = datetime.datetime.now()

    with h5py.File(filename, "w") as f:
        f.attrs['default'] = 'entry'
        f.attrs['file_name'] = filename
        f.attrs['file_time'] = str(timestamp)

        f.create_dataset(key, data=nest.GetStatus(multimeters[key], "events")[0]["V_m"])
        f.close()
    print "wrote file:", filename
    #title = "Membrane potential"
    #ev = nest.GetStatus(detec, "events")[0]
    #with open("{0}@voltage_{1}.txt".format(txt_result_path, name), 'w') as f:
    #    f.write("Name: {0}, Title: {1}\n".format(name, title))
    #    print int(T / multimeter_param['interval'])
    #    for line in range(0, int(T / multimeter_param['interval'])):
    #        for index in range(0, N_volt):
    #            print "{0} {1} ".format(ev["times"][line], ev["V_m"][line])
    #        #f.write("\n")
    #        print "\n" 
开发者ID:research-team,项目名称:NEUCOGAR,代码行数:27,代码来源:func.py

示例8: output_groups

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import close [as 别名]
def output_groups(tcs, alpha, mis, column_label, thresh=0, prefix=''):
    f = safe_open(prefix + '/text_files/groups.txt', 'w+')
    g = safe_open(prefix + '/text_files/groups_no_overlaps.txt', 'w+')
    m, nv = mis.shape
    for j in range(m):
        f.write('Group num: %d, TC(X;Y_j): %0.3f\n' % (j, tcs[j]))
        g.write('Group num: %d, TC(X;Y_j): %0.3f\n' % (j, tcs[j]))
        inds = np.where(alpha[j] * mis[j] > thresh)[0]
        inds = inds[np.argsort(-alpha[j, inds] * mis[j, inds])]
        for ind in inds:
            f.write(column_label[ind] + ', %0.3f, %0.3f, %0.3f\n' % (
                mis[j, ind], alpha[j, ind], mis[j, ind] * alpha[j, ind]))
        inds = np.where(alpha[j] == 1)[0]
        inds = inds[np.argsort(- mis[j, inds])]
        for ind in inds:
            g.write(column_label[ind] + ', %0.3f\n' % mis[j, ind])
    f.close()
    g.close() 
开发者ID:gregversteeg,项目名称:bio_corex,代码行数:20,代码来源:vis_corex.py

示例9: plot_convergence

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import close [as 别名]
def plot_convergence(history, prefix='', prefix2=''):
    plt.figure(figsize=(8, 5))
    ax = plt.subplot(111)

    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()

    plt.plot(history["TC"], '-', lw=2.5, color=tableau20[0])
    x = len(history["TC"])
    y = np.max(history["TC"])
    plt.text(0.5 * x, 0.8 * y, "TC", fontsize=18, fontweight='bold', color=tableau20[0])

    if "additivity" in history:
        plt.plot(history["additivity"], '-', lw=2.5, color=tableau20[1])
        plt.text(0.5 * x, 0.3 * y, "additivity", fontsize=18, fontweight='bold', color=tableau20[1])

    plt.ylabel('TC', fontsize=12, fontweight='bold')
    plt.xlabel('# Iterations', fontsize=12, fontweight='bold')
    plt.suptitle('Convergence', fontsize=12)
    filename = '{}/summary/convergence{}.pdf'.format(prefix, prefix2)
    if not os.path.exists(os.path.dirname(filename)):
        os.makedirs(os.path.dirname(filename))
    plt.savefig(filename, bbox_inches="tight")
    plt.close('all')
    return True 
开发者ID:gregversteeg,项目名称:LinearCorex,代码行数:27,代码来源:vis_corex.py

示例10: plot_heatmaps

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import close [as 别名]
def plot_heatmaps(data, mis, column_label, cont, topk=30, prefix=''):
    cmap = sns.cubehelix_palette(as_cmap=True, light=.9)
    m, nv = mis.shape
    for j in range(m):
        inds = np.argsort(- mis[j, :])[:topk]
        if len(inds) >= 2:
            plt.clf()
            order = np.argsort(cont[:,j])
            subdata = data[:, inds][order].T
            subdata -= np.nanmean(subdata, axis=1, keepdims=True)
            subdata /= np.nanstd(subdata, axis=1, keepdims=True)
            columns = [column_label[i] for i in inds]
            sns.heatmap(subdata, vmin=-3, vmax=3, cmap=cmap, yticklabels=columns, xticklabels=False, mask=np.isnan(subdata))
            filename = '{}/heatmaps/group_num={}.png'.format(prefix, j)
            if not os.path.exists(os.path.dirname(filename)):
                os.makedirs(os.path.dirname(filename))
            plt.title("Latent factor {}".format(j))
            plt.yticks(rotation=0)
            plt.savefig(filename, bbox_inches='tight')
            plt.close('all')
            #plot_rels(data[:, inds], map(lambda q: column_label[q], inds), colors=cont[:, j],
            #          outfile=prefix + '/relationships/group_num=' + str(j), latent=labels[:, j], alpha=0.1) 
开发者ID:gregversteeg,项目名称:LinearCorex,代码行数:24,代码来源:vis_corex.py

示例11: plot

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import close [as 别名]
def plot(t, plots, shot_ind):
    n = len(plots)

    for i in range(0,n):
        label, data = plots[i]

        plt = py.subplot(n, 1, i+1)
        plt.tick_params(labelsize=8)
        py.grid()
        py.xlim([t[0], t[-1]])
        py.ylabel(label)

        py.plot(t, data, 'k-')
        py.scatter(t[shot_ind], data[shot_ind], marker='*', c='g')

    py.xlabel("Time")
    py.show()
    py.close() 
开发者ID:sealneaward,项目名称:nba-movement-data,代码行数:20,代码来源:fix_shot_times.py

示例12: draw_graph_row

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import close [as 别名]
def draw_graph_row(graphs,
                   index=0,
                   contract=True,
                   n_graphs_per_line=5,
                   size=4,
                   xlim=None,
                   ylim=None,
                   **args):
    """draw_graph_row."""
    dim = len(graphs)
    size_y = size
    size_x = size * n_graphs_per_line * args.get('size_x_to_y_ratio', 1)
    plt.figure(figsize=(size_x, size_y))

    if xlim is not None:
        plt.xlim(xlim)
        plt.ylim(ylim)
    else:
        plt.xlim(xmax=3)

    for i in range(dim):
        plt.subplot(1, n_graphs_per_line, i + 1)
        graph = graphs[i]
        draw_graph(graph,
                   size=None,
                   pos=graph.graph.get('pos_dict', None),
                   **args)
    if args.get('file_name', None) is None:
        plt.show()
    else:
        row_file_name = '%d_' % (index) + args['file_name']
        plt.savefig(row_file_name,
                    bbox_inches='tight',
                    transparent=True,
                    pad_inches=0)
        plt.close() 
开发者ID:fabriziocosta,项目名称:EDeN,代码行数:38,代码来源:__init__.py

示例13: saveBEVImageWithAxes

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import close [as 别名]
def saveBEVImageWithAxes(data, outputname, cmap = None, xlabel = 'x [m]', ylabel = 'z [m]', rangeX = [-10, 10], rangeXpx = None, numDeltaX = 5, rangeZ = [7, 62], rangeZpx = None, numDeltaZ = 5, fontSize = 16):
    '''
    
    :param data:
    :param outputname:
    :param cmap:
    '''
    aspect_ratio = float(data.shape[1])/data.shape[0]
    fig = pylab.figure()
    Scale = 8
    # add +1 to get axis text
    fig.set_size_inches(Scale*aspect_ratio+1,Scale*1)
    ax = pylab.gca()
    #ax.set_axis_off()
    #fig.add_axes(ax)
    if cmap != None:
        pylab.set_cmap(cmap)
    
    #ax.imshow(data, interpolation='nearest', aspect = 'normal')
    ax.imshow(data, interpolation='nearest')
    
    if rangeXpx == None:
        rangeXpx = (0, data.shape[1])
    
    if rangeZpx == None:
        rangeZpx = (0, data.shape[0])
        
    modBev_plot(ax, rangeX, rangeXpx, numDeltaX, rangeZ, rangeZpx, numDeltaZ, fontSize, xlabel = xlabel, ylabel = ylabel)
    #plt.savefig(outputname, bbox_inches='tight', dpi = dpi)
    pylab.savefig(outputname, dpi = data.shape[0]/Scale)
    pylab.close()
    fig.clear() 
开发者ID:MarvinTeichmann,项目名称:KittiSeg,代码行数:34,代码来源:helper.py

示例14: test_bayesian_mnist

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import close [as 别名]
def test_bayesian_mnist(self):
        import pylab as plt

        # Create a astroNN neural network instance and set the basic parameter
        net = MNIST_BCNN()
        net.task = 'classification'
        net.callbacks = ErrorOnNaN()
        net.max_epochs = 1

        # Train the neural network
        net.train(x_train, y_train)
        net.save('mnist_bcnn_test')
        net.plot_dense_stats()
        plt.close()  # Travis-CI memory error??
        net.evaluate(x_test, utils.to_categorical(y_test, 10))

        pred, pred_err = net.test(x_test)
        test_num = y_test.shape[0]
        assert (np.sum(pred == y_test)) / test_num > 0.9  # assert accuracy

        net_reloaded = load_folder("mnist_bcnn_test")
        net_reloaded.mc_num = 3  # prevent memory issue on Tavis CI
        prediction_loaded = net_reloaded.test(x_test[:200])

        net_reloaded.folder_name = None  # set to None so it can be saved
        net_reloaded.save()

        load_folder(net_reloaded.folder_name)  # ignore pycharm warning, its not None 
开发者ID:henrysky,项目名称:astroNN,代码行数:30,代码来源:test_models.py

示例15: explorer

# 需要导入模块: import pylab [as 别名]
# 或者: from pylab import close [as 别名]
def explorer():
    for c in range(0, len(captchas), 77):
        e = del_line(captchas[c])
        pl.figure(c)
        for i, p in enumerate(split_pic(e)):
            pl.subplot(221+i)
            char = e[:, p[0]:p[1]]
            y1, y2 = split_y(char)
            pl.imshow(regularize(char[y1:y2, :]), cmap=pl.cm.Greys)
        pl.show()
        if raw_input() == 'q':
            pl.close('all')
            break 
开发者ID:leonhx,项目名称:njucaptcha,代码行数:15,代码来源:preprocess.py


注:本文中的pylab.close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。