Python matplotlib.pyplot.xlabel() Examples

The following are code examples for showing how to use matplotlib.pyplot.xlabel(). 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: ReinforcementLearningBookExamples   Author: Shawn-Guo-CN   File: 1TenArmedBandits.py    GNU General Public License v3.0 7 votes vote down vote up
def gradient_algorithm(num_bandits, episode_length):
    agents = [Agent(gradient=True, step_size=0.1, gradient_baseline=True),
              Agent(gradient=True, step_size=0.1, gradient_baseline=False),
              Agent(gradient=True, step_size=0.4, gradient_baseline=True),
              Agent(gradient=True, step_size=0.4, gradient_baseline=False)]

    best_action_counts, _ = play_game(num_bandits, episode_length, agents, 4.)
    labels = ['alpha = 0.1, with baseline',
              'alpha = 0.1, without baseline',
              'alpha = 0.4, with baseline',
              'alpha = 0.4, without baseline']
    global figure_index
    plt.figure(figure_index)
    figure_index += 1
    for i in range(0, len(agents)):
        plt.plot(best_action_counts[i], label=labels[i])
    plt.xlabel('Steps')
    plt.ylabel('% Optimal action')
    plt.legend()


# following three example functions are for understanding the playing procedure
# following is for testing whether agent and bandit are rightly implemented 
Example 4
Project: fenics-topopt   Author: zfergus   File: stress_gui.py    MIT License 6 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 5
Project: OpenAPS   Author: medicinexlab   File: oldpred.py    MIT License 6 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 6
Project: mmdetection   Author: open-mmlab   File: recall.py    Apache License 2.0 6 votes vote down vote up
def plot_num_recall(recalls, proposal_nums):
    """Plot Proposal_num-Recalls curve.

    Args:
        recalls(ndarray or list): shape (k,)
        proposal_nums(ndarray or list): same shape as `recalls`
    """
    if isinstance(proposal_nums, np.ndarray):
        _proposal_nums = proposal_nums.tolist()
    else:
        _proposal_nums = proposal_nums
    if isinstance(recalls, np.ndarray):
        _recalls = recalls.tolist()
    else:
        _recalls = recalls

    import matplotlib.pyplot as plt
    f = plt.figure()
    plt.plot([0] + _proposal_nums, [0] + _recalls)
    plt.xlabel('Proposal num')
    plt.ylabel('Recall')
    plt.axis([0, proposal_nums.max(), 0, 1])
    f.show() 
Example 7
Project: mmdetection   Author: open-mmlab   File: recall.py    Apache License 2.0 6 votes vote down vote up
def plot_iou_recall(recalls, iou_thrs):
    """Plot IoU-Recalls curve.

    Args:
        recalls(ndarray or list): shape (k,)
        iou_thrs(ndarray or list): same shape as `recalls`
    """
    if isinstance(iou_thrs, np.ndarray):
        _iou_thrs = iou_thrs.tolist()
    else:
        _iou_thrs = iou_thrs
    if isinstance(recalls, np.ndarray):
        _recalls = recalls.tolist()
    else:
        _recalls = recalls

    import matplotlib.pyplot as plt
    f = plt.figure()
    plt.plot(_iou_thrs + [1.0], _recalls + [0.])
    plt.xlabel('IoU')
    plt.ylabel('Recall')
    plt.axis([iou_thrs.min(), 1, 0, 1])
    f.show() 
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: ortholotree   Author: oxpeter   File: internal.py    GNU General Public License v2.0 6 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 12
Project: ReinforcementLearningBookExamples   Author: Shawn-Guo-CN   File: 1TenArmedBandits.py    GNU General Public License v3.0 6 votes vote down vote up
def epsilon_greedy(num_bandits, episode_length):
    epsilons = [0., 0.1, 0.01]
    agents = []
    for ep_idx, ep in enumerate(epsilons):
        agents.append(Agent(epsilon=ep, sample_average=True))
    best_action_counts, average_rewards = play_game(num_bandits, episode_length, agents)
    global figure_index
    plt.figure(figure_index)
    figure_index += 1
    for eps, counts in zip(epsilons, best_action_counts):
        plt.plot(counts, label='epsilon = ' + str(eps))
    plt.xlabel('Steps')
    plt.ylabel('% optimal action')
    plt.legend()
    plt.figure(figure_index)
    figure_index += 1
    for eps, rewards in zip(epsilons, average_rewards):
        plt.plot(rewards, label='epsilon = ' + str(eps))
    plt.xlabel('Steps')
    plt.ylabel('average reward')
    plt.legend()


# generate figure 2.3 
Example 13
Project: beta3_IRT   Author: yc14600   File: plots.py    MIT License 6 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 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: 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 16
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 17
Project: CNN_based_indoor_localization   Author: weimengmeng1999   File: epoch_graph.py    GNU General Public License v3.0 6 votes vote down vote up
def loss_plot(self, loss_type):
        iters = range(len(self.losses[loss_type]))
        plt.figure()
        # acc
        plt.plot(iters, self.accuracy[loss_type], 'r', label='train acc')
        # loss
        plt.plot(iters, self.losses[loss_type], 'g', label='train loss')
        if loss_type == 'epoch':
            # val_acc
            plt.plot(iters, self.val_acc[loss_type], 'b', label='val acc')
            # val_loss
            plt.plot(iters, self.val_loss[loss_type], 'k', label='val loss')
        plt.grid(True)
        plt.xlabel(loss_type)
        plt.ylabel('acc-loss')
        plt.legend(loc="upper right")
        plt.show() 
Example 18
Project: cs294-112_hws   Author: xuwd11   File: plot_part1.py    MIT License 6 votes vote down vote up
def plot_12(data):
    r1, r2, r3, r4 = data
    plt.figure()
    add_plot(r1, 'MeanReward100Episodes');
    add_plot(r1, 'BestMeanReward', 'vanilla DQN');
    add_plot(r2, 'MeanReward100Episodes');
    add_plot(r2, 'BestMeanReward', 'double DQN');
    plt.xlabel('Time step');
    plt.ylabel('Reward');
    plt.legend();
    plt.savefig(
        os.path.join('results', 'p12.png'),
        bbox_inches='tight',
        transparent=True,
        pad_inches=0.1
    ) 
Example 19
Project: cs294-112_hws   Author: xuwd11   File: plot_3.py    MIT License 6 votes vote down vote up
def plot_3(data):
    x = data.Iteration.unique()
    y_mean = data.groupby('Iteration').mean()
    y_std = data.groupby('Iteration').std()
    
    sns.set(style="darkgrid", font_scale=1.5)
    value = 'AverageReturn'
    plt.plot(x, y_mean[value], label=data['Condition'].unique()[0] + '_train');
    plt.fill_between(x, y_mean[value] - y_std[value], y_mean[value] + y_std[value], alpha=0.2);
    value = 'ValAverageReturn'
    plt.plot(x, y_mean[value], label=data['Condition'].unique()[0] + '_test');
    plt.fill_between(x, y_mean[value] - y_std[value], y_mean[value] + y_std[value], alpha=0.2);
    
    plt.xlabel('Iteration')
    plt.ylabel('AverageReturn')
    plt.legend(loc='best') 
Example 20
Project: HandPostureTranslator   Author: Wissben   File: ArchGenerators.py    GNU General Public License v3.0 6 votes vote down vote up
def plotCallback(variator: Variator, model: Model):
    # get last history
    pathlib.Path('Graphs').mkdir(parents=True, exist_ok=True)
    history = variator.histories[-1]
    # summarize history for accuracy
    fig = plt.figure()
    plt.plot(history.history['acc'])
    plt.plot(history.history['val_acc'])
    plt.title(variator.currentParameters['modelName'] + ' accuracy')
    plt.ylabel('accuracy')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper left')
    fig.savefig("Graphs/"+variator.currentParameters['modelName'] + '.png', dpi=fig.dpi)
    # from PIL import Image
    # Image.open(variator.currentParameters['modelName']+'.png').show()
    # plt.show()
    # plot(plt) 
Example 21
Project: Kaggler   Author: jeongyoonlee   File: classification.py    MIT License 6 votes vote down vote up
def plot_pr_curve(y, p):
    precision, recall, _ = precision_recall_curve(y, p)

    plt.step(recall, precision, color='b', alpha=0.2, where='post')
    plt.fill_between(recall, precision, step='post', alpha=0.2, color='b')
    plt.xlabel('Recall')
    plt.ylabel('Precision')
    plt.ylim([0.0, 1.05])
    plt.xlim([0.0, 1.0]) 
Example 22
Project: simulated-annealing-tsp   Author: chncyhn   File: anneal.py    MIT License 5 votes vote down vote up
def plot_learning(self):
        """
        Plot the fitness through iterations.
        """
        plt.plot([i for i in range(len(self.fitness_list))], self.fitness_list)
        plt.ylabel("Fitness")
        plt.xlabel("Iteration")
        plt.show() 
Example 23
Project: PEAKachu   Author: tbischler   File: window.py    ISC License 5 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 24
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 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: 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 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: 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 29
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 30
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 31
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 32
Project: Kaggle-Statoil-Challenge   Author: adodd202   File: utils.py    MIT License 5 votes vote down vote up
def plot(self, names=None):
        plt.figure()
        plt.plot()
        legend_text = []
        for logger in self.loggers:
            legend_text += plot_overlap(logger, names)
        legend_text = ['WRN-28-10+Ours (error 17.65%)', 'WRN-28-10 (error 18.68%)']
        plt.legend(legend_text, loc=0)
        plt.ylabel('test error (%)')
        plt.xlabel('epoch')
        plt.grid(True) 
Example 33
Project: Random-Erasing   Author: zhunzhong07   File: logger.py    Apache License 2.0 5 votes vote down vote up
def plot(self, names=None):
        plt.figure()
        plt.plot()
        legend_text = []
        for logger in self.loggers:
            legend_text += plot_overlap(logger, names)
        legend_text = ['WRN-28-10+Ours (error 17.65%)', 'WRN-28-10 (error 18.68%)']
        plt.legend(legend_text, loc=0)
        plt.ylabel('test error (%)')
        plt.xlabel('epoch')
        plt.grid(True) 
Example 34
Project: deep-learning-note   Author: wdxtub   File: utils.py    MIT License 5 votes vote down vote up
def semilogy(x_vals, y_vals, x_label, y_label, x2_vals=None, y2_vals=None, legend=None):
    plt.xlabel(x_label)
    plt.ylabel(y_label)
    plt.semilogy(x_vals, y_vals)
    if x2_vals and y2_vals:
        plt.semilogy(x2_vals, y2_vals, linestyle=':')
        plt.legend(legend)
    plt.show() 
Example 35
Project: deep-learning-note   Author: wdxtub   File: utils.py    MIT License 5 votes vote down vote up
def show_trace_2d(f, results):
    plt.plot(*zip(*results), '-o', color='#ff7f0e')
    x1, x2 = np.meshgrid(np.arange(-5.5, 1.0, 0.1), np.arange(-3.0, 1.0, 0.1))
    plt.contour(x1, x2, f(x1, x2), colors='#1f77b4')
    plt.xlabel('x1')
    plt.ylabel('x2')
    plt.show() 
Example 36
Project: deep-learning-note   Author: wdxtub   File: utils.py    MIT License 5 votes vote down vote up
def train_opt(optimizer_fn, states, hyperparams, features, labels,
              batch_size=10, num_epochs=2):
    # 初始化模型
    net, loss = linreg, squared_loss

    w = torch.nn.Parameter(torch.tensor(np.random.normal(0, 0.01, size=(features.shape[1], 1)), dtype=torch.float32),
                           requires_grad=True)
    b = torch.nn.Parameter(torch.zeros(1, dtype=torch.float32), requires_grad=True)

    def eval_loss():
        return loss(net(features, w, b), labels).mean().item()

    ls = [eval_loss()]
    data_iter = torch.utils.data.DataLoader(
        torch.utils.data.TensorDataset(features, labels), batch_size, shuffle=True)

    for _ in range(num_epochs):
        start = time.time()
        for batch_i, (X, y) in enumerate(data_iter):
            l = loss(net(X, w, b), y).mean()  # 使用平均损失

            # 梯度清零
            if w.grad is not None:
                w.grad.data.zero_()
                b.grad.data.zero_()

            l.backward()
            optimizer_fn([w, b], states, hyperparams)  # 迭代模型参数
            if (batch_i + 1) * batch_size % 100 == 0:
                ls.append(eval_loss())  # 每100个样本记录下当前训练误差
    # 打印结果和作图
    print('loss: %f, %f sec per epoch' % (ls[-1], time.time() - start))
    plt.plot(np.linspace(0, num_epochs, len(ls)), ls)
    plt.xlabel('epoch')
    plt.ylabel('loss')
    plt.show()


# 本函数与原书不同的是这里第一个参数优化器函数而不是优化器的名字
# 例如: optimizer_fn=torch.optim.SGD, optimizer_hyperparams={"lr": 0.05} 
Example 37
Project: deep-learning-note   Author: wdxtub   File: utils.py    MIT License 5 votes vote down vote up
def train_opt_pytorch(optimizer_fn, optimizer_hyperparams, features, labels,
                      batch_size=10, num_epochs=2):
    # 初始化模型
    net = nn.Sequential(
        nn.Linear(features.shape[-1], 1)
    )
    loss = nn.MSELoss()
    optimizer = optimizer_fn(net.parameters(), **optimizer_hyperparams)

    def eval_loss():
        return loss(net(features).view(-1), labels).item() / 2

    ls = [eval_loss()]
    data_iter = torch.utils.data.DataLoader(
        torch.utils.data.TensorDataset(features, labels), batch_size, shuffle=True)

    for _ in range(num_epochs):
        start = time.time()
        for batch_i, (X, y) in enumerate(data_iter):
            # 除以2是为了和train_ch7保持一致, 因为squared_loss中除了2
            l = loss(net(X).view(-1), y) / 2

            optimizer.zero_grad()
            l.backward()
            optimizer.step()
            if (batch_i + 1) * batch_size % 100 == 0:
                ls.append(eval_loss())
    # 打印结果和作图
    print('loss: %f, %f sec per epoch' % (ls[-1], time.time() - start))
    plt.plot(np.linspace(0, num_epochs, len(ls)), ls)
    plt.xlabel('epoch')
    plt.ylabel('loss')
    plt.show() 
Example 38
Project: deep-learning-note   Author: wdxtub   File: 38_gradient_descent.py    MIT License 5 votes vote down vote up
def show_trace(res):
    n = max(abs(min(res)), abs(max(res)), 10)
    f_line = np.arange(-n, n, 0.1)
    plt.plot(f_line, [x * x for x in f_line])
    plt.plot(res, [x * x for x in res], '-o')
    plt.xlabel('x')
    plt.ylabel('f(x)')
    plt.show() 
Example 39
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 40
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 41
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 42
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 43
Project: order   Author: ipudu   File: plot.py    MIT License 5 votes vote down vote up
def plot_ionic(self):
        """plot distribution"""

        data1 = np.loadtxt(self.fprefix+'_'+self.taskname+'_ti.dat')
        data2 = np.loadtxt(self.fprefix+'_'+self.taskname+'_iaafp.dat')

        #plot setting
        #plt.rcParams['font.family'] = 'serif'
        #plt.rcParams['font.serif'] = 'Ubuntu'
        #plt.rcParams['font.monospace'] = 'Ubuntu Mono'
        plt.rcParams['font.size'] = 10
        plt.rcParams['axes.labelsize'] = 10
        #plt.rcParams['axes.labelweight'] = 'bold'
        plt.rcParams['xtick.labelsize'] = 8
        plt.rcParams['ytick.labelsize'] = 8
        plt.rcParams['legend.fontsize'] = 10
        plt.rcParams['figure.titlesize'] = 12

        #clean last plot
        plt.clf()

        plt.xlabel("Simulation time(ps)")
        plt.ylabel("Charge from ions crossing the plane (e)")

        x1 = data1[:,0]
        y1 = data1[:,1]

        x2 = data2[:,0]
        y2 = data2[:,1]


        plt.plot(x1, y1, label='ti')
        plt.plot(x2, y2, label='iaafp')
        plt.legend()
        
        figure = self.fprefix + '_' + self.taskname.upper() + '.pdf'
        plt.savefig(figure, bbox_inches="tight") 
Example 44
Project: ReinforcementLearningBookExamples   Author: Shawn-Guo-CN   File: 1TenArmedBandits.py    GNU General Public License v3.0 5 votes vote down vote up
def figure2_1(bandit, dim=2000):
    global figure_index
    plt.figure(figure_index)
    figure_index += 1
    sns.violinplot(data=bandit.get_reward_samples(dim=dim))
    plt.xlabel("Action")
    plt.ylabel("Reward distribution")


# generate figure 2.2 
Example 45
Project: ReinforcementLearningBookExamples   Author: Shawn-Guo-CN   File: 1TenArmedBandits.py    GNU General Public License v3.0 5 votes vote down vote up
def optimal_initial_values(num_bandits, episode_length):
    agents = [Agent(epsilon=0, initial_value=5, step_size=.1),
              Agent(epsilon=0.1, initial_value=0, step_size=0.1)]
    best_action_counts, _ = play_game(num_bandits, episode_length, agents)
    global figure_index
    plt.figure(figure_index)
    plt.plot(best_action_counts[0], label='epsilon = 0, q = 5')
    plt.plot(best_action_counts[1], label='epsilon = 0.1, q = 0')
    plt.xlabel('Steps')
    plt.ylabel('% optimal action')
    plt.legend()


# for figure 2.4 
Example 46
Project: ReinforcementLearningBookExamples   Author: Shawn-Guo-CN   File: 1TenArmedBandits.py    GNU General Public License v3.0 5 votes vote down vote up
def ucb(num_bandits, episode_length):
    agents = [Agent(epsilon=0, step_size=0.1, UCB_param=2),
              Agent(epsilon=0.1, step_size=0.1)]
    _, avg_rewards = play_game(num_bandits, episode_length, agents)
    global figure_index
    plt.figure(figure_index)
    figure_index += 1
    plt.plot(avg_rewards[0], label='UCB c = 2')
    plt.plot(avg_rewards[1], label='epsilon greedy epsilon = 0.1')
    plt.xlabel('Steps')
    plt.ylabel('Average reward')
    plt.legend()


# for figure 2.5 
Example 47
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 48
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 49
Project: DiscEvolution   Author: rbooth200   File: run_model.py    GNU General Public License v3.0 5 votes vote down vote up
def _plot_grid(model):
    grid = model.disc.grid 

    try:
        eps = model.disc.dust_frac.sum(0)
        plt.subplot(222)
        plt.loglog(grid.Rc, eps)
        plt.xlabel('$R$')
        plt.ylabel('$\epsilon$')
        plt.ylim(ymin=1e-4)
        plt.subplot(223)
        plt.loglog(grid.Rc, model.disc.Stokes()[1])
        plt.xlabel('$R$')
        plt.ylabel('$St$')
        plt.subplot(224)
        plt.loglog(grid.Rc, model.disc.grain_size[1])
        plt.xlabel('$R$') 
        plt.ylabel('$a\,[\mathrm{cm}]$')

        plt.subplot(221)
        l, = plt.loglog(grid.Rc, model.disc.Sigma_D.sum(0), '--')
        c = l.get_color()
    except AttributeError:
        c = None

    plt.loglog(grid.Rc, model.disc.Sigma_G, c=c)
    plt.xlabel('$R$')
    plt.ylabel('$\Sigma_\mathrm{G, D}$')
    plt.ylim(ymin=1e-5) 
Example 50
Project: DataSciUF-Tutorial-Student   Author: jdamiani27   File: class_vis.py    MIT License 5 votes vote down vote up
def prettyPicture(clf, X_test, y_test):
    x_min = 0.0; x_max = 10.5
    y_min = 0.0; y_max = 10.5
    
    # Plot the decision boundary. For that, we will assign a color to each
    # point in the mesh [x_min, m_max]x[y_min, y_max].
    h = .01  # step size in the mesh
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])

    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())

    plt.pcolormesh(xx, yy, Z, cmap=pl.cm.seismic)

    # Plot also the test points
    grade_sig = [X_test[ii][0] for ii in range(0, len(X_test)) if y_test[ii]==2]
    bumpy_sig = [X_test[ii][1] for ii in range(0, len(X_test)) if y_test[ii]==2]
    grade_bkg = [X_test[ii][0] for ii in range(0, len(X_test)) if y_test[ii]==4]
    bumpy_bkg = [X_test[ii][1] for ii in range(0, len(X_test)) if y_test[ii]==4]

    plt.scatter(grade_sig, bumpy_sig, color = "b", label="benign")
    plt.scatter(grade_bkg, bumpy_bkg, color = "r", label="malignant")
    plt.legend()
    plt.xlabel("uniformity_cell_shape")
    plt.ylabel("bare_nuclei")

    plt.savefig("test.png")