Python matplotlib.pyplot.title() Examples

The following are code examples for showing how to use matplotlib.pyplot.title(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: fenics-topopt   Author: zfergus   File: stress_gui.py    MIT License 7 votes vote down vote up
def update(self, xPhys, u, title=None):
        """Plot to screen"""
        self.im.set_array(-xPhys.reshape((self.nelx, self.nely)).T)
        stress = self.stress_calculator.calculate_stress(xPhys, u, self.nu)
        # self.stress_calculator.calculate_fdiff_stress(xPhys, u, self.nu)
        self.myColorMap.set_norm(colors.Normalize(vmin=0, vmax=max(stress)))
        stress_rgba = self.myColorMap.to_rgba(stress)
        stress_rgba[:, :, 3] = xPhys.reshape(-1, 1)
        self.stress_im.set_array(np.swapaxes(
            stress_rgba.reshape((self.nelx, self.nely, 4)), 0, 1))
        self.fig.canvas.draw()
        self.fig.canvas.flush_events()
        if title is not None:
            plt.title(title)
        else:
            plt.xlabel("Max stress = {:.2f}".format(max(stress)[0]))
        plt.pause(0.01) 
Example 2
Project: keras-anomaly-detection   Author: chen0040   File: plot_utils.py    MIT License 7 votes vote down vote up
def visualize_anomaly(y_true, reconstruction_error, threshold):
    error_df = pd.DataFrame({'reconstruction_error': reconstruction_error,
                             'true_class': y_true})
    print(error_df.describe())

    groups = error_df.groupby('true_class')
    fig, ax = plt.subplots()

    for name, group in groups:
        ax.plot(group.index, group.reconstruction_error, marker='o', ms=3.5, linestyle='',
                label="Fraud" if name == 1 else "Normal")

    ax.hlines(threshold, ax.get_xlim()[0], ax.get_xlim()[1], colors="r", zorder=100, label='Threshold')
    ax.legend()
    plt.title("Reconstruction error for different classes")
    plt.ylabel("Reconstruction error")
    plt.xlabel("Data point index")
    plt.show() 
Example 3
Project: beta3_IRT   Author: yc14600   File: plots.py    MIT License 7 votes vote down vote up
def plot_item_parameters_corr(irt_prob_avg,difficulty,noise,disc=None):
    sns.set_context('paper')
    cls = sns.color_palette("BuGn_r")
    lgd = []

    f = plt.figure()
    plt.xlim([0.,1.])
    plt.ylim([0.,1.])
    
    
    plt.scatter(irt_prob_avg[noise>0],difficulty[noise>0],c=cls[3],s=60)
    lgd.append('noise item')
    if not disc is None:
        plt.scatter(irt_prob_avg[disc<0],difficulty[disc<0],c=cls[0],marker='+',facecolors='none')
        lgd.append('detected noise item')
    plt.scatter(irt_prob_avg[noise==0],difficulty[noise==0],facecolors='none',edgecolors='k',s=60)
    lgd.append('non-noise item')

    plt.title('Correlation between difficulty and response')
    plt.xlabel('Average response',fontsize=14)
    plt.ylabel('Difficulty',fontsize=14)
    l=plt.legend(lgd,frameon=True,fontsize=12)
    l.get_frame().set_edgecolor('g')
    return f 
Example 4
Project: PEAKachu   Author: tbischler   File: window.py    ISC License 6 votes vote down vote up
def _plot_initial_windows(self, unsig_base_means, unsig_fcs,
                              sig_base_means, sig_fcs):
        # create plot folder if it does not exist
        plot_folder = "{}/plots".format(self._output_folder)
        if not exists(plot_folder):
            makedirs(plot_folder)
        # MA plot
        plt.plot(np.log10(unsig_base_means),
                 np.log2(unsig_fcs), ".",
                 markersize=2.0, alpha=0.3)
        plt.plot(np.log10(sig_base_means),
                 np.log2(sig_fcs), ".",
                 markersize=2.0, color="red", alpha=0.3)
        plt.axhline(y=np.median(np.log2(unsig_fcs.append(sig_fcs))))
        plt.axvline(x=np.median(np.log10(unsig_base_means.append(
                                         sig_base_means))))
        plt.title("Initial_windows_MA_plot")
        plt.xlabel("log10 base mean")
        plt.ylabel("log2 fold-change")
        plt.savefig("{}/Initial_windows_MA_plot.png".format(plot_folder),
                    dpi=600)
        plt.close()
        # HexBin plot
        df = pd.DataFrame({'log10 base mean': np.log10(unsig_base_means.append(
            sig_base_means)), 'log2 fold-change': np.log2(unsig_fcs.append(
                sig_fcs))})
        df.plot(kind='hexbin', x='log10 base mean',
                y='log2 fold-change', gridsize=50, bins='log')
        plt.axhline(y=np.median(np.log2(unsig_fcs.append(sig_fcs))))
        plt.axvline(x=np.median(np.log10(unsig_base_means.append(
                                         sig_base_means))))
        plt.title("Initial_windows_HexBin_plot")
        plt.savefig("{}/Initial_windows_HexBin_plot.pdf".format(plot_folder))
        plt.close() 
Example 5
Project: OpenAPS   Author: medicinexlab   File: oldpred.py    MIT License 6 votes vote down vote up
def _get_old_pred(bg_df, start_index, end_index, num_pred_minutes):
    #The number of 5 minute sections until the prediction (e.g. 30 minutes = 6 sections)
    pred_array_index = num_pred_minutes / DATA_SPACING

    actual_bg_array, actual_bg_time_array, eventual_pred_array, eventual_pred_time_array, iob_pred_array, iob_pred_time_array, cob_pred_array, cob_pred_time_array, acob_pred_array, acob_pred_time_array = _get_raw_pred_array(bg_df, start_index, end_index, pred_array_index)

    eventual_pred_data = _find_compare_array(actual_bg_array, actual_bg_time_array, eventual_pred_array, eventual_pred_time_array, 30)
    iob_pred_data = _find_compare_array(actual_bg_array, actual_bg_time_array, iob_pred_array, iob_pred_time_array, num_pred_minutes)
    cob_pred_data= _find_compare_array(actual_bg_array, actual_bg_time_array, cob_pred_array, cob_pred_time_array, num_pred_minutes)
    acob_pred_data = _find_compare_array(actual_bg_array, actual_bg_time_array, acob_pred_array, acob_pred_time_array, num_pred_minutes)

    return eventual_pred_data, iob_pred_data, cob_pred_data, acob_pred_data


#Plots old pred data given namedtuple of old data (eventualBG, acob, cob, or iob).
#Can show or save prediction plot based on show_pred_plot or save_pred_plot, respectively.
#Same goes for the Clarke Error grid with show_clarke_plot or save_clarke_plot, respectively.
#id_str, algorithm_str, minutes_str are strings of the ID, the prediction algorithm and the number of prediction minutes used for the title. 
Example 6
Project: dc_tts   Author: Kyubyong   File: utils.py    Apache License 2.0 6 votes vote down vote up
def plot_alignment(alignment, gs, dir=hp.logdir):
    """Plots the alignment.

    Args:
      alignment: A numpy array with shape of (encoder_steps, decoder_steps)
      gs: (int) global step.
      dir: Output path.
    """
    if not os.path.exists(dir): os.mkdir(dir)

    fig, ax = plt.subplots()
    im = ax.imshow(alignment)

    fig.colorbar(im)
    plt.title('{} Steps'.format(gs))
    plt.savefig('{}/alignment_{}.png'.format(dir, gs), format='png')
    plt.close(fig) 
Example 7
Project: Kaggle-Statoil-Challenge   Author: adodd202   File: utils.py    MIT License 6 votes vote down vote up
def __init__(self, fpath, title=None, resume=False):
        self.file = None
        self.resume = resume
        self.title = '' if title == None else title
        if fpath is not None:
            if resume:
                self.file = open(fpath, 'r')
                name = self.file.readline()
                self.names = name.rstrip().split('\t')
                self.numbers = {}
                for _, name in enumerate(self.names):
                    self.numbers[name] = []

                for numbers in self.file:
                    numbers = numbers.rstrip().split('\t')
                    for i in range(0, len(numbers)):
                        self.numbers[self.names[i]].append(numbers[i])
                self.file.close()
                self.file = open(fpath, 'a')
            else:
                self.file = open(fpath, 'w') 
Example 8
Project: neural-fingerprinting   Author: StephanZheng   File: util.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def compute_roc(y_true, y_pred, plot=False):
    """
    TODO
    :param y_true: ground truth
    :param y_pred: predictions
    :param plot:
    :return:
    """
    fpr, tpr, _ = roc_curve(y_true, y_pred)
    auc_score = auc(fpr, tpr)
    if plot:
        plt.figure(figsize=(7, 6))
        plt.plot(fpr, tpr, color='blue',
                 label='ROC (AUC = %0.4f)' % auc_score)
        plt.legend(loc='lower right')
        plt.title("ROC Curve")
        plt.xlabel("FPR")
        plt.ylabel("TPR")
        plt.show()

    return fpr, tpr, auc_score 
Example 9
Project: neural-fingerprinting   Author: StephanZheng   File: util.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def compute_roc_rfeinman(probs_neg, probs_pos, plot=False):
    """
    TODO
    :param probs_neg:
    :param probs_pos:
    :param plot:
    :return:
    """
    probs = np.concatenate((probs_neg, probs_pos))
    labels = np.concatenate((np.zeros_like(probs_neg), np.ones_like(probs_pos)))
    fpr, tpr, _ = roc_curve(labels, probs)
    auc_score = auc(fpr, tpr)
    if plot:
        plt.figure(figsize=(7, 6))
        plt.plot(fpr, tpr, color='blue',
                 label='ROC (AUC = %0.4f)' % auc_score)
        plt.legend(loc='lower right')
        plt.title("ROC Curve")
        plt.xlabel("FPR")
        plt.ylabel("TPR")
        plt.show()

    return fpr, tpr, auc_score 
Example 10
Project: tensorflow-DeepFM   Author: ChenglongChen   File: main.py    MIT License 6 votes vote down vote up
def _plot_fig(train_results, valid_results, model_name):
    colors = ["red", "blue", "green"]
    xs = np.arange(1, train_results.shape[1]+1)
    plt.figure()
    legends = []
    for i in range(train_results.shape[0]):
        plt.plot(xs, train_results[i], color=colors[i], linestyle="solid", marker="o")
        plt.plot(xs, valid_results[i], color=colors[i], linestyle="dashed", marker="o")
        legends.append("train-%d"%(i+1))
        legends.append("valid-%d"%(i+1))
    plt.xlabel("Epoch")
    plt.ylabel("Normalized Gini")
    plt.title("%s"%model_name)
    plt.legend(legends)
    plt.savefig("./fig/%s.png"%model_name)
    plt.close()


# load data 
Example 11
Project: DOTA_models   Author: ringringyi   File: plot_lfads.py    Apache License 2.0 6 votes vote down vote up
def plot_time_series(vals_bxtxn, bidx=None, n_to_plot=np.inf, scale=1.0,
                     color='r', title=None):

  if bidx is None:
    vals_txn = np.mean(vals_bxtxn, axis=0)
  else:
    vals_txn = vals_bxtxn[bidx,:,:]

  T, N = vals_txn.shape
  if n_to_plot > N:
    n_to_plot = N

  plt.plot(vals_txn[:,0:n_to_plot] + scale*np.array(range(n_to_plot)),
           color=color, lw=1.0)
  plt.axis('tight')
  if title:
    plt.title(title) 
Example 12
Project: Pathfinder   Author: MatthewBCooke   File: Pathfinder.py    GNU General Public License v3.0 6 votes vote down vote up
def otherROI(self):
        logging.debug("Opening ROI menu")
        self.entries = []
        number = 0
        self.top4 = Toplevel(root)  # we set this to be the top
        self.canvas = Canvas(self.top4, width=500, height=200)
        self.vsb = Scrollbar(self.top4, orient="vertical", command=self.canvas.yview)
        self.canvas.configure(bg="white", yscrollcommand=self.vsb.set)
        self.add_button = Button(self.top4, text="Add Goal", command=self.addROI)
        self.saveButton = Button(self.top4, text="Save", command=self.saveROI)
        self.saveButton.config(width = 10)
        self.add_button.config(width = 10)
        self.container = Frame(self.top4)
        self.canvas.create_window(0,0,anchor="nw",window=self.container)
        Label(self.top4, text="Settings", bg="white", fg="red").pack(side="top") # we title it
        self.add_button.pack(side="top")
        self.vsb.pack(side="right", fill="y")
        self.canvas.pack(side="left", fill="both", expand=True)
        self.saveButton.pack(side="bottom") 
Example 13
Project: beta3_IRT   Author: yc14600   File: plots.py    MIT License 6 votes vote down vote up
def plot_noisy_points(xtest, disc=None):
    sns.set_context('paper')
    cls = sns.color_palette("BuGn_r")
    lgd = []
    f = plt.figure()
    
    plt.scatter(xtest.x[xtest.noise==0],xtest.y[xtest.noise==0],facecolors='none',edgecolors='k',s=60)
    lgd.append('non-noise item')
    plt.scatter(xtest.x[xtest.noise>0],xtest.y[xtest.noise>0],c=cls[3],s=60)
    lgd.append('noise item')
    if not disc is None:
        plt.scatter(xtest.x[disc<0],xtest.y[disc<0],c=cls[0],marker='+',facecolors='none')
        lgd.append('detected noise item')
    
    plt.title('True and detected noise items')
    l = plt.legend(lgd,frameon=True,fontsize=12)
    l.get_frame().set_edgecolor('g')
    return f 
Example 14
Project: beta3_IRT   Author: yc14600   File: plots.py    MIT License 6 votes vote down vote up
def vis_performance(gather_prec,gather_recal,path,asd='[email protected]',vtype='nfrac'):
    fig = plt.figure()      
    plt.plot(gather_recal.index, gather_recal.mean(axis=1),marker='o')
    plt.plot(gather_prec.index, gather_prec.mean(axis=1),marker='^')

    plt.errorbar(gather_recal.index, gather_recal.mean(axis=1), gather_recal.std(axis=1), linestyle='None')
    plt.errorbar(gather_prec.index, gather_prec.mean(axis=1), gather_prec.std(axis=1), linestyle='None')
    
    if vtype=='nfrac':
        plt.title('Precision and recall under different noise fractions')
        plt.xlabel('Noise fraction (percentile)')
        plt.ylim(-0.05,1.1)
        plt.yticks(np.arange(0,1.2,0.2))
        plt.legend(['Recall','Precision'],loc=0)
        plt.savefig(path+'gathered_dnoise_performance_nfrac_'+asd+'.pdf') 
    elif vtype=='astd':
        plt.title('Precision and recall under different prior SD')
        plt.xlabel('Prior standard deviation of discrimination')
        plt.xlim(0.5,3.25)
        plt.ylim(-0.05,1.1)
        plt.yticks(np.arange(0,1.2,0.2))
        plt.legend(['Recall','Precision'],loc=0)
        plt.savefig(path+'gathered_dnoise_performance_asd_nfrac20.pdf')
    plt.close(fig) 
Example 15
Project: procgen   Author: juancroldan   File: simplex.py    Apache License 2.0 6 votes vote down vote up
def simplex2D_subjective():
	print("Displaying 2D simplex output")
	N = 100
	pmap = [[combined(simplex2D, x / N, y / N) for x in range(N)] for y in range(N)]

	plt.subplot(221)
	plt.title("6 octaves")
	plt.imshow(pmap, cmap='plasma', interpolation='nearest')

	plt.subplot(222)
	plt.title("1 octave")
	pmap = [[combined(simplex2D, 6 * x / N, 6 * y / N, octaves=1) for x in range(N)] for y in range(N)]
	plt.imshow(pmap, cmap='plasma', interpolation='nearest')

	plt.subplot(223)
	plt.title("4 octaves, marbled")
	mpmap = [[sin(1.6 * 2 * pi * combined(simplex2D, 6 * x / N, 6 * y / N, octaves=4)) for x in range(N)] for y in range(N)]
	plt.imshow(mpmap, cmap='plasma', interpolation='nearest')

	plt.subplot(224)
	plt.title("15 octaves, crinkled")
	cpmap = [[combined(simplex2D, 10 * x / N, 10 * y / N, octaves=15) for x in range(N)] for y in range(N)]
	plt.imshow(cpmap, cmap='plasma', interpolation='nearest')

	plt.show() 
Example 16
Project: procgen   Author: juancroldan   File: white.py    Apache License 2.0 6 votes vote down vote up
def white2D_subjective():
	print("Displaying 2D white output")
	N = 100
	pmap = [[combined(white, x / N, y / N) for x in range(N)] for y in range(N)]

	plt.subplot(221)
	plt.title("6 octaves")
	plt.imshow(pmap, cmap='plasma', interpolation='nearest')

	plt.subplot(222)
	plt.title("1 octave")
	pmap = [[combined(white, 6 * x / N, 6 * y / N, octaves=1) for x in range(N)] for y in range(N)]
	plt.imshow(pmap, cmap='plasma', interpolation='nearest')

	plt.subplot(223)
	plt.title("4 octaves, marbled")
	mpmap = [[sin(1.6 * 2 * pi * combined(white, 6 * x / N, 6 * y / N, octaves=4)) for x in range(N)] for y in range(N)]
	plt.imshow(mpmap, cmap='plasma', interpolation='nearest')

	plt.subplot(224)
	plt.title("15 octaves, crinkled")
	cpmap = [[combined(white, 10 * x / N, 10 * y / N, octaves=15) for x in range(N)] for y in range(N)]
	plt.imshow(cpmap, cmap='plasma', interpolation='nearest')

	plt.show() 
Example 17
Project: procgen   Author: juancroldan   File: perlin.py    Apache License 2.0 6 votes vote down vote up
def perlin2D_subjective():
	print("Displaying 2D perlin output")
	N = 100
	pmap = [[combined(perlin2D, x / N, y / N) for x in range(N)] for y in range(N)]

	plt.subplot(221)
	plt.title("6 octaves")
	plt.imshow(pmap, cmap='plasma', interpolation='nearest')

	plt.subplot(222)
	plt.title("1 octave")
	pmap = [[combined(perlin2D, 6 * x / N, 6 * y / N, octaves=1) for x in range(N)] for y in range(N)]
	plt.imshow(pmap, cmap='plasma', interpolation='nearest')

	plt.subplot(223)
	plt.title("4 octaves, marbled")
	mpmap = [[sin(1.6 * 2 * pi * combined(perlin2D, 6 * x / N, 6 * y / N, octaves=4)) for x in range(N)] for y in range(N)]
	plt.imshow(mpmap, cmap='plasma', interpolation='nearest')

	plt.subplot(224)
	plt.title("15 octaves, crinkled")
	cpmap = [[combined(perlin2D, 10 * x / N, 10 * y / N, octaves=15) for x in range(N)] for y in range(N)]
	plt.imshow(cpmap, cmap='plasma', interpolation='nearest')

	plt.show() 
Example 18
Project: procgen   Author: juancroldan   File: opensimplex.py    Apache License 2.0 6 votes vote down vote up
def opensimplex2D_subjective():
	print("Displaying 2D opensimplex output")
	N = 100
	pmap = [[combined(opensimplex2D, x / N, y / N) for x in range(N)] for y in range(N)]

	plt.subplot(221)
	plt.title("6 octaves")
	plt.imshow(pmap, cmap='plasma', interpolation='nearest')

	plt.subplot(222)
	plt.title("1 octave")
	pmap = [[combined(opensimplex2D, 6 * x / N, 6 * y / N, octaves=1) for x in range(N)] for y in range(N)]
	plt.imshow(pmap, cmap='plasma', interpolation='nearest')

	plt.subplot(223)
	plt.title("4 octaves, marbled")
	mpmap = [[sin(1.6 * 2 * pi * combined(opensimplex2D, 6 * x / N, 6 * y / N, octaves=4)) for x in range(N)] for y in range(N)]
	plt.imshow(mpmap, cmap='plasma', interpolation='nearest')

	plt.subplot(224)
	plt.title("15 octaves, crinkled")
	cpmap = [[combined(opensimplex2D, 10 * x / N, 10 * y / N, octaves=15) for x in range(N)] for y in range(N)]
	plt.imshow(cpmap, cmap='plasma', interpolation='nearest')

	plt.show() 
Example 19
Project: CAFA_assessment_tool   Author: ashleyzhou972   File: plot.py    GNU General Public License v3.0 6 votes vote down vote up
def read_config():
    parser = argparse.ArgumentParser(description='Precision-Recall Curves plot', )
    

    parser.add_argument('config_stream',type=extant_file, help='Configuration file')
    #CAFA3 raw submission filename formats are listed here:https://www.synapse.org/#!Synapse:syn5840147/wiki/402192
    #example filename format: Doegroup_1_9606.txt/Doegroup_2_hpo.txt
    #If prediction file is already split by ontology it should follow Doegroup_1_9606_BPO.txt(or _MFO, _CCO)                  
    args = parser.parse_args()
    try:
        config_dict = yaml.load(args.config_stream)['plot']
    except yaml.YAMLError as exc:
        print(exc)
        sys.exit()
    Num_files = len(config_dict)-3
    results_folder = config_dict['results']
    title = config_dict['title']
    smooth = config_dict['smooth']
    methods = set()
    for i in xrange(Num_files):
        keyname = 'file'+str(i+1)
        methods.add(config_dict[keyname])
    return(results_folder, title,smooth, methods) 
Example 20
Project: DiscEvolution   Author: rbooth200   File: plot_planet_M-R.py    GNU General Public License v3.0 6 votes vote down vote up
def make_plot_planets(planets):
    for p in planets:
        plt.subplot(211)
        plt.loglog(p.R, p.M / 317.8)
        plt.subplot(212)
        plt.loglog(p.R, p.M_core)

    plt.subplot(211)
    plt.title('t_0 = {:g}yr'.format(p.t_form[0]))
    plt.ylabel('$M\,[M_J]$')
    plt.plot([0.1, 300], [1,1], 'k--')
    plt.xlim(0.1, 300)
    plt.subplot(212)
    plt.ylabel('$M_c\,[M_\oplus]$')
    plt.xlabel('$R\,[\mathrm{au}]$')
    plt.xlim(0.1, 300) 
Example 21
Project: DiscEvolution   Author: rbooth200   File: plot_planet_R-t.py    GNU General Public License v3.0 6 votes vote down vote up
def make_plot_planets(planets):
    for p in planets:
        plt.subplot(211)
        plt.loglog(p.R, p.M / 317.8)
        plt.subplot(212)
        plt.loglog(p.R, p.M_core)

    plt.subplot(211)
    plt.title('t_0 = {:g}yr'.format(p.t_form[0]))
    plt.ylabel('$M\,[M_J]$')
    plt.plot([0.1, 300], [1,1], 'k--')
    plt.xlim(0.1, 300)
    plt.subplot(212)
    plt.ylabel('$M_c\,[M_\oplus]$')
    plt.xlabel('$R\,[\mathrm{au}]$')
    plt.xlim(0.1, 300) 
Example 22
Project: RNASEqTool   Author: armell   File: mpld3_rendering.py    MIT License 6 votes vote down vote up
def plot_distribution_for_genes(data, genes):
    distributions = generate_distribution_for_genes(data, genes)
    sns.set_palette("deep", desat=.6)
    i = 0
    hist = None
    fig = plt.figure()
    for dist in distributions:
        plt.hist(dist, alpha=0.5, label=genes[i])
        i += 1

    plt.legend()
    plt.title(genes.__str__() + " distribution")

    #script, div = components(mpl.to_bokeh(), CDN)

    #return {"js": script, "html": div}
    plugins.connect(fig, extra.InteractiveLegendPlugin())
    return fig_to_html(fig) 
Example 23
Project: PEAKachu   Author: tbischler   File: adaptive.py    ISC License 5 votes vote down vote up
def _plot_initial_peaks(self, unsig_base_means, unsig_fcs,
                            sig_base_means, sig_fcs):
        # create plot folder if it does not exist
        plot_folder = "{}/plots".format(self._output_folder)
        if not exists(plot_folder):
            makedirs(plot_folder)
        # MA plot
        plt.plot(np.log10(unsig_base_means),
                 np.log2(unsig_fcs), ".",
                 markersize=2.0, alpha=0.3)
        plt.plot(np.log10(sig_base_means),
                 np.log2(sig_fcs), ".",
                 markersize=2.0, color="red", alpha=0.3)
        plt.axhline(y=np.median(np.log2(unsig_fcs.append(sig_fcs))))
        plt.axvline(x=np.median(np.log10(unsig_base_means.append(
                                         sig_base_means))))
        plt.title("Initial_peaks_MA_plot")
        plt.xlabel("log10 base mean")
        plt.ylabel("log2 fold-change")
        plt.savefig("{}/Initial_peaks_MA_plot.png".format(plot_folder),
                    dpi=600)
        plt.close()
        # HexBin plot
        df = pd.DataFrame({'log10 base mean': np.log10(unsig_base_means.append(
            sig_base_means)), 'log2 fold-change': np.log2(unsig_fcs.append(
                sig_fcs))})
        df.plot(kind='hexbin', x='log10 base mean',
                y='log2 fold-change', gridsize=50, bins='log')
        plt.axhline(y=np.median(np.log2(unsig_fcs.append(sig_fcs))))
        plt.axvline(x=np.median(np.log10(unsig_base_means.append(
                                         sig_base_means))))
        plt.title("Initial_peaks_HexBin_plot")
        plt.savefig("{}/Initial_peaks_HexBin_plot.pdf".format(plot_folder))
        plt.close() 
Example 24
Project: projection-methods   Author: akshayka   File: circles.py    GNU General Public License v3.0 5 votes vote down vote up
def main():
    x = cp.Variable(2)
    r = 10
    left_circle = ConvexSet(x, [cp.square(x[0] + r) + cp.square(x[1]) <= r**2])
    right_circle = ConvexSet(x, [cp.square(x[0] - r) + cp.square(x[1]) <= r**2])

    problem = FeasibilityProblem([left_circle, right_circle], np.array([0, 0]))

    initial_iterate = np.array([0, r])
    max_iters = 10

    plt.figure()
    plot_circles(r)
    solver = AltP(max_iters=max_iters, initial_iterate=initial_iterate)
    solver.solve(problem)
    plot_iterates(solver.all_iterates, 'Alternating Projections')

    solver = Polyak(max_iters=max_iters, initial_iterate=initial_iterate)
    it, res, status = solver.solve(problem)
    plot_iterates(it, 'Polyak\'s acceleration')

    solver = APOP(max_iters=max_iters, initial_iterate=initial_iterate,
        average=False)
    it, res, status = solver.solve(problem)
    plot_iterates(it, 'APOP')
    plt.title('Motivating APOP: Circles')
    plt.legend()
    plt.show() 
Example 25
Project: sfcc   Author: kv-kunalvyas   File: auxiliary.py    MIT License 5 votes vote down vote up
def plotLearningCurves(train, classifier):
    #P.show()
    X = train.values[:, 1::]
    y = train.values[:, 0]

    train_sizes, train_scores, test_scores = learning_curve(
            classifier, X, y, cv=10, n_jobs=-1, train_sizes=np.linspace(.1, 1., 10), verbose=0)

    train_scores_mean = np.mean(train_scores, axis=1)
    train_scores_std = np.std(train_scores, axis=1)
    test_scores_mean = np.mean(test_scores, axis=1)
    test_scores_std = np.std(test_scores, axis=1)

    plt.figure()
    plt.title("Learning Curves")
    plt.legend(loc="best")
    plt.xlabel("Training samples")
    plt.ylabel("Error Rate")
    plt.ylim((0, 1))
    plt.gca().invert_yaxis()
    plt.grid()

    # Plot the average training and test score lines at each training set size
    plt.plot(train_sizes, train_scores_mean, 'o-', color="b", label="Training score")
    plt.plot(train_sizes, test_scores_mean, 'o-', color="r", label="Test score")

    # Plot the std deviation as a transparent range at each training set size
    plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std,
                     alpha=0.1, color="b")
    plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std,
                     alpha=0.1, color="r")

    # Draw the plot and reset the y-axis
    plt.draw()
    plt.gca().invert_yaxis()

    # shuffle and split training and test sets
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.25)
    classifier.fit(X_train, y_train)
    plt.show() 
Example 26
Project: fenics-topopt   Author: zfergus   File: stress_gui.py    MIT License 5 votes vote down vote up
def __init__(self, nelx, nely, stress_calculator, nu, title=""):
        """Initialize plot and plot the initial design"""
        super(StressGUI, self).__init__(nelx, nely, title)
        self.stress_im = self.ax.imshow(
            np.swapaxes(np.zeros((nelx, nely, 4)), 0, 1),
            norm=colors.Normalize(vmin=0, vmax=1), cmap='jet')
        self.fig.colorbar(self.stress_im)
        self.stress_calculator = stress_calculator
        self.nu = nu
        self.myColorMap = colormaps.ScalarMappable(
            norm=colors.Normalize(vmin=0, vmax=1), cmap=colormaps.jet) 
Example 27
Project: fenics-topopt   Author: zfergus   File: gui.py    MIT License 5 votes vote down vote up
def __init__(self, nelx, nely, title=""):
        """Initialize plot and plot the initial design"""
        plt.ion()  # Ensure that redrawing is possible
        self.fig, self.ax = plt.subplots()
        self.im = self.ax.imshow(-np.zeros((nelx, nely)).T, cmap='gray',
            interpolation='none', norm=colors.Normalize(vmin=-1, vmax=0))
        plt.xlabel(title)
        # self.fig.tight_layout()
        self.fig.show()
        self.nelx, self.nely = nelx, nely 
Example 28
Project: fenics-topopt   Author: zfergus   File: gui.py    MIT License 5 votes vote down vote up
def update(self, xPhys, title=None):
        """Plot to screen"""
        self.im.set_array(-xPhys.reshape((self.nelx, self.nely)).T)
        self.fig.canvas.draw()
        self.fig.canvas.flush_events()
        if title is not None:
            plt.title(title)
        plt.pause(0.01) 
Example 29
Project: fenics-topopt   Author: zfergus   File: stress_gui.py    MIT License 5 votes vote down vote up
def __init__(self, nelx, nely, stress_calculator, nu, title=""):
        """Initialize plot and plot the initial design"""
        super(StressGUI, self).__init__(nelx, nely, title)
        self.stress_im = self.ax.imshow(
            np.swapaxes(np.zeros((nelx, nely, 4)), 0, 1),
            norm=colors.Normalize(vmin=0, vmax=1), cmap='jet')
        self.fig.colorbar(self.stress_im)
        self.stress_calculator = stress_calculator
        self.nu = nu
        self.myColorMap = colormaps.ScalarMappable(
            norm=colors.Normalize(vmin=0, vmax=1), cmap=colormaps.jet) 
Example 30
Project: fenics-topopt   Author: zfergus   File: gui.py    MIT License 5 votes vote down vote up
def __init__(self, nelx, nely, title=""):
        """Initialize plot and plot the initial design"""
        plt.ion()  # Ensure that redrawing is possible
        self.fig, self.ax = plt.subplots()
        self.im = self.ax.imshow(-np.zeros((nelx, nely)).T, cmap='gray',
            interpolation='none', norm=colors.Normalize(vmin=-1, vmax=0))
        plt.xlabel(title)
        # self.fig.tight_layout()
        self.fig.show()
        self.nelx, self.nely = nelx, nely 
Example 31
Project: fenics-topopt   Author: zfergus   File: gui.py    MIT License 5 votes vote down vote up
def update(self, xPhys, title=None):
        """Plot to screen"""
        self.im.set_array(-xPhys.reshape((self.nelx, self.nely)).T)
        self.fig.canvas.draw()
        self.fig.canvas.flush_events()
        if title is not None:
            plt.title(title)
        plt.pause(0.01) 
Example 32
Project: OpenAPS   Author: medicinexlab   File: oldpred.py    MIT License 5 votes vote down vote up
def _plot_old_pred_data(old_pred_data, show_pred_plot, save_pred_plot, show_clarke_plot, save_clarke_plot, id_str, algorithm_str, minutes_str):
    actual_bg_array = old_pred_data.result_actual_bg_array
    actual_bg_time_array = old_pred_data.result_actual_bg_time_array
    pred_array = old_pred_data.result_pred_array
    pred_time_array = old_pred_data.result_pred_time_array

    #Root mean squared error
    rms = math.sqrt(metrics.mean_squared_error(actual_bg_array, pred_array))
    print "                Root Mean Squared Error: " + str(rms)
    print "                Mean Absolute Error: " + str(metrics.mean_absolute_error(actual_bg_array, pred_array))
    print "                R^2 Coefficient of Determination: " + str(metrics.r2_score(actual_bg_array, pred_array))

    plot, zone = ClarkeErrorGrid.clarke_error_grid(actual_bg_array, pred_array, id_str + " " + algorithm_str + " " + minutes_str)
    print "                Percent A:{}".format(float(zone[0]) / (zone[0] + zone[1] + zone[2] + zone[3] + zone[4]))
    print "                Percent C, D, E:{}".format(float(zone[2] + zone[3] + zone[4])/ (zone[0] + zone[1] + zone[2] + zone[3] + zone[4]))
    print "                Zones are A:{}, B:{}, C:{}, D:{}, E:{}\n".format(zone[0],zone[1],zone[2],zone[3],zone[4])
    if save_clarke_plot: plt.savefig(id_str + algorithm_str.replace(" ", "") + minutes_str + "clarke.png")
    if show_clarke_plot: plot.show()

    plt.clf()
    plt.plot(actual_bg_time_array, actual_bg_array, label="Actual BG", color='black', linestyle='-')
    plt.plot(pred_time_array, pred_array, label="BG Prediction", color='black', linestyle=':')
    plt.title(id_str + " " + algorithm_str + " " + minutes_str + " BG Analysis")
    plt.ylabel("Blood Glucose Level (mg/dl)")
    plt.xlabel("Time (minutes)")
    plt.legend(loc='upper left')

    # SHOW/SAVE PLOT DEPENDING ON THE BOOLEAN PARAMETER
    if save_pred_plot: plt.savefig(id_str + algorithm_str.replace(" ","") + minutes_str + "plot.png")
    if show_pred_plot: plt.show()


#Function to analyze the old OpenAPS data 
Example 33
Project: OpenAPS   Author: medicinexlab   File: oldpred.py    MIT License 5 votes vote down vote up
def analyze_old_pred_data(bg_df, old_pred_algorithm_array, start_test_index, end_test_index, pred_minutes, show_pred_plot, save_pred_plot, show_clarke_plot, save_clarke_plot, id_str):
    """
    Function that analyzes the old OpenAPS prediction models (eventualBG, aCOB, COB, and IOB)
    based on what is put in the old_pred_algorithm_array. If it is empty, nothing will be plotted.
    Since all the algorithms are calculated every 5 minutes, pred_minutes must be a multiple of 5.
    eventualBG is only calculated by 30 minutes, so it will always be 30 minutes.
    It will save the prediction plot if save_pred_plot is True and the clarke plot if save_clarke_plot is True.
    It will show the prediction plot if show_pred_plot is true and the clarke plot if show_clarke_plot is True.

    Input:      bg_df                           Pandas dataframe of all of the data from ./data/[id_str]/devicestatus.json
                old_pred_algorithm_array        The array of the original OpenAPS prediction algorithms that you want to receive
                                                    data from. It can contain any/none of the following: "eventualBG", "acob", "cob", "iob"
                start_test_index                The starting index of the testing data
                end_test_index                  The ending index of the testing data
                pred_minutes                    The number of minutes in the future the prediction is for (predicion horizon). Must be a multiple of 5
                show_pred_plot                  Boolean to show the prediction plot
                save_pred_plot                  Boolean to save the prediction plot
                show_clarke_plot                Boolean to show the Clarke Error Grid Plot
                save_clarke_plot                Boolean to save the Clarke Error Grid Plot
                id_str                          The ID of the person as a string. Used for the title

    Output:     None
    Usage:      analyze_old_pred_data(bg_df, ['iob', 'cob'], 1500, 0, 30, True, False, True, False, "00000001")
    """

    if pred_minutes % 5 != 0: raise Exception("The prediction minutes is not a multiple of 5.")
    eventual_pred_data, iob_pred_data, cob_pred_data, acob_pred_data = _get_old_pred(bg_df, start_test_index, end_test_index, pred_minutes)
    if 'eventualBG' in old_pred_algorithm_array and pred_minutes == EVENTUALBG_PRED_MINUTES:
        print("        eventualBG")
        _plot_old_pred_data(eventual_pred_data, show_pred_plot, save_pred_plot, show_clarke_plot, save_clarke_plot, id_str, "eventualBG", "Pred" + str(30))
    if 'iob' in old_pred_algorithm_array:
        print("        iob")
        _plot_old_pred_data(iob_pred_data, show_pred_plot, save_pred_plot, show_clarke_plot, save_clarke_plot, id_str, "IOB", "Pred" + str(pred_minutes))
    if 'cob' in old_pred_algorithm_array:
        print("        cob")
        _plot_old_pred_data(cob_pred_data, show_pred_plot, save_pred_plot, show_clarke_plot, save_clarke_plot, id_str, "COB", "Pred" + str(pred_minutes))
    if 'acob' in old_pred_algorithm_array:
        print("        acob")
        _plot_old_pred_data(acob_pred_data, show_pred_plot, save_pred_plot, show_clarke_plot, save_clarke_plot, id_str, "aCOB", "Pred" + str(pred_minutes)) 
Example 34
Project: ml_news_popularity   Author: khaledJabr   File: lr.py    MIT License 5 votes vote down vote up
def plot(self):
        lw = 2
        plt.scatter(range(len(self.targets)), self.targets, color='darkorange', label='data')
        plt.scatter(range(len(self.predicted)), self.predicted, color='cornflowerblue', lw=lw, label='Polynomial model')
        plt.xlabel('Data')
        plt.ylabel('Target')
        plt.title('Lasso Regression')
        plt.legend()
        plt.show() 
Example 35
Project: Tacotron   Author: ElwynWang   File: signal_process.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_alignment(alignment, gs, mode, path = None):
    """Plots the alignment
    alignments: A list of (numpy) matrix of shape (encoder_steps, decoder_steps)
    gs : (int) global step
    mode: "save_fig" or "with_return". "save_fig":save fig locally, "with_return":return plot for tensorboard
    """

    plt.imshow(alignment, cmap='hot', interpolation='nearest')
    plt.xlabel('Decoder Steps')
    plt.ylabel('Encoder Steps')
    plt.title('{} Steps'.format(gs))

    if mode == "save_fig":
        if path is not None:
            plt.savefig('{}/alignment_{}k.png'.format(path, gs//Hp.save_model_step), format='jpg')
        else:
            print ("Warning! You need specify the saved path! The temporal path is {}".format(Hp.logdir))
            plt.savefig('{}/alignment_{}k.png'.format(Hp.logdir, gs//Hp.save_model_step), format='jpg')

    elif mode == "with_return":
        buf = io.BytesIO()
        plt.savefig(buf, format='png')
        buf.seek(0)
        plot = tf.image.decode_png(buf.getvalue(), channels=4)
        plot = tf.expand_dims(plot,0)
        return plot

    else:
        print ("Error Mode! Exit!")
        sys.exit(0) 
Example 36
Project: RandomFourierFeatures   Author: tiskw   File: sample_rff_regression.py    MIT License 5 votes vote down vote up
def main():

    ### Fix seed for random fourier feature calclation
    pyrff.seed(111)

    ### Prepare training data
    Xs_train = np.linspace(0, 3, 21).reshape((21, 1))
    ys_train = np.sin(Xs_train**2)
    Xs_test  = np.linspace(0, 3, 101).reshape((101, 1))
    ys_test  = np.sin(Xs_test**2)

    ### Create classifier instance
    reg = pyrff.RFFRegression(dim_output = 8, std = 0.5)

    ### Train regression with random fourier features
    reg.fit(Xs_train, ys_train)

    ### Conduct prediction for the test data
    predict = reg.predict(Xs_test)

    ### Plot regression results
    mpl.figure(0)
    mpl.title("Regression for function y = sin(x^2) with RFF")
    mpl.xlabel("X")
    mpl.ylabel("Y")
    mpl.plot(Xs_train, ys_train, "o")
    mpl.plot(Xs_test,  ys_test,  ".")
    mpl.plot(Xs_test,  predict,  "-")
    mpl.legend(["Training data", "Test data", "Prediction by RFF regression"])
    mpl.grid()
    mpl.show() 
Example 37
Project: mmdetection   Author: open-mmlab   File: analyze_logs.py    Apache License 2.0 5 votes vote down vote up
def add_plot_parser(subparsers):
    parser_plt = subparsers.add_parser(
        'plot_curve', help='parser for plotting curves')
    parser_plt.add_argument(
        'json_logs',
        type=str,
        nargs='+',
        help='path of train log in json format')
    parser_plt.add_argument(
        '--keys',
        type=str,
        nargs='+',
        default=['bbox_mAP'],
        help='the metric that you want to plot')
    parser_plt.add_argument('--title', type=str, help='title of figure')
    parser_plt.add_argument(
        '--legend',
        type=str,
        nargs='+',
        default=None,
        help='legend of each plot')
    parser_plt.add_argument(
        '--backend', type=str, default=None, help='backend of plt')
    parser_plt.add_argument(
        '--style', type=str, default='dark', help='style of plt')
    parser_plt.add_argument('--out', type=str, default=None) 
Example 38
Project: mmdetection   Author: open-mmlab   File: coco_error_analysis.py    Apache License 2.0 5 votes vote down vote up
def makeplot(rs, ps, outDir, class_name, iou_type):
    cs = np.vstack([
        np.ones((2, 3)),
        np.array([.31, .51, .74]),
        np.array([.75, .31, .30]),
        np.array([.36, .90, .38]),
        np.array([.50, .39, .64]),
        np.array([1, .6, 0])
    ])
    areaNames = ['allarea', 'small', 'medium', 'large']
    types = ['C75', 'C50', 'Loc', 'Sim', 'Oth', 'BG', 'FN']
    for i in range(len(areaNames)):
        area_ps = ps[..., i, 0]
        figure_tile = iou_type + '-' + class_name + '-' + areaNames[i]
        aps = [ps_.mean() for ps_ in area_ps]
        ps_curve = [
            ps_.mean(axis=1) if ps_.ndim > 1 else ps_ for ps_ in area_ps
        ]
        ps_curve.insert(0, np.zeros(ps_curve[0].shape))
        fig = plt.figure()
        ax = plt.subplot(111)
        for k in range(len(types)):
            ax.plot(rs, ps_curve[k + 1], color=[0, 0, 0], linewidth=0.5)
            ax.fill_between(
                rs,
                ps_curve[k],
                ps_curve[k + 1],
                color=cs[k],
                label=str('[{:.3f}'.format(aps[k]) + ']' + types[k]))
        plt.xlabel('recall')
        plt.ylabel('precision')
        plt.xlim(0, 1.)
        plt.ylim(0, 1.)
        plt.title(figure_tile)
        plt.legend()
        # plt.show()
        fig.savefig(outDir + '/{}.png'.format(figure_tile))
        plt.close(fig) 
Example 39
Project: Kaggle-Statoil-Challenge   Author: adodd202   File: utils.py    MIT License 5 votes vote down vote up
def plot_overlap(logger, names=None):
    names = logger.names if names == None else names
    numbers = logger.numbers
    for _, name in enumerate(names):
        x = np.arange(len(numbers[name]))
        if name in ['Train Acc.', 'Valid Acc.']:
            plt.plot(x, 100 - np.asarray(numbers[name], dtype='float'))
        else:
            plt.plot(x, np.asarray(numbers[name]))
    return [logger.title + '(' + name + ')' for name in names] 
Example 40
Project: Kaggle-Statoil-Challenge   Author: adodd202   File: utils.py    MIT License 5 votes vote down vote up
def plot(self, names=None):
        names = self.names if names == None else names
        numbers = self.numbers
        for _, name in enumerate(names):
            x = np.arange(len(numbers[name]))
            plt.plot(x, np.asarray(numbers[name]))
        plt.legend([self.title + '(' + name + ')' for name in names])
        plt.grid(True) 
Example 41
Project: Kaggle-Statoil-Challenge   Author: adodd202   File: utils.py    MIT License 5 votes vote down vote up
def __init__(self, paths):
        '''paths is a distionary with {name:filepath} pair'''
        self.loggers = []
        for title, path in paths.items():
            logger = Logger(path, title=title, resume=True)
            self.loggers.append(logger) 
Example 42
Project: Kaggle-Statoil-Challenge   Author: adodd202   File: utils.py    MIT License 5 votes vote down vote up
def plot_log(filename, show=True):
    # load data
    keys = []
    values = []
    with open(filename, 'r') as f:
        reader = csv.DictReader(f)
        for row in reader:
            if keys == []:
                for key, value in row.items():
                    keys.append(key)
                    values.append(float(value))
                continue

            for _, value in row.items():
                values.append(float(value))

        values = np.reshape(values, newshape=(-1, len(keys)))
        values[:,0] += 1

    fig = plt.figure(figsize=(4,6))
    fig.subplots_adjust(top=0.95, bottom=0.05, right=0.95)
    fig.add_subplot(211)
    for i, key in enumerate(keys):
        if key.find('loss') >= 0 and not key.find('val') >= 0:  # training loss
            plt.plot(values[:, 0], values[:, i], label=key)
    plt.legend()
    plt.title('Training loss')

    fig.add_subplot(212)
    for i, key in enumerate(keys):
        if key.find('acc') >= 0:  # acc
            plt.plot(values[:, 0], values[:, i], label=key)
    plt.legend()
    plt.title('Training and validation accuracy')

    # fig.savefig('result/log.png')
    if show:
        plt.show() 
Example 43
Project: programsynthesishunting   Author: flexgp   File: save_plots.py    GNU General Public License v3.0 5 votes vote down vote up
def save_plot_from_data(data, name):
    """
    Saves a plot of a given set of data.

    :param data: the data to be plotted
    :param name: the name of the data to be plotted.
    :return: Nothing.
    """

    from algorithm.parameters import params

    # Initialise up figure instance.
    fig = plt.figure()
    ax1 = fig.add_subplot(1, 1, 1)

    # Plot data.
    ax1.plot(data)

    # Set labels.
    ax1.set_ylabel(name, fontsize=14)
    ax1.set_xlabel('Generation', fontsize=14)

    # Plot title.
    plt.title(name)

    # Save plot and close.
    plt.savefig(path.join(params['FILE_PATH'], (name + '.pdf')))
    plt.close() 
Example 44
Project: programsynthesishunting   Author: flexgp   File: save_plots.py    GNU General Public License v3.0 5 votes vote down vote up
def save_plot_from_file(filename, stat_name):
    """
    Saves a plot of a given stat from the stats file.

    :param filename: a full specified path to a .csv stats file.
    :param stat_name: the stat of interest for plotting.
    :return: Nothing.
    """

    # Read in the data
    data = pd.read_csv(filename, sep="\t")
    try:
        stat = list(data[stat_name])
    except KeyError:
        s = "utilities.stats.save_plots.save_plot_from_file\n" \
            "Error: stat %s does not exist" % stat_name
        raise Exception(s)

        # Set up the figure.
    fig = plt.figure()
    ax1 = fig.add_subplot(1, 1, 1)

    # Plot the data.
    ax1.plot(stat)

    # Plot title.
    plt.title(stat_name)

    # Get save path
    save_path = pathsep.join(filename.split(pathsep)[:-1])

    # Save plot and close.
    plt.savefig(path.join(save_path, (stat_name + '.pdf')))
    plt.close() 
Example 45
Project: programsynthesishunting   Author: flexgp   File: save_plots.py    GNU General Public License v3.0 5 votes vote down vote up
def save_box_plot(data, names, title):
    """
    Given an array of some data, and a list of names of that data, generate
    and save a box plot of that data.

    :param data: An array of some data to be plotted.
    :param names: A list of names of that data.
    :param title: The title of the plot.
    :return: Nothing
    """

    from algorithm.parameters import params

    import matplotlib.pyplot as plt
    plt.rc('font', family='Times New Roman')

    # Set up the figure.
    fig = plt.figure()
    ax1 = fig.add_subplot(1, 1, 1)

    # Plot tight layout.
    plt.tight_layout()

    # Plot the data.
    ax1.boxplot(np.transpose(data), 1)

    # Plot title.
    plt.title(title)

    # Generate list of numbers for plotting names.
    nums = list(range(len(data))[1:]) + [len(data)]

    # Plot names for each data point.
    plt.xticks(nums, names, rotation='vertical', fontsize=8)

    # Save plot.
    plt.savefig(path.join(params['FILE_PATH'], (title + '.pdf')))

    # Close plot.
    plt.close() 
Example 46
Project: deep-learning-note   Author: wdxtub   File: 2_serving_and_predict.py    MIT License 5 votes vote down vote up
def show(idx, title):
  plt.figure()
  plt.imshow(test_images[idx].reshape(28,28))
  plt.axis('off')
  plt.title('\n\n{}'.format(title), fontdict={'size': 16})
  plt.show() 
Example 47
Project: keras-anomaly-detection   Author: chen0040   File: plot_utils.py    MIT License 5 votes vote down vote up
def plot_confusion_matrix(y_true, y_pred):
    conf_matrix = confusion_matrix(y_true, y_pred)

    plt.figure(figsize=(12, 12))
    sns.heatmap(conf_matrix, xticklabels=LABELS, yticklabels=LABELS, annot=True, fmt="d")
    plt.title("Confusion matrix")
    plt.ylabel('True class')
    plt.xlabel('Predicted class')
    plt.show() 
Example 48
Project: keras-anomaly-detection   Author: chen0040   File: plot_utils.py    MIT License 5 votes vote down vote up
def plot_training_history(history):
    if history is None:
        return
    plt.plot(history['loss'])
    plt.plot(history['val_loss'])
    plt.title('model loss')
    plt.ylabel('loss')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper right')
    plt.show() 
Example 49
Project: keras-anomaly-detection   Author: chen0040   File: plot_utils.py    MIT License 5 votes vote down vote up
def visualize_reconstruction_error(reconstruction_error, threshold):
    plt.plot(reconstruction_error, marker='o', ms=3.5, linestyle='',
             label='Point')

    plt.hlines(threshold, xmin=0, xmax=len(reconstruction_error)-1, colors="r", zorder=100, label='Threshold')
    plt.legend()
    plt.title("Reconstruction error")
    plt.ylabel("Reconstruction error")
    plt.xlabel("Data point index")
    plt.show() 
Example 50
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: dcgan.py    Apache License 2.0 5 votes vote down vote up
def visual(title, X, name):
    assert len(X.shape) == 4
    X = X.transpose((0, 2, 3, 1))
    X = np.clip((X - np.min(X))*(255.0/(np.max(X) - np.min(X))), 0, 255).astype(np.uint8)
    n = np.ceil(np.sqrt(X.shape[0]))
    buff = np.zeros((int(n*X.shape[1]), int(n*X.shape[2]), int(X.shape[3])), dtype=np.uint8)
    for i, img in enumerate(X):
        fill_buf(buff, i, img, X.shape[1:3])
    buff = buff[:,:,::-1]
    plt.imshow(buff)
    plt.title(title)
    plt.savefig(name) 
Example 51
Project: helloworld   Author: pip-uninstaller-python   File: matplotlibTest.py    GNU General Public License v2.0 5 votes vote down vote up
def main():
    # line
    x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
    c, s = np.cos(x), np.sin(x)
    plt.figure(1)
    plt.plot(x, c, color="blue", linewidth=1.0, linestyle="-", label="COS", alpha=0.5)  # 自变量, 因变量
    plt.plot(x, s, "r.", label="SIN")  # 正弦  "-"/"r-"/"r."
    plt.title("COS & SIN")
    ax = plt.gca()
    ax.spines["right"].set_color("none")
    ax.spines["top"].set_color("none")
    ax.spines["left"].set_position(("data", 0))  # 横轴位置
    ax.spines["bottom"].set_position(("data", 0))  # 纵轴位置
    ax.xaxis.set_ticks_position("bottom")
    ax.yaxis.set_ticks_position("left")
    plt.xticks([-np.pi, -np.pi / 2.0, np.pi / 2, np.pi],
               [r'$-\pi/2$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$-\pi$'])
    plt.yticks(np.linspace(-1, 1, 5, endpoint=True))
    for label in ax.get_xticklabels() + ax.get_yticklabels():
        label.set_fontsize(16)
        label.set_bbox(dict(facecolor="white", edgecolor="None", alpha=0.2))
    plt.legend(loc="upper left")  # 左上角的显示图标
    plt.grid()  # 网格线
    # plt.axis([-1, 1, -0.5, 1])  # 显示范围
    plt.fill_between(x, np.abs(x) < 0.5, c, c < 0.5, color="green", alpha=0.25)
    t = 1
    plt.plot([t, t], [0, np.cos(t)], "y", linewidth=3, linestyle="--")
    # 注释
    plt.annotate("cos(1)", xy=(t, np.cos(1)), xycoords="data", xytext=(+10, +30),
                 textcoords="offset points", arrowprops=dict(arrowstyle="->", connectionstyle="arc3, rad=.2"))
    plt.show()


# Scatter --> 散点图 
Example 52
Project: GST-Tacotron   Author: KinglittleQ   File: utils.py    MIT License 5 votes vote down vote up
def plot_alignment(alignment, gs):
    """Plots the alignment
    alignments: A list of (numpy) matrix of shape (encoder_steps, decoder_steps)
    gs : (int) global step
    """
    fig, ax = plt.subplots()
    im = ax.imshow(alignment)

    # cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
    fig.colorbar(im)
    plt.title('{} Steps'.format(gs))
    plt.savefig('{}/alignment_{}k.png'.format(hp.logdir, gs // 1000), format='png') 
Example 53
Project: DOTA_models   Author: ringringyi   File: plot_lfads.py    Apache License 2.0 5 votes vote down vote up
def _plot_item(W, name, full_name, nspaces):
  plt.figure()
  if W.shape == ():
    print(name, ": ", W)
  elif W.shape[0] == 1:
    plt.stem(W.T)
    plt.title(full_name)
  elif W.shape[1] == 1:
    plt.stem(W)
    plt.title(full_name)
  else:
    plt.imshow(np.abs(W), interpolation='nearest', cmap='jet');
    plt.colorbar()
    plt.title(full_name) 
Example 54
Project: DOTA_models   Author: ringringyi   File: plot_lfads.py    Apache License 2.0 5 votes vote down vote up
def plot_priors():
  g0s_prior_mean_bxn = train_modelvals['prior_g0_mean']
  g0s_prior_var_bxn = train_modelvals['prior_g0_var']
  g0s_post_mean_bxn = train_modelvals['posterior_g0_mean']
  g0s_post_var_bxn = train_modelvals['posterior_g0_var']

  plt.figure(figsize=(10,4), tight_layout=True);
  plt.subplot(1,2,1)
  plt.hist(g0s_post_mean_bxn.flatten(), bins=20, color='b');
  plt.hist(g0s_prior_mean_bxn.flatten(), bins=20, color='g');

  plt.title('Histogram of Prior/Posterior Mean Values')
  plt.subplot(1,2,2)
  plt.hist((g0s_post_var_bxn.flatten()), bins=20, color='b');
  plt.hist((g0s_prior_var_bxn.flatten()), bins=20, color='g');
  plt.title('Histogram of Prior/Posterior Log Variance Values')

  plt.figure(figsize=(10,10), tight_layout=True)
  plt.subplot(2,2,1)
  plt.imshow(g0s_prior_mean_bxn.T, interpolation='nearest', cmap='jet')
  plt.colorbar(fraction=0.025, pad=0.04)
  plt.title('Prior g0 means')

  plt.subplot(2,2,2)
  plt.imshow(g0s_post_mean_bxn.T, interpolation='nearest', cmap='jet')
  plt.colorbar(fraction=0.025, pad=0.04)
  plt.title('Posterior g0 means');

  plt.subplot(2,2,3)
  plt.imshow(g0s_prior_var_bxn.T, interpolation='nearest', cmap='jet')
  plt.colorbar(fraction=0.025, pad=0.04)
  plt.title('Prior g0 variance Values')

  plt.subplot(2,2,4)
  plt.imshow(g0s_post_var_bxn.T, interpolation='nearest', cmap='jet')
  plt.colorbar(fraction=0.025, pad=0.04)
  plt.title('Posterior g0 variance Values')

  plt.figure(figsize=(10,5))
  plt.stem(np.sort(np.log(g0s_post_mean_bxn.std(axis=0))));
  plt.title('Log standard deviation of h0 means'); 
Example 55
Project: smach_based_introspection_framework   Author: birlrobotics   File: collect_classification_statistics.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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`.
    """
    try:
        if normalize:
            cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
            print("Normalized confusion matrix")
        else:
            print('Confusion matrix, without normalization')
    except FloatingPointError:
        print ('Error occurred: invalid value encountered in divide')
        sys.exit()
    
    print(cm)

    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)

    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 56
Project: ortholotree   Author: oxpeter   File: internal.py    GNU General Public License v2.0 5 votes vote down vote up
def rank_scores(homologlist, thresh1=0, thresh2=None, genename=None, outfile=None, showplot=False):
    yvalues = sorted([val[1] for val in homologlist.values()], reverse=True)
    plt.plot(yvalues)
    score_cutoff = thresh1 * max(yvalues)
    sample_cutoff = sum(1 for s in yvalues if s >= thresh1 * max(yvalues))
    plt.axhline( score_cutoff , color='r' )
    if thresh2:
        plt.axhline( thresh2 * max(yvalues) , color='r' )
    plt.axvline( sample_cutoff -1 , color='g' )
    plt.text(sample_cutoff + 1,score_cutoff + 10 , "(%d,%d)" % (sample_cutoff,score_cutoff) )
    plt.xlabel("Gene rank")
    plt.ylabel("Phmmer score")
    plt.title("Ranking of phmmer scores for alignment with %s" % genename)
    if outfile:
        plt.savefig(outfile, format='png')
    if showplot:
        plt.show()
    else:
        plt.close() 
Example 57
Project: deep-summarization   Author: harpribot   File: plotter.py    MIT License 5 votes vote down vote up
def plot_one_metric(self, models_metric, title):
        """

        :param models_metric:
        :param title:
        :return:
        """
        for index, model_metric in enumerate(models_metric):
            plt.plot(self.steps, model_metric, label=self.file_desc[index])
        plt.title(title)
        plt.legend()
        plt.xlabel('Number of batches')
        plt.ylabel('Score') 
Example 58
Project: Pathfinder   Author: MatthewBCooke   File: Pathfinder.py    GNU General Public License v3.0 5 votes vote down vote up
def guiHeatmap(self, aExperiment):

        self.top3 = Toplevel(root)  # create a new toplevel window
        self.top3.configure(bg="white")
        self.top3.geometry('{}x{}'.format( 500, 500 ))
        Label(self.top3, text="Heatmap Parameters", bg="white", fg="black", width=15).pack()  # add a title

        self.gridSizeL = Label(self.top3, text="Grid Size:", bg="white")
        self.gridSizeL.pack(side=TOP)
        self.gridSizeE = Entry(self.top3, textvariable=gridSizeStringVar)
        self.gridSizeE.pack(side=TOP)

        self.maxValL = Label(self.top3, text="Maximum Value:", bg="white")
        self.maxValL.pack(side=TOP)
        self.maxValE = Entry(self.top3, textvariable=maxValStringVar)
        self.maxValE.pack(side=TOP)

        self.dayValL = Label(self.top3, text="Day(s) to consider:", bg="white")
        self.dayValL.pack(side=TOP)
        self.dayValE = Entry(self.top3, textvariable=dayValStringVar)
        self.dayValE.pack(side=TOP)

        self.trialValL = Label(self.top3, text="Trial(s) to consider:", bg="white")
        self.trialValL.pack(side=TOP)
        self.trialValE = Entry(self.top3, textvariable=trialValStringVar)
        self.trialValE.pack(side=TOP)

        Button(self.top3, text="Generate", command=lambda: self.heatmap(aExperiment), fg="black", bg="white").pack() 
Example 59
Project: Deep_Learning_Weather_Forecasting   Author: BruceBinBoxing   File: utils.py    Apache License 2.0 5 votes vote down vote up
def plot_prediction(x, y_true, y_pred, input_ruitu=None):
    """Plots the predictions.
    
    Arguments
    ---------
    x: Input sequence of shape (input_sequence_length,
        dimension_of_signal)
    y_true: True output sequence of shape (input_sequence_length,
        dimension_of_signal)
    y_pred: Predicted output sequence (input_sequence_length,
        dimension_of_signal)
    """

    plt.figure(figsize=(12, 3))

    output_dim = x.shape[-1]# feature dimension
    for j in range(output_dim):
        past = x[:, j] 
        true = y_true[:, j]
        pred = y_pred[:, j]
        if input_ruitu is not None:
            ruitu = input_ruitu[:, j]

        label1 = "Seen (past) values" if j==0 else "_nolegend_"
        label2 = "True future values" if j==0 else "_nolegend_"
        label3 = "Predictions" if j==0 else "_nolegend_"
        label4 = "Ruitu values" if j==0 else "_nolegend_"

        plt.plot(range(len(past)), past, "o-g",
                 label=label1)
        plt.plot(range(len(past),
                 len(true)+len(past)), true, "x--g", label=label2)
        plt.plot(range(len(past), len(pred)+len(past)), pred, "o--y",
                 label=label3)
        if input_ruitu is not None:
            plt.plot(range(len(past), len(ruitu)+len(past)), ruitu, "o--r",
                 label=label4)
    plt.legend(loc='best')
    plt.title("Predictions v.s. true values v.s. Ruitu")
    plt.show() 
Example 60
Project: Deep_Learning_Weather_Forecasting   Author: BruceBinBoxing   File: competition_model_class.py    Apache License 2.0 5 votes vote down vote up
def plot_prediction(self, x, y_true, y_pred, input_ruitu=None):
        """Plots the predictions.

        Arguments
        ---------
        x: Input sequence of shape (input_sequence_length,
            dimension_of_signal)
        y_true: True output sequence of shape (input_sequence_length,
            dimension_of_signal)
        y_pred: Predicted output sequence (input_sequence_length,
            dimension_of_signal)
        input_ruitu: Ruitu output sequence 
        """

        plt.figure(figsize=(12, 3))

        output_dim = x.shape[-1]# feature dimension
        for j in range(output_dim):
            past = x[:, j] 
            true = y_true[:, j]
            pred = y_pred[:, j]
            if input_ruitu is not None:
                ruitu = input_ruitu[:, j]

            label1 = "Seen (past) values" if j==0 else "_nolegend_"
            label2 = "True future values" if j==0 else "_nolegend_"
            label3 = "Predictions" if j==0 else "_nolegend_"
            label4 = "Ruitu values" if j==0 else "_nolegend_"

            plt.plot(range(len(past)), past, "o-g",
                     label=label1)
            plt.plot(range(len(past),
                     len(true)+len(past)), true, "x--g", label=label2)
            plt.plot(range(len(past), len(pred)+len(past)), pred, "o--y",
                     label=label3)
            if input_ruitu is not None:
                plt.plot(range(len(past), len(ruitu)+len(past)), ruitu, "o--r",
                     label=label4)
        plt.legend(loc='best')
        plt.title("Predictions v.s. true values v.s. Ruitu")
        plt.show() 
Example 61
Project: CAFA_assessment_tool   Author: ashleyzhou972   File: plot.py    GNU General Public License v3.0 5 votes vote down vote up
def plotMultiple(title,listofResults,smooth):
    '''
    supply lists of precision+recall+name lists
    '''
    fontP = FontProperties()
    fontP.set_size('small')
    num = len(listofResults)
    pal=sns.color_palette("Paired", num)
    colors=pal.as_hex()
    for j,i in enumerate(listofResults):
        linetype = '-'
        if smooth=='Y':
            ax = plt.subplot()
            precision = curveSmooth(i)[0][1:]
            recall = curveSmooth(i)[1][1:]
            ax.plot(recall,precision,linetype,color=colors[j],label=i.method+':\nF=%s C=%s'%(i.opt,i.coverage)) 
            ax.plot(i.recall[int(i.thres*100)],i.precision[int(i.thres*100)],'o',color=colors[j])
        elif smooth=='N':
            ax = plt.subplot()
            ax.plot(i.recall,i.precision,linetype,color=colors[j],label=i.method+':\nF=%s C=%s'%(i.opt,i.coverage))
            ax.plot(i.recall[int(i.thres*100)],i.precision[int(i.thres*100)],'o',color=colors[j])
    plt.axis([0,1,0,1])
    box = ax.get_position()
    ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
    plt.yticks(numpy.arange(0,1,0.1))
    plt.xlabel('Recall')
    plt.ylabel('Precision')
    ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
    plt.title(title)
    figurename = os.path.join('./plots/',title)       
    plt.savefig(figurename,dpi=200)
    plt.close() 
Example 62
Project: whatsapp-stats   Author: nielsrolf   File: analyze.py    Apache License 2.0 5 votes vote down vote up
def actual_categorical_plot(group, stat, keys, values):
    name = stat + " " + group
    plt.clf()
    plt.bar(range(len(keys)), values)
    plt.xticks(range(len(keys)), keys)
    plt.title(name)
    plt.savefig(PLOT_PATH + "/" + name+".png")
    plt.clf() 
Example 63
Project: whatsapp-stats   Author: nielsrolf   File: analyze.py    Apache License 2.0 5 votes vote down vote up
def timeline_plot(group, stat, keys, values, fig=None):
    """
    If fig is None, plot in a new figure
    If fig is not None, use the group as label and plot in that figure
    """
    def prepare(int_keys, values):
        # add 0 where keys are missing
        values = dict(zip(int_keys, values))
        keys = list(range(max(int_keys))) # add missing dates
        values = [values.get(i, 0) for i in keys] # add zero as value for the missing dates
        # prepare plotting as well
        locs = keys[::int(len(keys)/6)]
        dates = [get_str_date(i) for i in locs]
        return keys, values, locs, dates
    
    if fig is None:
        plt.clf()
        name = stat + " " + group
        keys, values, locs, dates = prepare(keys, values)
        plt.plot(keys, values)
        plt.xticks(locs, dates)
        plt.title(name)
        plt.savefig(PLOT_PATH + "/" + name+".png")
        plt.clf()
    else:
        keys, values, locs, dates = prepare(keys, values)
        plt.plot(keys, values, label=group)
        plt.xticks(locs, dates)



# -----
# Groups (combos from group_by and plots)
# ----- 
Example 64
Project: whatsapp-stats   Author: nielsrolf   File: analyze.py    Apache License 2.0 5 votes vote down vote up
def plot(self, stat_name, keys, values):
        plt.clf()
        fig = plt.figure()

        cats = list(dict(keys).keys()) # keys are cat, time pairs
        for cat in cats:
            filtered_values = [value for key, value in zip(keys, values) if key[0]==cat]
            time_labels = [key[1] for key in keys if key[0]==cat]
            self.time_group._plot(cat, stat_name, time_labels, filtered_values, fig)

        plt.legend()
        plt.title(stat_name + " " + self.name)
        plt.savefig(PLOT_PATH + "/" + self.name+" "+stat_name+".png")
        plt.close('all') 
Example 65
Project: ANN   Author: waynezv   File: ANN_large_v23.py    MIT License 5 votes vote down vote up
def show_image(self, prange):
        num_slices = self.data['real'].shape[0]
        plt.figure()
        for i in np.arange(num_slices):
            amp = np.sqrt(self.data['real'][i, :, :]**2 + self.data['imag'][i, :, :]**2)
            plt.subplot(2, 2, i+1)
            plt.imshow(amp, extent=prange)
            plt.title(i+1)
        plt.show() 
Example 66
Project: ANN   Author: waynezv   File: ANN.py    MIT License 5 votes vote down vote up
def show_image(self, prange):
        num_slices = self.data['real'].shape[0]
        plt.figure()
        for i in np.arange(num_slices):
            amp = np.sqrt(self.data['real'][i, :, :]**2 + self.data['imag'][i, :, :]**2)
            plt.subplot(2, 2, i+1)
            plt.imshow(amp, extent=prange)
            plt.title(i+1)
        plt.show() 
Example 67
Project: projection-methods   Author: akshayka   File: plot_residuals.py    GNU General Public License v3.0 4 votes vote down vote up
def main():
    parser = argparse.ArgumentParser()
    # --- input/output --- #
    parser.add_argument(
        'data', metavar='D',
        help=('glob matching pickled results to plot; results should be '
        'generated by experiment.py'))
    parser.add_argument(
        '-o', '--output', type=str, default=None,
        help=('output filename of plot (w/o extension); if None, plot is '
        'shown but not saved.'))
    # --- plot settings --- #
    parser.add_argument(
        '-t', '--title', type=str, default='Residuals for feasibility problem',
        help='plot title')
    args = vars(parser.parse_args())

    if args['output'] is not None:
        output_path = PosixPath(args['output'] + '.png')
        if output_path.is_file():
            raise ValueError('Output file %s already exists!' % str(output_path))

    data_paths = [PosixPath(f) for f in glob(args['data'])]
    data = []
    for p in data_paths:
        if not p.is_file():
            raise ValueError('File %s does not exist.' % str(p))
        with p.open('rb') as f:
            data.append(cPickle.load(f))

    plt.figure() 
    max_its = 0
    for d in data:
        res = d['res']
        res = [sum(r) for r in res]
        if 0 in res:
            res = [r + 1e-20 for r in res]
        it = range(len(res))
        if len(res) > max_its:
            max_its = len(res)
        plt.plot(it, res, label=d['name'])
    plt.semilogy()
    step = int(max_its / 10)
    plt.xticks(range(0, max_its+1, step))
    plt.title(args['title']) 
    plt.ylabel('residual')
    plt.xlabel('iterations')
    plt.legend()

    if args['output'] is not None:
        plt.savefig(str(output_path))
    else:
        datacursor(formatter='{label}'.format)
        plt.show() 
Example 68
Project: wikilinks   Author: trovdimi   File: heatmaps.py    MIT License 4 votes vote down vote up
def clicks_heatmap_first_occ():
    print 'loading'
    db = MySQLDatabase(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, DATABASE_NAME)
    db_worker_view = db.get_work_view()
    coords = db_worker_view.retrieve_all_links_coords_clicks_first_occ()
    print 'coord loaded'
    links = {}
    x = []
    y = []
    values = []
    for link in coords.values():
        x_normed = float(link['x'])/float(1920)
        y_normed = float(link['y'])/float(link['page_length'])
        if  x_normed <=1.0 and y_normed <=1.0:
            x.append(x_normed)
            y.append(y_normed)
            values.append(float(link['counts']))


    heatmap, xedges, yedges = np.histogram2d(x, y, bins=100, weights=values)
    extent = [xedges[0], xedges[-1], yedges[-1], yedges[0] ]

    fig_size = (2.4, 2)

    plt.clf()
    plt.figure(figsize=fig_size)

    plt.grid(True)
    plt.imshow(heatmap , extent=extent, origin='upper', norm=LogNorm(), cmap=plt.get_cmap('jet'))
    plt.colorbar()
    #plt.title("Clicks Heatmap Log Normalized")

    plt.show()
    plt.savefig('output/clicks_heatmap_lognormed_self_loop_first_occ.pdf')

    plt.clf()
    plt.figure(figsize=fig_size)

    plt.grid(True)
    plt.imshow(heatmap , extent=extent, origin='upper', norm=Normalize(), cmap=plt.get_cmap('jet'))
    plt.colorbar()
    #plt.title("Clicks Heatmap Normalized")

    plt.show()
    plt.savefig('output/clicks_heatmap_normed_self_loop_first_occ.pdf')
    print "done" 
Example 69
Project: wikilinks   Author: trovdimi   File: heatmaps.py    MIT License 4 votes vote down vote up
def clicks_heatmap_total():
    print 'loading'
    db = MySQLDatabase(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, DATABASE_NAME)
    db_worker_view = db.get_work_view()
    coords = db_worker_view.retrieve_all_links_coords_clicks()
    print 'coord loaded'
    links = {}
    x = []
    y = []
    values = []
    for coord in coords:
        x_normed = float(coord['x'])/float(1920)
        y_normed = float(coord['y'])/float(coord['page_length'])
        if x_normed <=1.0 and y_normed <=1.0:
            x.append(x_normed)
            y.append(y_normed)
            values.append(float(coord['counts']))

    heatmap, xedges, yedges = np.histogram2d(x, y, bins=100, weights=values)
    extent = [xedges[0], xedges[-1], yedges[-1], yedges[0] ]


    fig_size = (2.4, 2)

    plt.clf()
    plt.figure(figsize=fig_size)

    plt.grid(True)
    plt.imshow(heatmap , extent=extent, origin='upper', norm=LogNorm(), cmap=plt.get_cmap('jet'))
    plt.colorbar()
    #plt.title("Clicks Heatmap Log Normalized")

    plt.show()
    plt.savefig('output/clicks_heatmap_lognormed_self_loop_total.pdf')

    plt.clf()
    plt.figure(figsize=fig_size)

    plt.grid(True)
    plt.imshow(heatmap , extent=extent, origin='upper', norm=Normalize(), cmap=plt.get_cmap('jet'))
    plt.colorbar()
    #plt.title("Clicks Heatmap Normalized")

    plt.show()
    plt.savefig('output/clicks_heatmap_normed_self_loop_total.pdf')
    print "done" 
Example 70
Project: wikilinks   Author: trovdimi   File: heatmaps.py    MIT License 4 votes vote down vote up
def links_heatmap():
    #http://stackoverflow.com/questions/2369492/generate-a-heatmap-in-matplotlib-using-a-scatter-data-set
    # Get URLs from a text file, remove white space.
    print 'loading'
    db = MySQLDatabase(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, DATABASE_NAME)
    db_worker_view = db.get_work_view()
    coords = db_worker_view.retrieve_all_links_coords()
    print 'coord loaded'
    x=[]
    y=[]

    page_lenghts = db_worker_view.retrieve_all_page_lengths()
    print 'lenghts loaded'
    for coord in coords:
        x_normed = float(coord['x'])/float(1920)
        y_normed = float(coord['y'])/float(page_lenghts[coord['source_article_id']])
        if  x_normed <=1.0 and y_normed <=1.0:
            x.append(x_normed)
            y.append(y_normed)



    heatmap, xedges, yedges = np.histogram2d(x, y, bins=100)
    extent = [xedges[0], xedges[-1], yedges[-1], yedges[0]]

    fig_size = (2.4, 2)
    #fig_size = (3.5, 3)
    plt.clf()
    plt.figure(figsize=fig_size)
    plt.grid(True)

    plt.imshow(heatmap, extent=extent, origin='upper', norm=LogNorm(), cmap=plt.get_cmap('jet'))
    plt.colorbar()
    #plt.title("Links Heatmap Log Normalized")

    plt.show()
    plt.savefig('output/links_heatmap_lognormed_self_loop.pdf')

    plt.clf()
    plt.figure(figsize=fig_size)
    plt.grid(True)

    plt.imshow(heatmap , extent=extent, origin='upper', norm=Normalize(),cmap=plt.get_cmap('jet'))
    plt.colorbar()
    #plt.title("Links Heatmap Normalized")

    plt.show()
    plt.savefig('output/links_heatmap_normed_self_loop.pdf')

    print "done" 
Example 71
Project: OpenAPS   Author: medicinexlab   File: mlalgorithm.py    MIT License 4 votes vote down vote up
def analyze_ml_data(actual_bg_array, bg_prediction, bg_time_array, show_pred_plot, save_pred_plot, show_clarke_plot, save_clarke_plot, id_str, algorithm_str, minutes_str):
    """
    Function to analyze and plot the machine learning data. It takes in the actual_bg_array and the bg_prediction and compares
    the two with various analysis methods, such as root mean squared error, mean absolute error,
    R^2 coefficient of determination, and clarke error grid analysis.

    Input:      actual_bg_array                 The array of actual bg values
                bg_prediction                   The array of prediction bg values
                bg_time_array                   The array of times corresponding to bg_prediction
                show_pred_plot                  Boolean to show the prediction plot
                save_pred_plot                  Boolean to save the prediction plot
                show_clarke_plot                Boolean to show the clarke error grid
                save_clarke_plot                Boolean to save the clarke error grid
                id_str                          String of the ID
                algorithm_str                   String of the algorithm name
                minutes_str                     String of the number of minutes (both prediction and data minutes)
.
    Output:     None
    Usage:      analyze_ml_data(actual_bg_test_array, test_prediction, True, False, True, False, "00000001", "Linear Regression", "Pred30Data5")
    """

    #Root mean squared error
    rms = math.sqrt(metrics.mean_squared_error(actual_bg_array, bg_prediction))
    print "                Root Mean Squared Error: " + str(rms)
    print "                Mean Absolute Error: " + str(metrics.mean_absolute_error(actual_bg_array, bg_prediction))
    print "                R^2 Coefficient of Determination: " + str(metrics.r2_score(actual_bg_array, bg_prediction))

    plot, zone = ClarkeErrorGrid.clarke_error_grid(actual_bg_array, bg_prediction, id_str + " " + algorithm_str + " " + minutes_str)
    print "                Percent A:{}".format(float(zone[0]) / (zone[0] + zone[1] + zone[2] + zone[3] + zone[4]))
    print "                Percent C, D, E:{}".format(float(zone[2] + zone[3] + zone[4])/ (zone[0] + zone[1] + zone[2] + zone[3] + zone[4]))
    print "                Zones are A:{}, B:{}, C:{}, D:{}, E:{}\n".format(zone[0],zone[1],zone[2],zone[3],zone[4])
    if save_clarke_plot: plt.savefig(id_str + algorithm_str.replace(" ", "") + minutes_str + "clarke.png")
    if show_clarke_plot: plot.show()

    plt.clf()
    plt.plot(bg_time_array, actual_bg_array, label="Actual BG", color='black', linestyle='-')
    plt.plot(bg_time_array, bg_prediction, label="BG Prediction", color='black', linestyle=':')
    plt.title(id_str + " " + algorithm_str + " " + minutes_str + " BG Analysis")
    plt.ylabel("Blood Glucose Level (mg/dl)")
    plt.xlabel("Time (minutes)")
    plt.legend(loc='upper left')

    # SHOW/SAVE PLOT DEPENDING ON THE BOOLEAN PARAMETER
    if save_pred_plot: plt.savefig(id_str + algorithm_str.replace(" ","") + minutes_str + "plot.png")
    if show_pred_plot: plt.show()


#Preprocesses the data by the standard scaler relative to the train_data_matrix 
Example 72
Project: FRIDA   Author: LCAV   File: plotters.py    MIT License 4 votes vote down vote up
def plt_planewave(y_mic_noiseless, y_mic_noisy, mic=0, save_fig=False, **kwargs):
    """
    plot received planewaves at microhpnes
    :param y_mic_noiseless: the noiseless planewave
    :param y_mic_noisy: the noisy planewave
    :param mic: planewave at which microphone to plot
    :return:
    """
    if 'SNR' in kwargs:
        SNR = kwargs['SNR']
    else:
        SNR = 20 * np.log10(linalg.norm(y_mic_noiseless[mic, :].flatten('F')) /
                            linalg.norm((y_mic_noisy[mic, :] - y_mic_noiseless[mic, :]).flatten('F')))
    plt.figure(figsize=(6, 3), dpi=90)
    ax1 = plt.axes([0.1, 0.53, 0.85, 0.32])
    plt.plot(np.real(y_mic_noiseless[mic, :]), color=[0, 0.447, 0.741],
             linestyle='-', linewidth=1.5, label='noiseless', alpha=0.6)
    plt.plot(np.real(y_mic_noisy[mic, :]), color=[0.850, 0.325, 0.098],
             linestyle='-', linewidth=1.5, label='noisy', alpha=0.6)

    plt.xlim([0, y_mic_noisy.shape[1] - 1])
    # plt.xlabel(r'time snapshot', fontsize=11)
    plt.ylabel(r'$\Re\{y(\omega, t)\}$', fontsize=11)

    ax1.yaxis.major.locator.set_params(nbins=5)
    plt.legend(framealpha=0.5, scatterpoints=1, loc=0,
               fontsize=9, ncol=2, handletextpad=.2,
               columnspacing=1.7, labelspacing=0.1)

    plt.title(r'received planewaves at microphe {0} ($\mbox{{SNR}} = {1:.1f}$dB)'.format(repr(mic), SNR),
              fontsize=11)

    ax2 = plt.axes([0.1, 0.14, 0.85, 0.32])
    plt.plot(np.imag(y_mic_noiseless[mic, :]), color=[0, 0.447, 0.741],
             linestyle='-', linewidth=1.5, label='noiseless', alpha=0.6)
    plt.plot(np.imag(y_mic_noisy[mic, :]), color=[0.850, 0.325, 0.098],
             linestyle='-', linewidth=1.5, label='noisy', alpha=0.6)

    plt.xlim([0, y_mic_noisy.shape[1] - 1])
    plt.xlabel(r'time snapshot', fontsize=11)
    plt.ylabel(r'$\Im\{y(\omega, t)\}$', fontsize=11)

    ax2.yaxis.major.locator.set_params(nbins=5)

    if save_fig:
        if 'file_name' in kwargs:
            file_name = kwargs['file_name']
        else:
            file_name = 'planewave_mic{0}.pdf'.format(repr(mic))
        plt.savefig(file_name, format='pdf', dpi=300, transparent=True) 
Example 73
Project: mmdetection   Author: open-mmlab   File: analyze_logs.py    Apache License 2.0 4 votes vote down vote up
def plot_curve(log_dicts, args):
    if args.backend is not None:
        plt.switch_backend(args.backend)
    sns.set_style(args.style)
    # if legend is None, use {filename}_{key} as legend
    legend = args.legend
    if legend is None:
        legend = []
        for json_log in args.json_logs:
            for metric in args.keys:
                legend.append('{}_{}'.format(json_log, metric))
    assert len(legend) == (len(args.json_logs) * len(args.keys))
    metrics = args.keys

    num_metrics = len(metrics)
    for i, log_dict in enumerate(log_dicts):
        epochs = list(log_dict.keys())
        for j, metric in enumerate(metrics):
            print('plot curve of {}, metric is {}'.format(
                args.json_logs[i], metric))
            if metric not in log_dict[epochs[0]]:
                raise KeyError('{} does not contain metric {}'.format(
                    args.json_logs[i], metric))

            if 'mAP' in metric:
                xs = np.arange(1, max(epochs) + 1)
                ys = []
                for epoch in epochs:
                    ys += log_dict[epoch][metric]
                ax = plt.gca()
                ax.set_xticks(xs)
                plt.xlabel('epoch')
                plt.plot(xs, ys, label=legend[i * num_metrics + j], marker='o')
            else:
                xs = []
                ys = []
                num_iters_per_epoch = log_dict[epochs[0]]['iter'][-1]
                for epoch in epochs:
                    iters = log_dict[epoch]['iter']
                    if log_dict[epoch]['mode'][-1] == 'val':
                        iters = iters[:-1]
                    xs.append(
                        np.array(iters) + (epoch - 1) * num_iters_per_epoch)
                    ys.append(np.array(log_dict[epoch][metric][:len(iters)]))
                xs = np.concatenate(xs)
                ys = np.concatenate(ys)
                plt.xlabel('iter')
                plt.plot(
                    xs, ys, label=legend[i * num_metrics + j], linewidth=0.5)
            plt.legend()
        if args.title is not None:
            plt.title(args.title)
    if args.out is None:
        plt.show()
    else:
        print('save curve to: {}'.format(args.out))
        plt.savefig(args.out)
        plt.cla() 
Example 74
Project: Kaggle-Statoil-Challenge   Author: adodd202   File: main-tf-audio.py    MIT License 4 votes vote down vote up
def plot_curve(self, save_path, args, model):
        title = 'PyTorch Model:' + str((type(model).__name__)).upper() + ', DataSet:' + str(args.dataset).upper() + ',' \
                + 'Params: %.2fM' % (
            sum(p.numel() for p in model.parameters()) / 1000000.0) + ', Seed: %.2f' % args.manualSeed
        dpi = 80
        width, height = 1200, 800
        legend_fontsize = 10
        scale_distance = 48.8
        figsize = width / float(dpi), height / float(dpi)

        fig = plt.figure(figsize=figsize)
        x_axis = np.array([i for i in range(self.total_epoch)])  # epochs
        y_axis = np.zeros(self.total_epoch)

        plt.xlim(0, self.total_epoch)
        plt.ylim(0, 1.0)
        interval_y = 0.05 / 3.0
        interval_x = 1
        plt.xticks(np.arange(0, self.total_epoch + interval_x, interval_x))
        plt.yticks(np.arange(0, 1.0 + interval_y, interval_y))
        plt.grid()
        plt.title(title, fontsize=18)
        plt.xlabel('EPOCH', fontsize=16)
        plt.ylabel('LOSS/ACC', fontsize=16)

        y_axis[:] = self.epoch_accuracy[:, 0] / 100.0
        plt.plot(x_axis, y_axis, color='g', linestyle='-', label='tr-accuracy/100', lw=2)
        plt.legend(loc=4, fontsize=legend_fontsize)

        y_axis[:] = self.epoch_accuracy[:, 1] / 100.0
        plt.plot(x_axis, y_axis, color='y', linestyle='-', label='val-accuracy/100', lw=2)
        plt.legend(loc=4, fontsize=legend_fontsize)

        y_axis[:] = self.epoch_losses[:, 0]
        plt.plot(x_axis, y_axis, color='r', linestyle=':', label='tr-loss', lw=2)
        plt.legend(loc=4, fontsize=legend_fontsize)

        y_axis[:] = self.epoch_losses[:, 1]
        plt.plot(x_axis, y_axis, color='b', linestyle=':', label='val-loss', lw=4)
        plt.legend(loc=4, fontsize=legend_fontsize)

        if save_path is not None:
            fig.savefig(save_path, dpi=dpi, bbox_inches='tight')
            # print('---- save figure {} into {}'.format(title, save_path))
        plt.close(fig) 
Example 75
Project: programsynthesishunting   Author: flexgp   File: save_plots.py    GNU General Public License v3.0 4 votes vote down vote up
def save_pareto_fitness_plot():
    """
    Saves a plot of the current fitness for a pareto front.

    :return: Nothing
    """

    from algorithm.parameters import params

    # Initialise up figure instance.
    fig = plt.figure()
    ax1 = fig.add_subplot(1, 1, 1)

    # Set up iterator for color plotting.
    color = iter(plt.cm.jet(np.linspace(0, 1, len(first_pareto_list))))

    # Get labels for individual fitnesses.
    ffs = params['FITNESS_FUNCTION'].fitness_functions

    # Find the direction for step lines to "bend"
    step_dir = 'pre' if ffs[0].maximise else 'post'

    # Plot data.
    for i, gen in enumerate(first_pareto_list):
        c = next(color)
        ax1.step(gen[0], gen[1], linestyle='--',
                 where=step_dir, color=c, lw=0.35, alpha=0.25)
        ax1.plot(gen[0], gen[1], 'o', color=c, ms=1)

    # Set labels with class names.
    ax1.set_xlabel(ffs[0].__class__.__name__, fontsize=14)
    ax1.set_ylabel(ffs[1].__class__.__name__, fontsize=14)

    # Plot title and legend.
    plt.title("First pareto fronts by generation")

    # Set up colorbar instead of legend. Normalise axis to scale of data.
    sm = plt.cm.ScalarMappable(cmap="jet",
                   norm=plt.Normalize(vmin=0, vmax=len(first_pareto_list) - 1))

    # Fake up the array of the scalar mappable.
    sm._A = []

    # Plot the colorbar.
    cbar = plt.colorbar(sm, ticks=[0, len(first_pareto_list) - 1])

    # Set label of colorbar.
    # cbar.ax.get_yaxis().labelpad = 15
    cbar.ax.set_ylabel('Generation', rotation=90)

    # Save plot and close.
    plt.savefig(path.join(params['FILE_PATH'], "fitness.pdf"))
    plt.close() 
Example 76
Project: DensityPeakCluster   Author: lanbing510   File: plot_utils.py    MIT License 4 votes vote down vote up
def plot_scatter_diagram(which_fig, x, y, x_label = 'x', y_label = 'y', title = 'title', style_list = None):
	'''
	Plot scatter diagram

	Args:
		which_fig  : which sub plot
		x          : x array
		y          : y array
		x_label    : label of x pixel
		y_label    : label of y pixel
		title      : title of the plot
	'''
	styles = ['k', 'g', 'r', 'c', 'm', 'y', 'b', '#9400D3','#C0FF3E']
	assert len(x) == len(y)
	if style_list != None:
		assert len(x) == len(style_list) and len(styles) >= len(set(style_list))
	plt.figure(which_fig)
	plt.clf()
	if style_list == None:
		plt.plot(x, y, color=styles[0], linestyle='.', marker='.')
	else:
		clses = set(style_list)
		xs, ys = {}, {}
		for i in xrange(len(x)):
			try:
				xs[style_list[i]].append(x[i])
				ys[style_list[i]].append(y[i])
			except KeyError:
				xs[style_list[i]] = [x[i]]
				ys[style_list[i]] = [y[i]]
		added = 1
		for idx, cls in enumerate(clses):
			if cls == -1:
				style = styles[0]
				added = 0
			else:
				style = styles[idx + added]
			plt.plot(xs[cls], ys[cls], color=style, linestyle='.', marker='.')
	plt.title(title)
	plt.xlabel(x_label)
	plt.ylabel(y_label)
	plt.show() 
Example 77
Project: helloworld   Author: pip-uninstaller-python   File: matplotlibTest.py    GNU General Public License v2.0 4 votes vote down vote up
def scatter():
    fig = plt.figure()  # 建立一个表格
    fig.add_subplot(3, 3, 1)
    n = 128
    X = np.random.normal(0, 1, n)
    Y = np.random.normal(0, 1, n)
    T = np.arctan2(Y, X)  # 上色
    plt.axes([0.025, 0.025, 0.95, 0.95])  # 显示范围
    plt.scatter(X, Y, s=75, c=T, alpha=.5)  # s点的大小, c颜色, alpha透明度
    plt.xlim(-1.5, 1.5), plt.xticks([])  # x范围
    plt.ylim(-1.5, 1.5), plt.yticks([])  # x范围
    plt.axis()
    plt.title("scatter")
    plt.xlabel("x")
    plt.ylabel("y")
    # plt.show()

    # other
    fig = plt.figure()  # 建立一个表格
    ax = fig.add_subplot(3, 3, 1)
    n = 128
    X = np.random.normal(0, 1, n)
    Y = np.random.normal(0, 1, n)
    T = np.arctan2(Y, X)  # 上色
    # plt.axes([0.025, 0.025, 0.95, 0.95])  # 显示范围
    ax.scatter(X, Y, s=75, c=T, alpha=.5)  # s点的大小, c颜色, alpha透明度
    plt.xlim(-1.5, 1.5), plt.xticks([])  # x范围
    plt.ylim(-1.5, 1.5), plt.yticks([])  # x范围
    plt.axis()
    plt.title("scatter")
    plt.xlabel("x")
    plt.ylabel("y")
    # plt.show()

    # 散点图
    # fig = plt.figure()  # 建立一个表格
    fig.add_subplot(332)  # n>10不可用这个数值
    n = 10  # 10个点
    X = np.arange(n)  # 构建一个数列 0-9
    # 营造出来一种有变化的效果
    Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)  # *随机数, 随机数范围在0.5-1.0之间
    Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
    # 然后画出来
    plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')
    plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')
    for x, y in zip(X, Y1):  # 添加注释 位置, 格式, ha水平位置, va垂直位置
        plt.text(x + 0.4, y + 0.05, '%.2f' % y, ha='center', va='bottom')
    for x, y in zip(X, Y1):
        plt.text(x + 0.4, -y - 0.05, '%.2f' % y, ha='center', va='top')
    plt.show()


# 柱状图 
Example 78
Project: cvpr2018-hnd   Author: kibok90   File: test.py    MIT License 4 votes vote down vote up
def print_results(work_name, results, save_path, hierarchical_measure=False, start_time=time.time()):

    if hierarchical_measure:
        mtypes = ['acc', 'HF']
    else:
        mtypes = ['acc']
    
    print(save_path)
    print('{work_name}; '.format(work_name=work_name), end='')
    print('{time:8.3f} s'.format(time=time.time()-start_time))
    for m, mtype in enumerate(mtypes):
        print('bias: {res:7.4f}; '.format(res=results['acc']['g_bias']), end='')
        print('{mtype:4s}'.format(mtype=mtype), end='')
        print('known: {res:5.2f}; '.format(res=results[mtype]['g_known']*100.), end='')
        print('novel: {res:5.2f}; '.format(res=results[mtype]['g_novel']*100.), end='')
        if mtype == 'acc':
            print('auc  : {res:5.2f}; '.format(res=results[mtype]['auc']*100.))
        else:
            print('hmean: {res:5.2f}; '.format(res=results[mtype]['g_harmonic']*100.))
    
        # plot known vs. novel
        plt.figure(m)
        plt.plot(results[mtype]['known'], results[mtype]['novel'], 'k.-')
        if mtype == 'HE':
            plt.xticks(np.arange(0., 11., 1.))
            plt.yticks(np.arange(0., 11., 1.))
            plt.axis([0., 10., 0., 10.])
        else:
            plt.xticks(np.arange(0., 1.1, .1))
            plt.yticks(np.arange(0., 1.1, .1))
            plt.axis([0., 1., 0., 1.])
        plt.grid()
        plt.xlabel('known class accuracy')
        plt.ylabel('novel class accuracy')
        plt.title('known: {res:5.2f}; '.format(res=results[mtype]['g_known']*100.) + \
                  'novel: {res:5.2f}; '.format(res=results[mtype]['g_novel']*100.) + \
                  'hmean: {res:5.2f}; '.format(res=results[mtype]['g_harmonic']*100.) + \
                  'auc  : {res:5.2f}; '.format(res=results[mtype]['auc']*100.)
                 )
        plt.savefig(save_path + '_' + work_name + '_' + mtype + '.png')
        plt.clf()
        plt.close() 
Example 79
Project: Deep_Learning_Weather_Forecasting   Author: BruceBinBoxing   File: seq2seq_class.py    Apache License 2.0 4 votes vote down vote up
def plot_prediction(self, x, y_true, y_pred, intervals=None, input_ruitu=None, pi_degree=0.8, renorm_flag=False):
        """Plots the predictions.

        Arguments
        ---------
        x: Input sequence of shape (input_sequence_length,
            dimension_of_signal) E.g. (28, 1)
        y_true: True output sequence of shape (input_sequence_length,
            dimension_of_signal) E.g. (35, 1)
        y_pred: Predicted output sequence (input_sequence_length,
            dimension_of_signal) E.g. (35, 1)
        input_ruitu: Ruitu output sequence E.g. (35, 1)
        pi_degree: Confident Level such as 0.95, 0.9, 0.8, and 0.68 etc.
        """
        plt.figure(figsize=(12, 3))
        output_dim = x.shape[-1]# feature dimension
        for j in range(output_dim):
            past = x[:, j] 
            true = y_true[:, j]
            pred = y_pred[:, j]
            if input_ruitu is not None:
                ruitu = input_ruitu[:, j]
            if intervals is not None:
                pi_var = intervals[:, j]
                pi_var = np.sqrt(np.exp(pi_var))
                
            label1 = "Seen (past) values" if j==0 else "_nolegend_"
            label2 = "True future values" if j==0 else "_nolegend_"
            label3 = "Predictions" if j==0 else "_nolegend_"
            label4 = "Ruitu values" if j==0 else "_nolegend_"
            label5 = "Lower-Upper bound" if j==0 else "_nolegend_"

            plt.plot(range(len(past)), past, "o-g",
                     label=label1)
            plt.plot(range(len(past),
                     len(true)+len(past)), true, "x--g", label=label2)
            plt.plot(range(len(past), len(pred)+len(past)), pred, ".--b",
                     label=label3)
            if input_ruitu is not None:
                plt.plot(range(len(past), len(ruitu)+len(past)), ruitu, ".--r",
                     label=label4)
            if intervals is not None:
                #print(intervals.shape)
                print(pi_var.shape)
                up_bound = pred + self.pi_dic[pi_degree]*pi_var
                low_bound = pred - self.pi_dic[pi_degree]*pi_var
                plt.fill_between(range(len(past), len(ruitu)+len(past)), 
                                 up_bound, low_bound, facecolor='blue', alpha=0.1)              
                
        plt.legend(loc='best')
        plt.title("Predictions v.s. true values v.s. Ruitu")
        plt.show() 
Example 80
Project: Deep_Learning_Weather_Forecasting   Author: BruceBinBoxing   File: competition_model_class.py    Apache License 2.0 4 votes vote down vote up
def plot_prediction(self, x, y_true, y_pred, intervals=None, input_ruitu=None, pi_degree=0.8, renorm_flag=False):
        """Plots the predictions.

        Arguments
        ---------
        x: Input sequence of shape (input_sequence_length,
            dimension_of_signal) E.g. (28, 1)
        y_true: True output sequence of shape (input_sequence_length,
            dimension_of_signal) E.g. (35, 1)
        y_pred: Predicted output sequence (input_sequence_length,
            dimension_of_signal) E.g. (35, 1)
        input_ruitu: Ruitu output sequence E.g. (35, 1)
        pi_degree: Confident Level such as 0.95, 0.9, 0.8, and 0.68 etc.
        """

        plt.figure(figsize=(12, 3))


        output_dim = x.shape[-1]# feature dimension
        for j in range(output_dim):
            past = x[:, j] 
            true = y_true[:, j]
            pred = y_pred[:, j]
            if input_ruitu is not None:
                ruitu = input_ruitu[:, j]
            if intervals is not None:
                pi_var = intervals[:, j]
                pi_var = np.sqrt(np.exp(pi_var))
                
            label1 = "Seen (past) values" if j==0 else "_nolegend_"
            label2 = "True future values" if j==0 else "_nolegend_"
            label3 = "Predictions" if j==0 else "_nolegend_"
            label4 = "Ruitu values" if j==0 else "_nolegend_"
            label5 = "Lower-Upper bound" if j==0 else "_nolegend_"

            plt.plot(range(len(past)), past, "o-g",
                     label=label1)
            plt.plot(range(len(past),
                     len(true)+len(past)), true, "x--g", label=label2)
            plt.plot(range(len(past), len(pred)+len(past)), pred, ".--b",
                     label=label3)
            if input_ruitu is not None:
                plt.plot(range(len(past), len(ruitu)+len(past)), ruitu, ".--r",
                     label=label4)
            if intervals is not None:
                #print(intervals.shape)
                print(pi_var.shape)
                up_bound = pred + self.pi_dic[pi_degree]*pi_var
                low_bound = pred - self.pi_dic[pi_degree]*pi_var
                plt.fill_between(range(len(past), len(ruitu)+len(past)), 
                                 up_bound, low_bound, facecolor='blue', alpha=0.1)              
                
        plt.legend(loc='best')
        plt.title("Predictions v.s. true values v.s. Ruitu")
        plt.show()