Python seaborn.set_style() Examples

The following are 30 code examples of seaborn.set_style(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module seaborn , or try the search function .
Example #1
Source File: training.py    From adversarial-policies with MIT License 6 votes vote down vote up
def visualize_score(command, styles, tb_dir, score_paths, fig_dir):
    baseline = [util.load_datasets(path) for path in score_paths]
    baseline = pd.concat(baseline)

    sns.set_style("whitegrid")
    for style in styles:
        plt.style.use(vis_styles.STYLES[style])

    out_paths = command(tb_dir, baseline)
    for out_path in out_paths:
        visualize_training_ex.add_artifact(filename=out_path)

    for observer in visualize_training_ex.observers:
        if hasattr(observer, "dir"):
            logger.info(f"Copying from {observer.dir} to {fig_dir}")
            copy_tree(observer.dir, fig_dir)
            break 
Example #2
Source File: evals.py    From acnn with GNU General Public License v3.0 6 votes vote down vote up
def plot_kim_curve(tmp):
    sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 5})
    sns.set_style("darkgrid")

    plt.figure(figsize=(20, 10))
    plt.hold('on')
    plt.plot(np.linspace(0, 0.3, 100), tmp['kc_avg'])
    plt.ylim([0, 1])

#    plt.figure(figsize=(10,5))
#    plt.hold('on')
#    legend = []
#    for k,v in bench_res.iteritems():
#        plt.plot(np.linspace(0, 0.3, 100), v['kc_avg'])
#        legend.append(k)
#    plt.ylim([0, 1])
#    plt.legend(legend, loc='lower right') 
Example #3
Source File: plot_return.py    From MinAtar with GNU General Public License v3.0 6 votes vote down vote up
def plot_avg_return(file_name, granularity):
    plotting_data = torch.load(file_name + "_processed_data")

    returns = plotting_data['returns']
    unique_frames = plotting_data['unique_frames']
    x_len = len(unique_frames)
    x_index = [i for i in numpy.arange(0, x_len, granularity)]

    x = unique_frames[::granularity]
    y = numpy.transpose(numpy.array(returns)[x_index, :])

    f, ax = plt.subplots(1, 1, figsize=[3, 2], dpi=300)
    sns.set_style("ticks")
    sns.set_context("paper")

    # Find the order of magnitude of the last frame
    order = int(math.log10(unique_frames[-1]))
    range_frames = int(unique_frames[-1]/ (10**order))

    sns.tsplot(data=y, time=numpy.array(x)/(10**order), color='b')
    ax.set_xticks(numpy.arange(range_frames + 1))
    plt.show()

    f.savefig(file_name + "_avg_return.pdf", bbox_inches="tight")
    plt.close(f) 
Example #4
Source File: word_question.py    From guesswhat with Apache License 2.0 6 votes vote down vote up
def __init__(self, path, games, logger, suffix):
        super(WordVsQuestion, self).__init__(path, self.__class__.__name__, suffix)


        w_by_q = []
        for game in games:
            for q in game.questions:
                q = re.sub('[?]', '', q)
                words = re.findall(r'\w+', q)
                w_by_q.append(len(words))

        sns.set_style("whitegrid", {"axes.grid": False})

        # ratio question/words
        f = sns.distplot(w_by_q, norm_hist=True, kde=False, bins=np.arange(2.5, 15.5, 1), color="g")

        f.set_xlabel("Number of words", {'size': '14'})
        f.set_ylabel("Ratio of questions", {'size': '14'})
        f.set_xlim(2.5, 14.5)
        f.set_ylim(bottom=0) 
Example #5
Source File: visualize.py    From adversarial-policies with MIT License 6 votes vote down vote up
def main():
    logging.basicConfig(level=logging.DEBUG)

    output_dir = "data/density/visualize"
    os.makedirs(output_dir, exist_ok=True)

    styles = ["paper", "density_twocol"]
    sns.set_style("whitegrid")
    for style in styles:
        plt.style.use(vis_styles.STYLES[style])

    plot_heatmaps(output_dir)
    plot_comparative_densities(output_dir)
    bar_chart(
        ENV_NAMES,
        victim_id="1",
        n_components=20,
        covariance="full",
        savefile=f"{output_dir}/bar_chart.pdf",
    ) 
Example #6
Source File: question_dialogues.py    From guesswhat with Apache License 2.0 6 votes vote down vote up
def __init__(self, path, games, logger, suffix):
        super(QuestionVsDialogue, self).__init__(path, self.__class__.__name__, suffix)

        q_by_d = []
        for game in games:
            q_by_d.append(len(game.questions))

        sns.set_style("whitegrid", {"axes.grid": False})


        #ratio question/dialogues
        f = sns.distplot(q_by_d, norm_hist =True, kde=False, bins=np.arange(0.5, 25.5, 1))
        f.set_xlim(0.5,25.5)
        f.set_ylim(bottom=0)

        f.set_xlabel("Number of questions", {'size':'14'})
        f.set_ylabel("Ratio of dialogues", {'size':'14'}) 
Example #7
Source File: visualizations.py    From fitlins with Apache License 2.0 6 votes vote down vote up
def _run_interface(self, runtime):
        import matplotlib
        matplotlib.use('Agg')
        import seaborn as sns
        from matplotlib import pyplot as plt
        sns.set_style('white')
        plt.rcParams['svg.fonttype'] = 'none'
        plt.rcParams['image.interpolation'] = 'nearest'

        data = self._load_data(self.inputs.data)
        out_name = fname_presuffix(self.inputs.data,
                                   suffix='.' + self.inputs.image_type,
                                   newpath=runtime.cwd,
                                   use_ext=False)
        self._visualize(data, out_name)
        self._results['figure'] = out_name
        return runtime 
Example #8
Source File: chart.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 6 votes vote down vote up
def image(path: str, costs: Dict[str, int]) -> str:
    ys = ['0', '1', '2', '3', '4', '5', '6', '7+', 'X']
    xs = [costs.get(k, 0) for k in ys]
    sns.set_style('white')
    sns.set(font='Concourse C3', font_scale=3)
    g = sns.barplot(ys, xs, palette=['#cccccc'] * len(ys))
    g.axes.yaxis.set_ticklabels([])
    rects = g.patches
    sns.set(font='Concourse C3', font_scale=2)
    for rect, label in zip(rects, xs):
        if label == 0:
            continue
        height = rect.get_height()
        g.text(rect.get_x() + rect.get_width()/2, height + 0.5, label, ha='center', va='bottom')
    g.margins(y=0, x=0)
    sns.despine(left=True, bottom=True)
    g.get_figure().savefig(path, transparent=True, pad_inches=0, bbox_inches='tight')
    plt.clf() # Clear all data from matplotlib so it does not persist across requests.
    return path 
Example #9
Source File: callbacks.py    From keras-utilities with MIT License 6 votes vote down vote up
def on_train_begin(self, logs={}):
        sns.set_style("whitegrid")
        sns.set_style("whitegrid", {"grid.linewidth": 0.5,
                                    "lines.linewidth": 0.5,
                                    "axes.linewidth": 0.5})
        flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e",
                  "#2ecc71"]
        sns.set_palette(sns.color_palette(flatui))
        # flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"]
        # sns.set_palette(sns.color_palette("Set2", 10))

        plt.ion()  # set plot to animated
        width = self.width * (1 + len(self.get_metrics(logs)))
        height = self.height
        self.fig = plt.figure(figsize=(width, height))

        # move it to the upper left corner
        move_figure(self.fig, 25, 25) 
Example #10
Source File: callbacks.py    From keras-utilities with MIT License 6 votes vote down vote up
def on_train_begin(self, logs={}):
        for layer in self.get_trainable_layers():
            for param in self.parameters:
                if any(w for w in layer.weights if param in w.name.split("_")):
                    name = layer.name + "_" + param
                    self.layers_stats[name]["values"] = numpy.asarray(
                        []).ravel()
                    for s in self.stats:
                        self.layers_stats[name][s] = []

        # plt.style.use('ggplot')
        plt.ion()  # set plot to animated
        width = 3 * (1 + len(self.stats))
        height = 2 * len(self.layers_stats)
        self.fig = plt.figure(figsize=(width, height))
        # sns.set_style("whitegrid")
        self.draw_plot() 
Example #11
Source File: timit.py    From pyroomacoustics with MIT License 5 votes vote down vote up
def plot(self):
        try:
            import matplotlib.pyplot as plt
            import seaborn as sns
        except ImportError:
            return

        sns.set_style('white')

        L = self.samples.shape[0]
        plt.plot(np.arange(L)/self.fs, self.samples)
        plt.xlim((0,L/self.fs))
        plt.xlabel('Time')
        plt.title(self.word) 
Example #12
Source File: Auto_NLP.py    From Auto_ViML with Apache License 2.0 5 votes vote down vote up
def plot_confusion_matrix(y_test,y_pred, model_name='Model'):
    """
    This plots a beautiful confusion matrix based on input: ground truths and predictions
    """
    #Confusion Matrix
    '''Plotting CONFUSION MATRIX'''
    import matplotlib.pyplot as plt
    import seaborn as sns
    sns.set_style('darkgrid')

    '''Display'''
    from IPython.core.display import display, HTML
    display(HTML("<style>.container { width:95% !important; }</style>"))
    pd.options.display.float_format = '{:,.2f}'.format

    #Get the confusion matrix and put it into a df
    from sklearn.metrics import confusion_matrix, f1_score

    cm = confusion_matrix(y_test, y_pred)

    cm_df = pd.DataFrame(cm,
                         index = np.unique(y_test).tolist(),
                         columns = np.unique(y_test).tolist(),
                        )

    #Plot the heatmap
    plt.figure(figsize=(12, 8))

    sns.heatmap(cm_df,
                center=0,
                cmap=sns.diverging_palette(220, 15, as_cmap=True),
                annot=True,
                fmt='g')

    plt.title(' %s \nF1 Score(avg = micro): %0.2f \nF1 Score(avg = macro): %0.2f' %(
        model_name,f1_score(y_test, y_pred, average='micro'),f1_score(y_test, y_pred, average='macro')),
              fontsize = 13)
    plt.ylabel('True label', fontsize = 13)
    plt.xlabel('Predicted label', fontsize = 13)
    plt.show();
############################################################################################## 
Example #13
Source File: attention_allocation_experiment_plotting.py    From ml-fairness-gym with Apache License 2.0 5 votes vote down vote up
def plot_discovered_occurred_ratio_range(dataframe, file_path=''):
  """Plot the range of discovered incidents/occurred range between locations."""
  plot_height = 5
  aspect_ratio = 1.3
  sns.set_style('whitegrid')
  sns.despine()

  sns.catplot(
      x='param_value',
      y='discovered/occurred range',
      data=dataframe,
      hue='agent_type',
      kind='bar',
      palette='muted',
      height=plot_height,
      aspect=aspect_ratio)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Discovered/occurred range', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  # plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.savefig(file_path + '.pdf', bbox_inches='tight')

  sns.catplot(
      x='param_value',
      y='discovered/occurred range weighted',
      data=dataframe,
      hue='agent_type',
      kind='bar',
      palette='muted',
      height=plot_height,
      aspect=aspect_ratio)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Delta', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  # plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.savefig(file_path + '_weighted.pdf', bbox_inches='tight') 
Example #14
Source File: plaidplotter.py    From plaidbench with Apache License 2.0 5 votes vote down vote up
def set_style():
    sns.set_style("whitegrid", {    
        "font.family": "serif",
        "font.serif": ["Times", "Palatino", "serif"]
    }) 
Example #15
Source File: 04-optimize-simionescu.py    From Hands-On-Genetic-Algorithms-with-Python with MIT License 5 votes vote down vote up
def main():

    # create initial population (generation 0):
    population = toolbox.populationCreator(n=POPULATION_SIZE)

    # prepare the statistics object:
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("min", np.min)
    stats.register("avg", np.mean)

    # define the hall-of-fame object:
    hof = tools.HallOfFame(HALL_OF_FAME_SIZE)

    # perform the Genetic Algorithm flow with elitism:
    population, logbook = elitism.eaSimpleWithElitism(population, toolbox, cxpb=P_CROSSOVER, mutpb=P_MUTATION,
                                              ngen=MAX_GENERATIONS, stats=stats, halloffame=hof, verbose=True)

    # print info for best solution found:
    best = hof.items[0]
    print("-- Best Individual = ", best)
    print("-- Best Fitness = ", best.fitness.values[0])

    # extract statistics:
    minFitnessValues, meanFitnessValues = logbook.select("min", "avg")

    # plot statistics:
    sns.set_style("whitegrid")
    plt.plot(minFitnessValues, color='red')
    plt.plot(meanFitnessValues, color='green')
    plt.xlabel('Generation')
    plt.ylabel('Min / Average Fitness')
    plt.title('Min and Average fitness over Generations')

    plt.show() 
Example #16
Source File: 05-optimize-simionescu-second.py    From Hands-On-Genetic-Algorithms-with-Python with MIT License 5 votes vote down vote up
def main():

    # create initial population (generation 0):
    population = toolbox.populationCreator(n=POPULATION_SIZE)

    # prepare the statistics object:
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("min", np.min)
    stats.register("avg", np.mean)

    # define the hall-of-fame object:
    hof = tools.HallOfFame(HALL_OF_FAME_SIZE)

    # perform the Genetic Algorithm flow with elitism:
    population, logbook = elitism.eaSimpleWithElitism(population, toolbox, cxpb=P_CROSSOVER, mutpb=P_MUTATION,
                                              ngen=MAX_GENERATIONS, stats=stats, halloffame=hof, verbose=True)

    # print info for best solution found:
    best = hof.items[0]
    print("-- Best Individual = ", best)
    print("-- Best Fitness = ", best.fitness.values[0])

    # extract statistics:
    minFitnessValues, meanFitnessValues = logbook.select("min", "avg")

    # plot statistics:
    sns.set_style("whitegrid")
    plt.plot(minFitnessValues, color='red')
    plt.plot(meanFitnessValues, color='green')
    plt.xlabel('Generation')
    plt.ylabel('Min / Average Fitness')
    plt.title('Min and Average fitness over Generations')

    plt.show() 
Example #17
Source File: 01-optimize-eggholder.py    From Hands-On-Genetic-Algorithms-with-Python with MIT License 5 votes vote down vote up
def main():

    # create initial population (generation 0):
    population = toolbox.populationCreator(n=POPULATION_SIZE)

    # prepare the statistics object:
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("min", np.min)
    stats.register("avg", np.mean)

    # define the hall-of-fame object:
    hof = tools.HallOfFame(HALL_OF_FAME_SIZE)

    # perform the Genetic Algorithm flow with elitism:
    population, logbook = elitism.eaSimpleWithElitism(population, toolbox, cxpb=P_CROSSOVER, mutpb=P_MUTATION,
                                              ngen=MAX_GENERATIONS, stats=stats, halloffame=hof, verbose=True)

    # print info for best solution found:
    best = hof.items[0]
    print("-- Best Individual = ", best)
    print("-- Best Fitness = ", best.fitness.values[0])

    # extract statistics:
    minFitnessValues, meanFitnessValues = logbook.select("min", "avg")

    # plot statistics:
    sns.set_style("whitegrid")
    plt.plot(minFitnessValues, color='red')
    plt.plot(meanFitnessValues, color='green')
    plt.xlabel('Generation')
    plt.ylabel('Min / Average Fitness')
    plt.title('Min and Average fitness over Generations')

    plt.show() 
Example #18
Source File: 03-solve-tsp.py    From Hands-On-Genetic-Algorithms-with-Python with MIT License 5 votes vote down vote up
def main():

    # create initial population (generation 0):
    population = toolbox.populationCreator(n=POPULATION_SIZE)

    # prepare the statistics object:
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("min", np.min)
    stats.register("avg", np.mean)

    # define the hall-of-fame object:
    hof = tools.HallOfFame(HALL_OF_FAME_SIZE)

    # perform the Genetic Algorithm flow with hof feature added:
    population, logbook = elitism.eaSimpleWithElitism(population, toolbox, cxpb=P_CROSSOVER, mutpb=P_MUTATION,
                                              ngen=MAX_GENERATIONS, stats=stats, halloffame=hof, verbose=True)

    # print best individual info:
    best = hof.items[0]
    print("-- Best Ever Individual = ", best)
    print("-- Best Ever Fitness = ", best.fitness.values[0])

    # plot best solution:
    plt.figure(1)
    tsp.plotData(best)

    # plot statistics:
    minFitnessValues, meanFitnessValues = logbook.select("min", "avg")
    plt.figure(2)
    sns.set_style("whitegrid")
    plt.plot(minFitnessValues, color='red')
    plt.plot(meanFitnessValues, color='green')
    plt.xlabel('Generation')
    plt.ylabel('Min / Average Fitness')
    plt.title('Min and Average fitness over Generations')

    # show both plots:
    plt.show() 
Example #19
Source File: 02-solve-tsp-first-attempt.py    From Hands-On-Genetic-Algorithms-with-Python with MIT License 5 votes vote down vote up
def main():

    # create initial population (generation 0):
    population = toolbox.populationCreator(n=POPULATION_SIZE)

    # prepare the statistics object:
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("min", np.min)
    stats.register("avg", np.mean)

    # define the hall-of-fame object:
    hof = tools.HallOfFame(HALL_OF_FAME_SIZE)

    # perform the Genetic Algorithm flow with hof feature added:
    population, logbook = algorithms.eaSimple(population, toolbox, cxpb=P_CROSSOVER, mutpb=P_MUTATION,
                                              ngen=MAX_GENERATIONS, stats=stats, halloffame=hof, verbose=True)

    # print best individual info:
    best = hof.items[0]
    print("-- Best Ever Individual = ", best)
    print("-- Best Ever Fitness = ", best.fitness.values[0])

    # plot best solution:
    plt.figure(1)
    tsp.plotData(best)

    # plot statistics:
    minFitnessValues, meanFitnessValues = logbook.select("min", "avg")
    plt.figure(2)
    sns.set_style("whitegrid")
    plt.plot(minFitnessValues, color='red')
    plt.plot(meanFitnessValues, color='green')
    plt.xlabel('Generation')
    plt.ylabel('Min / Average Fitness')
    plt.title('Min and Average fitness over Generations')

    # show both plots:
    plt.show() 
Example #20
Source File: b_sbn_arm.py    From ARM-gradient with MIT License 5 votes vote down vote up
def fig_gnrt(figs,epoch,show=False,bny=True,name_fig=None):
    '''
    input:N*28*28
    '''
    sns.set_style("whitegrid", {'axes.grid' : False})
    plt.ioff()
    
    if bny:
        b = figs > 0.5
        figs = b.astype('float')
    nx = ny = 10
    canvas = np.empty((28*ny, 28*nx))
    for i in range(nx):
        for j in range(ny):
            canvas[(nx-i-1)*28:(nx-i)*28, j*28:(j+1)*28] = figs[i*nx+j]
    
    plt.figure(figsize=(8, 10))        
    plt.imshow(canvas, origin="upper", cmap="gray")
    plt.tight_layout()
    if name_fig == None:
        path = os.getcwd()+'/out/'
        if not os.path.exists(path):
            os.makedirs(path)
        name_fig = path + str(epoch)+'.png'
    plt.savefig(name_fig, bbox_inches='tight') 
    plt.close('all')
    if show:
        plt.show()   
    

#%% 
Example #21
Source File: sucess_dialogue_length.py    From guesswhat with Apache License 2.0 5 votes vote down vote up
def __init__(self, path, games, logger, suffix):
        super(SuccessDialogueLength, self).__init__(path, self.__class__.__name__, suffix)

        status_list = []
        status_count = collections.defaultdict(int)
        length_list = []

        for game in games:

            length_list.append(len(game.questions))

            status_count[game.status] += 1
            status_list.append(game.status)


        success = np.array([s == "success" for s in status_list]) + 0
        failure = np.array([s == "failure" for s in status_list]) + 0
        incomp  = np.array([s == "incomplete" for s in status_list]) + 0

        sns.set_style("whitegrid", {"axes.grid": False})

        if sum(incomp) > 0:
            columns = ['Size of Dialogues', 'Success', 'Failure', 'Incomplete']
            data = np.array([length_list, success, failure, incomp]).transpose()
        else:
            columns = ['Size of Dialogues', 'Success', 'Failure']
            data = np.array([length_list, success, failure]).transpose()

        df = pd.DataFrame(data, columns=columns)
        df = df.convert_objects(convert_numeric=True)
        df = df.groupby('Size of Dialogues').sum()
        df = df.div(df.sum(axis=1), axis=0)
        #df = df.sort_values(by='Success')
        f = df.plot(kind="bar", stacked=True, width=1, alpha=0.3)

        f.set_xlim(-0.5,29.5)

        plt.xlabel("Size of Dialogues", {'size':'14'})
        plt.ylabel("Success ratio", {'size':'14'}) 
Example #22
Source File: plot.py    From pytorch-asr with GNU General Public License v3.0 5 votes vote down vote up
def plot_llk(train_elbo, test_elbo):
    import matplotlib.pyplot as plt
    import scipy as sp
    import seaborn as sns
    import pandas as pd
    plt.figure(figsize=(30, 10))
    sns.set_style("whitegrid")
    data = np.concatenate([np.arange(len(test_elbo))[:, sp.newaxis], -test_elbo[:, sp.newaxis]], axis=1)
    df = pd.DataFrame(data=data, columns=['Training Epoch', 'Test ELBO'])
    g = sns.FacetGrid(df, size=10, aspect=1.5)
    g.map(plt.scatter, "Training Epoch", "Test ELBO")
    g.map(plt.plot, "Training Epoch", "Test ELBO")
    plt.savefig(str(Path(result_dir, 'test_elbo_vae.png')))
    plt.close('all') 
Example #23
Source File: graph.py    From pipedream with MIT License 5 votes vote down vote up
def plot_cdfs(self, cdfs, output_directory):
        import matplotlib
        matplotlib.use('Agg')
        from matplotlib import pyplot as plt
        from matplotlib.backends.backend_pdf import PdfPages
        import seaborn as sns
        matplotlib.rc('text', usetex=True)
        sns.set_style('ticks')
        sns.set_style({'font.family':'sans-serif'})
        flatui = ['#002A5E', '#FD151B', '#8EBA42', '#348ABD', '#988ED5', '#777777', '#8EBA42', '#FFB5B8']
        sns.set_palette(flatui)
        paper_rc = {'lines.linewidth': 2, 'lines.markersize': 10}
        sns.set_context("paper", font_scale=3,  rc=paper_rc)
        current_palette = sns.color_palette()

        plt.figure(figsize=(10, 4))
        ax = plt.subplot2grid((1, 1), (0, 0), colspan=1)

        labels = ["Compute", "Activations", "Parameters"]
        for i in range(3):
            cdf = [cdfs[j][i] for j in range(len(cdfs))]
            ax.plot(range(len(cdfs)), cdf,  label=labels[i],
                    linewidth=2)
        ax.set_xlim([0, None])
        ax.set_ylim([0, 100])

        ax.set_xlabel("Layer ID")
        ax.set_ylabel("CDF (\%)")
        plt.legend()

        with PdfPages(os.path.join(output_directory, "cdf.pdf")) as pdf:
            pdf.savefig(bbox_inches='tight') 
Example #24
Source File: plot.py    From pipedream with MIT License 5 votes vote down vote up
def plot(values, epochs_to_plot, ylimit, ylabel, output_filepath):
    import matplotlib
    matplotlib.use('Agg')
    from matplotlib import pyplot as plt
    from matplotlib.backends.backend_pdf import PdfPages
    import seaborn as sns
    matplotlib.rc('text', usetex=True)
    sns.set_style('ticks')
    sns.set_style({'font.family':'sans-serif'})
    flatui = ['#002A5E', '#FD151B', '#8EBA42', '#348ABD', '#988ED5', '#777777', '#8EBA42', '#FFB5B8']
    sns.set_palette(flatui)
    paper_rc = {'lines.linewidth': 2, 'lines.markersize': 10}
    sns.set_context("paper", font_scale=3,  rc=paper_rc)
    current_palette = sns.color_palette()

    plt.figure(figsize=(10, 4))
    ax = plt.subplot2grid((1, 1), (0, 0), colspan=1)

    for epoch_to_plot in epochs_to_plot:
        values_to_plot = values[epoch_to_plot]
        ax.plot(range(len(values_to_plot)), values_to_plot,
                label="Epoch %d" % epoch_to_plot,
                linewidth=2)
    ax.set_xlim([0, None])
    ax.set_ylim([0, ylimit])

    ax.set_xlabel("Layer ID")
    ax.set_ylabel(ylabel)
    plt.legend()

    with PdfPages(output_filepath) as pdf:
        pdf.savefig(bbox_inches='tight') 
Example #25
Source File: timit.py    From pyroomacoustics with MIT License 5 votes vote down vote up
def plot(self, L=512, hop=128, zpb=0, phonems=False, **kwargs):

        try:
            import matplotlib.pyplot as plt
            import seaborn as sns
        except ImportError:
            return

        sns.set_style('white')
        X = stft(self.data, L=L, hop=hop, zp_back=zpb, transform=np.fft.rfft, win=np.hanning(L+zpb))
        X = 10*np.log10(np.abs(X)**2).T

        plt.imshow(X, origin='lower', aspect='auto')

        ticks = []
        ticklabels = []

        if phonems:
            for phonem in self.phonems:
                plt.axvline(x=phonem['bnd'][0]/hop)
                plt.axvline(x=phonem['bnd'][1]/hop)
                ticks.append((phonem['bnd'][1]+phonem['bnd'][0])/2/hop)
                ticklabels.append(phonem['name'])

        else:
            for word in self.words:
                plt.axvline(x=word.boundaries[0]/hop)
                plt.axvline(x=word.boundaries[1]/hop)
                ticks.append((word.boundaries[1]+word.boundaries[0])/2/hop)
                ticklabels.append(word.word)

        plt.xticks(ticks, ticklabels, rotation=-45)
        plt.yticks([],[])
        plt.tick_params(axis='both', which='major', labelsize=14) 
Example #26
Source File: attention_allocation_experiment_plotting.py    From ml-fairness-gym with Apache License 2.0 5 votes vote down vote up
def plot_total_miss_discovered(dataframe, file_path=''):
  """Plot bar charts comparing agents total missed and discovered incidents."""
  plot_height = 5
  aspect_ratio = 1.3
  sns.set_style('whitegrid')
  sns.despine()

  sns.catplot(
      x='param_value',
      y='total_missed',
      data=dataframe,
      hue='agent_type',
      kind='bar',
      palette='muted',
      height=plot_height,
      aspect=aspect_ratio,
      legend=False)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Total missed incidents', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.savefig(file_path + '_missed.pdf', bbox_inches='tight')

  sns.catplot(
      x='param_value',
      y='total_discovered',
      data=dataframe,
      hue='agent_type',
      kind='bar',
      palette='muted',
      height=plot_height,
      aspect=aspect_ratio,
      legend=False)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Total discovered incidents', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.savefig(file_path + '_discovered.pdf', bbox_inches='tight') 
Example #27
Source File: Auto_NLP.py    From Auto_ViML with Apache License 2.0 5 votes vote down vote up
def plot_confusion_matrix(y_test,y_pred, model_name='Model'):
    """
    This plots a beautiful confusion matrix based on input: ground truths and predictions
    """
    #Confusion Matrix
    '''Plotting CONFUSION MATRIX'''
    import matplotlib.pyplot as plt
    import seaborn as sns
    sns.set_style('darkgrid')

    '''Display'''
    from IPython.core.display import display, HTML
    display(HTML("<style>.container { width:95% !important; }</style>"))
    pd.options.display.float_format = '{:,.2f}'.format

    #Get the confusion matrix and put it into a df
    from sklearn.metrics import confusion_matrix, f1_score

    cm = confusion_matrix(y_test, y_pred)

    cm_df = pd.DataFrame(cm,
                         index = np.unique(y_test).tolist(),
                         columns = np.unique(y_test).tolist(),
                        )

    #Plot the heatmap
    plt.figure(figsize=(12, 8))

    sns.heatmap(cm_df,
                center=0,
                cmap=sns.diverging_palette(220, 15, as_cmap=True),
                annot=True,
                fmt='g')

    plt.title(' %s \nF1 Score(avg = micro): %0.2f \nF1 Score(avg = macro): %0.2f' %(
        model_name,f1_score(y_test, y_pred, average='micro'),f1_score(y_test, y_pred, average='macro')),
              fontsize = 13)
    plt.ylabel('True label', fontsize = 13)
    plt.xlabel('Predicted label', fontsize = 13)
    plt.show();
############################################################################################## 
Example #28
Source File: app.py    From smallrnaseq with GNU General Public License v3.0 5 votes vote down vote up
def plot_results(res, path):
    """Some results plots"""

    if res is None or len(res) == 0:
        return
    counts = base.pivot_count_data(res, idxcols=['name','ref'])
    x = base.get_fractions_mapped(res)
    print (x)
    import seaborn as sns
    sns.set_style('white')
    sns.set_context("paper",font_scale=1.2)
    fig = plotting.plot_fractions(x)
    fig.savefig(os.path.join(path,'libraries_mapped.png'))
    fig = plotting.plot_sample_counts(counts)
    fig.savefig(os.path.join(path,'total_per_sample.png'))
    fig = plotting.plot_read_count_dists(counts)
    fig.savefig(os.path.join(path,'top_mapped.png'))
    scols,ncols = base.get_column_names(counts)
    for l,df in counts.groupby('ref'):
        if 'mirbase' in l:
            fig = plotting.plot_read_count_dists(df)
            fig.savefig(os.path.join(path,'top_%s.png' %l))
    #if len(scols)>1:
    #    fig = plotting.expression_clustermap(counts)
    #    fig.savefig(os.path.join(path,'expr_map.png'))
    return 
Example #29
Source File: model.py    From neural-cryptography-tensorflow with MIT License 5 votes vote down vote up
def plot_errors(self):
        """
        Plot Lowest Decryption Errors achieved by Bob and Eve per epoch
        """
        sns.set_style("darkgrid")
        plt.plot(self.bob_errors)
        plt.plot(self.eve_errors)
        plt.legend(['bob', 'eve'])
        plt.xlabel('Epoch')
        plt.ylabel('Lowest Decryption error achieved')
        plt.show() 
Example #30
Source File: plot_results.py    From py-lapsolver with MIT License 5 votes vote down vote up
def draw_plots(df):
    sns.set_style("whitegrid")
    for s, g in df.groupby('scalar'):
        print(g)
        plt.figure(figsize=(8, 5.5))
        title='Benchmark results for dtype={}'.format(s)
        ax = sns.barplot(x='mean-time', y='matrix-size', hue='solver', data=g, errwidth=0, palette="muted")
        ax.set_xscale("log")
        ax.set_xlabel('mean-time (sec)')
        plt.legend(loc='upper right')
        plt.title(title)
        plt.tight_layout()
        plt.savefig('benchmark-dtype-{}.png'.format(s), transparent=True, )
        plt.show()