Python matplotlib.pyplot.xscale() Examples

The following are code examples for showing how to use matplotlib.pyplot.xscale(). 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: dota2-predictor   Author: andreiapostoae   File: learning_curve.py    MIT License 6 votes vote down vote up
def _plot_matplotlib(subset_sizes, data_list, mmr):
    """ Plots learning curve using matplotlib backend.
    Args:
        subset_sizes: list of dataset sizes on which the evaluation was done
        data_list: list of ROC AUC scores corresponding to subset_sizes
        mmr: what MMR the data is taken from
    """
    plt.plot(subset_sizes, data_list[0], lw=2)
    plt.plot(subset_sizes, data_list[1], lw=2)

    plt.legend(['Cross validation error', 'Test error'])
    plt.xscale('log')
    plt.xlabel('Dataset size')
    plt.ylabel('Error')

    if mmr:
        plt.title('Learning curve plot for %d MMR' % mmr)
    else:
        plt.title('Learning curve plot')

    plt.show() 
Example 2
Project: keras_lr_finder   Author: surmenok   File: lr_finder.py    MIT License 6 votes vote down vote up
def plot_loss_change(self, sma=1, n_skip_beginning=10, n_skip_end=5, y_lim=(-0.01, 0.01)):
        """
        Plots rate of change of the loss function.
        Parameters:
            sma - number of batches for simple moving average to smooth out the curve.
            n_skip_beginning - number of batches to skip on the left.
            n_skip_end - number of batches to skip on the right.
            y_lim - limits for the y axis.
        """
        derivatives = self.get_derivatives(sma)[n_skip_beginning:-n_skip_end]
        lrs = self.lrs[n_skip_beginning:-n_skip_end]
        plt.ylabel("rate of loss change")
        plt.xlabel("learning rate (log scale)")
        plt.plot(lrs, derivatives)
        plt.xscale('log')
        plt.ylim(y_lim)
        plt.show() 
Example 3
Project: typhon   Author: atmtools   File: __init__.py    MIT License 6 votes vote down vote up
def plot_alt_temp_mole(atmosphere=None, temp=None, alt_ref=None, mole=None):
    """Plot-helping function
    """
    if atmosphere is True:
        alt, pre, temp, mole, alt_ref = swifile(atmosphere)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(mole*1.e-6,alt_ref,'b-')  # ,label='Number density(SSL=60)')
    plt.xlabel('Number density [cm$^{-3}$]',fontsize=18,weight='bold')
    plt.xscale('log')
    plt.ylabel('Altitude [km]',fontsize=18,weight='bold')
    ax2=ax.twiny()
    ax2.plot(temp,alt_ref,'k-', label='Temperature')
    ax2.set_xlabel("Temperature [K]",fontsize=18,weight='bold')
    ax2.plot([],[],'b-', label='H$_{2}$O Number density')
    plt.legend()
    fig.tight_layout(pad=0.4)
    return fig 
Example 4
Project: reinforcement-learning-an-introduction   Author: ShangtongZhang   File: infinite_variance.py    MIT License 6 votes vote down vote up
def figure_5_4():
    runs = 10
    episodes = 100000
    for run in range(runs):
        rewards = []
        for episode in range(0, episodes):
            reward, trajectory = play()
            if trajectory[-1] == ACTION_END:
                rho = 0
            else:
                rho = 1.0 / pow(0.5, len(trajectory))
            rewards.append(rho * reward)
        rewards = np.add.accumulate(rewards)
        estimations = np.asarray(rewards) / np.arange(1, episodes + 1)
        plt.plot(estimations)
    plt.xlabel('Episodes (log scale)')
    plt.ylabel('Ordinary Importance Sampling')
    plt.xscale('log')

    plt.savefig('../images/figure_5_4.png')
    plt.close() 
Example 5
Project: reinforcement-learning-an-introduction   Author: ShangtongZhang   File: blackjack.py    MIT License 6 votes vote down vote up
def figure_5_3():
    true_value = -0.27726
    episodes = 10000
    runs = 100
    error_ordinary = np.zeros(episodes)
    error_weighted = np.zeros(episodes)
    for i in tqdm(range(0, runs)):
        ordinary_sampling_, weighted_sampling_ = monte_carlo_off_policy(episodes)
        # get the squared error
        error_ordinary += np.power(ordinary_sampling_ - true_value, 2)
        error_weighted += np.power(weighted_sampling_ - true_value, 2)
    error_ordinary /= runs
    error_weighted /= runs

    plt.plot(error_ordinary, label='Ordinary Importance Sampling')
    plt.plot(error_weighted, label='Weighted Importance Sampling')
    plt.xlabel('Episodes (log scale)')
    plt.ylabel('Mean square error')
    plt.xscale('log')
    plt.legend()

    plt.savefig('../images/figure_5_3.png')
    plt.close() 
Example 6
Project: ZOGY   Author: pmvreeswijk   File: zogy.py    MIT License 6 votes vote down vote up
def plot_scatter (x, y, limits, corder, cmap='rainbow_r', marker='o', markersize=3,
                  xlabel=None, ylabel=None, legendlabel=None, title=None, filename=None,
                  simple=False, xscale='log', yscale='linear'):

    plt.axis(limits)
    plt.scatter(x, y, c=corder, cmap=cmap, alpha=1, label=legendlabel, edgecolors='black')
    plt.xscale(xscale)
    plt.yscale(yscale)
    if legendlabel is not None:
        plt.legend(numpoints=1, fontsize='medium')
    if xlabel is not None:
        plt.xlabel(xlabel)
    if ylabel is not None:
        plt.ylabel(ylabel)
    if title is not None:
        plt.title(title)
    if filename is not None:
        plt.savefig(filename)
    if get_par(set_zogy.show_plots,tel): plt.show()
    plt.close()


################################################################################ 
Example 7
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 6 votes vote down vote up
def test_markevery_log_scales():
    cases = [None,
             8,
             (30, 8),
             [16, 24, 30], [0, -1],
             slice(100, 200, 3),
             0.1, 0.3, 1.5,
             (0.0, 0.1), (0.45, 0.1)]

    cols = 3
    gs = matplotlib.gridspec.GridSpec(len(cases) // cols + 1, cols)

    delta = 0.11
    x = np.linspace(0, 10 - 2 * delta, 200) + delta
    y = np.sin(x) + 1.0 + delta

    for i, case in enumerate(cases):
        row = (i // cols)
        col = i % cols
        plt.subplot(gs[row, col])
        plt.title('markevery=%s' % str(case))
        plt.xscale('log')
        plt.yscale('log')
        plt.plot(x, y, 'o', ls='-', ms=4,  markevery=case) 
Example 8
Project: nanopores   Author: mitschabaude   File: randomwalk.py    MIT License 6 votes vote down vote up
def exponential_hist(times, a, b, **params):
    cutoff = 0.03 # cutoff frequency in ms
    if len(times) == 0:
        return
    bins = np.logspace(a, b, 100)
    hist = plt.hist(times, bins=bins, alpha=0.5, **params)
    plt.xscale("log")
    params.pop("label")
    color = params.pop("color")
    total = integrate_hist(hist, cutoff)
    if sum(times > cutoff) == 0:
        return
    tmean = times[times > cutoff].mean()
    T = np.logspace(a-3, b, 1000)
    fT = np.exp(-T/tmean)*T/tmean
    fT *= total/integrate_values(T, fT, cutoff)
    plt.plot(T, fT, label="exp. fit, mean = %.2f ms" % (tmean,),
             color="dark" + color, **params)
    plt.xlim(10**a, 10**b) 
Example 9
Project: nanopores   Author: mitschabaude   File: utilities.py    MIT License 6 votes vote down vote up
def loadplots(name, show=True):
    defaultstyle = "-x"
    DIR = os.path.join(DATADIR, "plots")
    dic = load_dict(DIR, name)
    meta = dic["meta"]
    plots = dic["plots"]
    for plot in plots:
        plt.figure()
        for line in plot["data"]:
            style = line["style"] if "style" in line else defaultstyle
            plt.plot(line["x"], line["y"], style, label=line["label"])
        plt.xlabel(plot["xlabel"])
        plt.ylabel(plot["ylabel"])
        if "xscale" in plot:
            plt.xscale(plot["xscale"])
        if "yscale" in plot:
            plt.yscale(plot["yscale"])
        plt.legend()
    if show: plt.show()
    return meta

# TODO: to make this truly magical, we could recursively modify all parents 
Example 10
Project: hdp   Author: ZewenShen   File: plot.py    MIT License 6 votes vote down vote up
def test_6d_std(self):
        vanilla = np.array([7.91e-02, 5.17e-02, 3.66e-02, 2.45e-02, 1.78e-02,\
                            1.12e-02, 8.69e-03, 6.42e-03, 4.46e-03])
        antithetic = np.array([5.45e-02, 3.88e-02, 2.76e-02, 1.95e-02, 1.35e-02,\
                               9.44e-03, 6.82e-03, 4.64e-03, 3.28e-03])
        control = np.array([4.41e-02, 3.1e-02, 2.17e-02, 1.52e-02, 1.07e-02,\
                            7.64e-03, 5.28e-03, 3.17e-03, 2.59e-03])
        N = np.array([2**i for i in range(10, 19)])
        plt.plot(N, vanilla, '--o', N, antithetic, '--o', N, control, '--o')
        plt.legend(['vanilla MC', 'antithetic variates', 'control variates'])
        plt.xscale('log')
        plt.yscale('log')
        plt.xlabel('N')
        plt.ylabel('SD')
        plt.title('Standard Deviation of Different Variation Reduction Techniques')
        plt.savefig("std.png", dpi=1000)
        plt.show() 
Example 11
Project: neural-network-animation   Author: miloharper   File: test_axes.py    MIT License 6 votes vote down vote up
def test_markevery_log_scales():
    cases = [None,
         8,
         (30, 8),
         [16, 24, 30], [0,-1],
         slice(100, 200, 3),
         0.1, 0.3, 1.5,
         (0.0, 0.1), (0.45, 0.1)]

    cols = 3
    gs = matplotlib.gridspec.GridSpec(len(cases) // cols + 1, cols)

    delta = 0.11
    x = np.linspace(0, 10 - 2 * delta, 200) + delta
    y = np.sin(x) + 1.0 + delta

    for i, case in enumerate(cases):
        row = (i // cols)
        col = i % cols
        plt.subplot(gs[row, col])
        plt.title('markevery=%s' % str(case))
        plt.xscale('log')
        plt.yscale('log')
        plt.plot(x, y, 'o', ls='-', ms=4,  markevery=case) 
Example 12
Project: Learning-to-Generate-Chairs-with-Convolutional-Neural-Networks   Author: bmahlbrand   File: viz_utils.py    MIT License 6 votes vote down vote up
def plot_smooth_training_loss_change(train_losses, learning_rates, sma=1, n_skip=20, y_lim=(-0.01,0.01)):
    """
    Plots rate of change of the loss function.
    Parameters:
        train_losses - losses
        learning_rates - learning rate wrt to loss
        sma - number of batches for simple moving average to smooth out the curve.
        n_skip - number of batches to skip on the left.
        y_lim - limits for the y axis.
    """
    derivatives = [0] * (sma + 1)
    for i in range(1 + sma, len(learning_rates)):
        derivative = (train_losses[i] - train_losses[i - sma]) / sma
        derivatives.append(derivative)
        
    plt.ylabel("d/loss")
    plt.xlabel("learning rate (log scale)")
    plt.plot(learning_rates[n_skip:], derivatives[n_skip:])
    plt.xscale('log')
    plt.ylim(y_lim) 
Example 13
Project: python3_ios   Author: holzschu   File: test_axes.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_markevery_log_scales():
    cases = [None,
             8,
             (30, 8),
             [16, 24, 30], [0, -1],
             slice(100, 200, 3),
             0.1, 0.3, 1.5,
             (0.0, 0.1), (0.45, 0.1)]

    cols = 3
    gs = matplotlib.gridspec.GridSpec(len(cases) // cols + 1, cols)

    delta = 0.11
    x = np.linspace(0, 10 - 2 * delta, 200) + delta
    y = np.sin(x) + 1.0 + delta

    for i, case in enumerate(cases):
        row = (i // cols)
        col = i % cols
        plt.subplot(gs[row, col])
        plt.title('markevery=%s' % str(case))
        plt.xscale('log')
        plt.yscale('log')
        plt.plot(x, y, 'o', ls='-', ms=4,  markevery=case) 
Example 14
Project: lumin   Author: GilesStrong   File: opt_callbacks.py    Apache License 2.0 6 votes vote down vote up
def plot(self, n_skip:int=0, n_max:Optional[int]=None, lim_y:Optional[Tuple[float,float]]=None) -> None:
        r'''
        Plot the loss as a function of the LR.

        Arguments:
            n_skip: Number of initial iterations to skip in plotting
            n_max: Maximum iteration number to plot
            lim_y: y-range for plotting
        '''

        # TODO: Decide on whether to keep this; could just pass to plot_lr_finders

        with sns.axes_style(self.plot_settings.style), sns.color_palette(self.plot_settings.cat_palette):
            plt.figure(figsize=(self.plot_settings.w_mid, self.plot_settings.h_mid))
            plt.plot(self.history['lr'][n_skip:n_max], self.history['loss'][n_skip:n_max], label='Training loss', color='g')
            if np.log10(self.lr_bounds[1])-np.log10(self.lr_bounds[0]) >= 3: plt.xscale('log')
            plt.ylim(lim_y)
            plt.grid(True, which="both")
            plt.legend(loc=self.plot_settings.leg_loc, fontsize=self.plot_settings.leg_sz)
            plt.xticks(fontsize=self.plot_settings.tk_sz, color=self.plot_settings.tk_col)
            plt.yticks(fontsize=self.plot_settings.tk_sz, color=self.plot_settings.tk_col)
            plt.ylabel("Loss", fontsize=self.plot_settings.lbl_sz, color=self.plot_settings.lbl_col)
            plt.xlabel("Learning rate", fontsize=self.plot_settings.lbl_sz, color=self.plot_settings.lbl_col)
            plt.show() 
Example 15
Project: frbpoppy   Author: davidgardenier   File: logn_logs_abc.py    MIT License 6 votes vote down vote up
def plot_logn_logs(data):
    """Plot log N log S data in a cumlative histogram."""
    plot_aa_style()

    fig, (ax1) = plt.subplots(1, 1)

    for key in data:
        x, y = data[key]
        ax1.step(x, y, where='post', label=key)

    plt.xlabel(r'S$_{\text{min}}$ (Jy)')
    plt.ylabel(r'N(${>}\text{S}_{\text{min}}$)')
    plt.xscale('log')
    plt.yscale('log')
    plt.xlim((1e-3, 1e1))
    plt.legend()
    plt.tight_layout()
    plt.savefig(rel_path('plots/logn_logs_abc.pdf')) 
Example 16
Project: pypact   Author: fispact   File: compareplots.py    Apache License 2.0 6 votes vote down vote up
def plot(self):
        """
            Handles the plotting
        """
        f = plt.figure()
        
        # plot the data using matplotlib
        plt.xscale('log')
        plt.yscale('log')
        plt.title(self.title, fontsize=22)
        plt.xlabel('Time after irradiation (years)', fontsize=18)
        plt.ylabel('Heat output (kW/kg)', fontsize=18)
        plt.plot(self.time, self.heat,
                 linestyle='--', marker='o', color='k')

        # add the data points from isotope values
        for k, v in self.isotope_values.items():
            plt.plot(v[0], v[1], label=k, marker='+', color='g', markersize=8)
            plt.annotate(k, xy=v)

        # add a grid
        plt.grid(True, which="both")

        return f 
Example 17
Project: ml-fairness-gym   Author: google   File: lending_plots.py    Apache License 2.0 6 votes vote down vote up
def plot_cumulative_recall_differences(cumulative_recalls, path):
  """Plot differences in cumulative recall between groups up to time T."""
  plt.figure(figsize=(8, 3))
  style = {'dynamic': '-', 'static': '--'}

  for setting, recalls in cumulative_recalls.items():
    abs_array = np.mean(np.abs(recalls[0::2, :] - recalls[1::2, :]), axis=0)

    plt.plot(abs_array, style[setting], label=setting)

  plt.title(
      'Recall gap for EO agent in dynamic vs static environments', fontsize=16)
  plt.yscale('log')
  plt.xscale('log')
  plt.ylabel('TPR gap', fontsize=16)
  plt.xlabel('# steps', fontsize=16)
  plt.grid(True)
  plt.legend()
  plt.tight_layout()
  _write(path) 
Example 18
Project: linear_neuron   Author: uglyboxer   File: test_axes.py    MIT License 6 votes vote down vote up
def test_markevery_log_scales():
    cases = [None,
         8,
         (30, 8),
         [16, 24, 30], [0,-1],
         slice(100, 200, 3),
         0.1, 0.3, 1.5,
         (0.0, 0.1), (0.45, 0.1)]

    cols = 3
    gs = matplotlib.gridspec.GridSpec(len(cases) // cols + 1, cols)

    delta = 0.11
    x = np.linspace(0, 10 - 2 * delta, 200) + delta
    y = np.sin(x) + 1.0 + delta

    for i, case in enumerate(cases):
        row = (i // cols)
        col = i % cols
        plt.subplot(gs[row, col])
        plt.title('markevery=%s' % str(case))
        plt.xscale('log')
        plt.yscale('log')
        plt.plot(x, y, 'o', ls='-', ms=4,  markevery=case) 
Example 19
Project: modelling-course   Author: robjstan   File: f05.py    MIT License 6 votes vote down vote up
def diffusion(log_D:(-20,0,1)=-5):
    D = 10**log_D # units of D are cm^2/sec
    dist = [10**log_d for log_d in range(-6,3)]
    t = [d**2/D for d in dist]

    plt.figure(figsize=[9,6])
    plt.plot(dist,t)
    plt.xscale('log')
    plt.yscale('log')
    plt.ylim(0.001,60*60)
    # units are cm
    plt.xticks([1e-4,1e-3,1e-1,1e0,1e2], \
               ['1 um','10 um','1mm','1cm','1m'])
    plt.yticks([0.001,1,60,60*60,60*60*24,60*60*24*365,60*60*24*365*100], \
               ['0.001 sec','1 sec','1 min','1 hour','1 day','1 year','100 years'])
    plt.show() 
Example 20
Project: lattice_rnn   Author: qiujiali   File: evaluation.py    MIT License 6 votes vote down vote up
def plot_det(fnr, fpr, name, dst_dir):
    """Plotting DET curve.

    Arguments:
        fnr {list} -- a list of numpy 1D array for true positive rate
        fpr {list} -- a list of numpy 1D array for false positive rate
        name {str} -- text for the legend
        dst_dir {str} -- output figure directory, file name `det.pdf`
    """
    plt.clf()
    plt.figure(figsize=(3, 3))
    plt.rcParams["font.family"] = "Times New Roman"
    for (x_val, y_val, string) in zip(fpr, fnr, name):
        plt.plot(x_val, y_val, label=string)
    plt.legend(loc='upper right')
    plt.xlim([0.01, 1])
    plt.ylim([0.01, 1])
    plt.xscale('log')
    plt.yscale('log')
    plt.ylabel('False Negative Rate')
    plt.xlabel('False Positive Rate')
    axes = plt.gca()
    axes.xaxis.set_major_formatter(mpl.ticker.FormatStrFormatter('%.2f'))
    axes.yaxis.set_major_formatter(mpl.ticker.FormatStrFormatter('%.2f'))
    plt.savefig(os.path.join(dst_dir, 'det.pdf'), bbox_inches='tight') 
Example 21
Project: TXPipe   Author: LSSTDESC   File: twopoint.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def write_output_plot(self, results):
        import matplotlib.pyplot as plt
        d = results[0]

        fig = self.open_output('gammat_bright_stars_plot', wrapper=True)

        # compute the mean and the chi^2/dof
        flat1 = 0
        z = (d.value - flat1) / d.error
        chi2 = np.sum(z ** 2)
        chi2dof = chi2 / (len(d.theta) - 1)
        print('error,',d.error)

        plt.errorbar(d.theta,  d.theta*d.value, d.theta*d.error, fmt='ro', capsize=3,label='$\chi^2/dof = $'+str(chi2dof))
        plt.legend(loc='best')
        plt.xscale('log')

        plt.xlabel(r"$\theta$ / arcmin")
        plt.ylabel(r"$\theta \cdot \gamma_t(\theta)$")
        plt.title("Bright Star Centers Tangential Shear")

        print('type',type(fig))
        fig.close() 
Example 22
Project: TXPipe   Author: LSSTDESC   File: twopoint.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def write_output_plot(self, results):
        import matplotlib.pyplot as plt
        d = results[0]

        fig = self.open_output('gammat_dim_stars_plot', wrapper=True)

        # compute the mean and the chi^2/dof
        flat1 = 0
        z = (d.value - flat1) / d.error
        chi2 = np.sum(z ** 2)
        chi2dof = chi2 / (len(d.theta) - 1)
        print('error,',d.error)

        plt.errorbar(d.theta,  d.theta*d.value, d.theta*d.error, fmt='ro', capsize=3,label='$\chi^2/dof = $'+str(chi2dof))
        plt.legend(loc='best')
        plt.xscale('log')

        plt.xlabel(r"$\theta$ / arcmin")
        plt.ylabel(r"$\theta \cdot \gamma_t(\theta)$")
        plt.title("Dim Star Centers Tangential Shear")

        print('type',type(fig))
        fig.close() 
Example 23
Project: Sessile.drop.analysis   Author: mvgorcum   File: GUI_sessile_drop_analysis.py    GNU General Public License v3.0 5 votes vote down vote up
def plotstuff(typexplot,typeyplot,logxbool,logybool,pxscale,fps):
    x=np.float()
    y=np.float()
    if typexplot==1:
        x=thetal
    elif typexplot==2:
        x=thetar
    elif typexplot==3:
        x=dropvolume*pxscale**3
    elif typexplot==3:
        x=leftspeed*pxscale*fps
    elif typexplot==4:
        x=rightspeed*pxscale*fps
    else:
        print('no x variable set')
    if typeyplot==1:
        y=thetal
    elif typeyplot==2:
        y=thetar
    elif typeyplot==3:
        y=dropvolume
    elif typeyplot==3:
        y=leftspeed
    elif typeyplot==4:
        y=rightspeed
    else:
        print('no y variable set')
    if x.size==1 or y.size==1:
        plt.scatter(x,y)
    else:
        plt.plot(x,y)
    
    if logxbool:
        plt.xscale('log')
    if logybool:
        plt.yscale('log')
    plt.show() 
Example 24
Project: SNN   Author: arnogranier   File: compare_times.py    MIT License 5 votes vote down vote up
def stuff_on_all_graph():
        """Things that will alway be used for those plots"""
        plt.gca().grid()
        plt.xscale('log')
        plt.xlabel('Number of synapses')

    # Get computation times 
Example 25
Project: show-me-the-code   Author: hacpai   File: main.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_ranks( rank_freq, scale = 'log' ):
    """Plots frequency vs. rank."""
    rs, fs = zip( *rank_freq )

    pyplot.clf()
    pyplot.xscale( scale )
    pyplot.yscale( scale )
    pyplot.title( 'Zipf plot' )
    pyplot.xlabel( 'rank' )
    pyplot.ylabel( 'frequency' )
    pyplot.plot( rs, fs, 'r-' )
    pyplot.show() 
Example 26
Project: keras_lr_finder   Author: surmenok   File: lr_finder.py    MIT License 5 votes vote down vote up
def plot_loss(self, n_skip_beginning=10, n_skip_end=5, x_scale='log'):
        """
        Plots the loss.
        Parameters:
            n_skip_beginning - number of batches to skip on the left.
            n_skip_end - number of batches to skip on the right.
        """
        plt.ylabel("loss")
        plt.xlabel("learning rate (log scale)")
        plt.plot(self.lrs[n_skip_beginning:-n_skip_end], self.losses[n_skip_beginning:-n_skip_end])
        plt.xscale(x_scale)
        plt.show() 
Example 27
Project: spn-pytorch-experiments   Author: steven-lang   File: compare_speed_isotropic_vs_mvgauss.py    MIT License 5 votes vote down vote up
def compare_cov_size():
    # Compare different number of input features with fixed cov size 4
    t_ins = []
    t_mns = []
    # 2**12 x 2**12 cov matrix does not fit into the memory => 11 is the limit
    xs = [2 ** i for i in range(2, 12)]
    n_features = 2 ** 14
    for cardinality in xs:
        print("cardinality =", cardinality)
        # Run a few times before measuring
        run(IndependentNormal, multiplicity, n_features, cardinality, iterations=5)
        t_ins.append(
            run(IndependentNormal, multiplicity, n_features, cardinality, iterations)
        )

        # Run a few times before measuring
        run(MultivariateNormal, multiplicity, n_features, cardinality, iterations=5)
        t_mns.append(
            run(MultivariateNormal, multiplicity, n_features, cardinality, iterations)
        )

    plt.figure()
    plt.plot(xs, t_ins, label="IndependentNormal")
    plt.plot(xs, t_mns, label="MultivariateNormal")
    plt.xscale("log", basex=2)
    plt.xlabel("Number of Variables per Gaussian")
    plt.ylabel("Time in Seconds")
    plt.title(
        f"Independent Normal vs MV-Gauss: Gauss-Size vs Time\n($features = {n_features}$, $bs={batch_size}$, $iters={iterations}$)"
    )
    plt.legend()
    plt.savefig("./comp-independent-normal-vs-mv-gauss/gauss-size.png", dpi=180) 
Example 28
Project: spn-pytorch-experiments   Author: steven-lang   File: compare_speed_isotropic_vs_mvgauss.py    MIT License 5 votes vote down vote up
def compare_in_features():
    # Compare different number of input features with fixed cov size 4
    t_ins = []
    t_mns = []
    feats = [2 ** i for i in range(4, 15)]
    cardinality = 16
    for in_features in feats:
        print("in_features =", in_features)

        run(MultivariateNormal, multiplicity, in_features, cardinality, iterations=5)
        t_mns.append(
            run(MultivariateNormal, multiplicity, in_features, cardinality, iterations)
        )

        run(IndependentNormal, multiplicity, in_features, cardinality, iterations=5)
        t_ins.append(
            run(IndependentNormal, multiplicity, in_features, cardinality, iterations)
        )

    plt.figure()
    plt.plot(feats, t_ins, label="IndependentNormal")
    plt.plot(feats, t_mns, label="MultivariateNormal")
    plt.xscale("log", basex=2)
    plt.xlabel("Number of Features")
    plt.ylabel("Time in Seconds")
    plt.title(
        f"Independent Normal vs MV-Gauss: Features vs Time\n($covsize = {cardinality}$, $bs={batch_size}$, $iters={iterations}$)"
    )
    plt.legend()
    plt.savefig("./comp-independent-normal-vs-mv-gauss/nfeats.png", dpi=180) 
Example 29
Project: photograv   Author: hippke   File: photograv.py    MIT License 5 votes vote down vote up
def make_figure_distance_pitch_angle(data, scale, stellar_radius):

    encounter_time, step_of_closest_encounter = get_closest_encounter(data)

    # select data from start to closest encounter
    stellar_radii = sun_radius / stellar_radius
    px_stellar_units = data['px'][:step_of_closest_encounter] * stellar_radii
    py_stellar_units = data['py'][:step_of_closest_encounter] * stellar_radii
    pitch_angle = data['alpha'][:step_of_closest_encounter]
    pitch_angle = -numpy.degrees(pitch_angle)

    # distance between sail and origin in [m]
    distance = sqrt((px_stellar_units**2) + (py_stellar_units**2))

    # make figure
    fig = plt.figure(figsize=(6, 6))
    ax = plt.gca()
    fig.suptitle('b', fontsize=14, fontweight='bold', x=0.131, y=0.95)
    plt.plot(distance, pitch_angle, linewidth=0.5, color='black')
    plt.xscale('log')
    ax.set_xticks([5, 10, 100])
    ax.set_xticklabels(["50", "10", "100"])
    ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
    plt.xlim(4, 100)
    plt.ylim(-45, 0)
    plt.xlabel('Stellar Distance [Stellar Radii]', fontweight='bold')
    plt.ylabel(
        r'Sail Pitch Angle $\alpha$ During Approach [Degrees]',
        fontweight='bold')
    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')

    return plt 
Example 30
Project: RL-Cache   Author: WVadim   File: graphs_auxiliary.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_cum(data, label, log=True):
    x, y = ecdf(data)
    if log:
        plt.xscale('log')
    plt.plot(x, y, label=label, lw=2) 
Example 31
Project: Flipkart-Grid   Author: ad71   File: lr_finder.py    MIT License 5 votes vote down vote up
def loss_graph(self):
		plt.plot(self.history['lr'], self.history['loss'])
		plt.xscale('log')
		plt.xlabel('lr')
		plt.ylabel('loss')
		plt.show() 
Example 32
Project: isoclassify   Author: danxhuber   File: plot.py    MIT License 5 votes vote down vote up
def plotposterior(x,y,res,err1,err2,names,j,ix,iy):
    #fig = plt.figure(figsize=(8,12))
    plt.subplot(len(names),2,ix)
    plt.plot(x,np.cumsum(y))
    plt.plot([res,res],[0,1],'r')
    plt.plot([res+err1,res+err1],[0,1],'--r')
    plt.plot([res-err2,res-err2],[0,1],'--r')
    plt.ylim([0,1])
    plt.title(names[j])
    if fnmatch.fnmatch(names[j],'*rho*'):
        plt.xscale('log')
    if fnmatch.fnmatch(names[j],'*lum*'):
        plt.xscale('log')


    plt.subplot(len(names),2,iy)
    plt.plot(x,y)
    plt.plot([res,res],[0,1],'r')
    plt.plot([res+err1,res+err1],[0,1],'--r')
    plt.plot([res-err2,res-err2],[0,1],'--r')
    plt.ylim([0,np.max(y)+np.max(y)*0.1])
    plt.title(names[j])
    if fnmatch.fnmatch(names[j],'*rho*'):
        plt.xscale('log')
    if fnmatch.fnmatch(names[j],'*lum*'):
        plt.xscale('log')

    if fnmatch.fnmatch(names[j],'*feh*'):
        xt=np.arange(-2.,1.,0.01)
        yt=fehprior(xt)
        plt.plot(xt,yt*np.max(y)/np.max(yt),'--g') 
Example 33
Project: isoclassify   Author: danxhuber   File: plot.py    MIT License 5 votes vote down vote up
def plotposterior_sec(x,y,res,err1,err2,names,j,ix,iy):
    fig3 = plt.figure('secondary',figsize=(8,12))
    plt.figure('secondary')
    plt.subplot(len(names),2,ix)
    plt.plot(x,np.cumsum(y))
    plt.plot([res,res],[0,1],'r')
    plt.plot([res+err1,res+err1],[0,1],'--r')
    plt.plot([res-err2,res-err2],[0,1],'--r')
    plt.ylim([0,1])
    plt.title(names[j])
    if fnmatch.fnmatch(names[j],'*rho*'):
        plt.xscale('log')
    if fnmatch.fnmatch(names[j],'*lum*'):
        plt.xscale('log')


    plt.subplot(len(names),2,iy)
    plt.plot(x,y)
    plt.plot([res,res],[0,1],'r')
    plt.plot([res+err1,res+err1],[0,1],'--r')
    plt.plot([res-err2,res-err2],[0,1],'--r')
    plt.ylim([0,np.max(y)+np.max(y)*0.1])
    plt.title(names[j])
    if fnmatch.fnmatch(names[j],'*rho*'):
        plt.xscale('log')
    if fnmatch.fnmatch(names[j],'*lum*'):
        plt.xscale('log')

    if fnmatch.fnmatch(names[j],'*feh*'):
        xt=np.arange(-2.,1.,0.01)
        yt=fehprior(xt)
        plt.plot(xt,yt*np.max(y)/np.max(yt),'--g') 
Example 34
Project: ble5-nrf52-mac   Author: tomasero   File: test_axes.py    MIT License 5 votes vote down vote up
def test_minorticks_on(xscale, yscale):
    ax = plt.subplot(111)
    ax.plot([1, 2, 3, 4])
    ax.set_xscale(xscale)
    ax.set_yscale(yscale)
    ax.minorticks_on() 
Example 35
Project: nanopores   Author: mitschabaude   File: statistics.py    MIT License 5 votes vote down vote up
def compare_cdfs(self, sample, log=True):
        t = grid(sample, 20, 0.005, log=log)
        tt = grid(sample, 100, 0.005, log=log)
        plt.plot(t, empirical_cdf(t, sample), "o")
        self.plot_cdf(tt)
        if log:
            plt.xscale("log") 
Example 36
Project: nanopores   Author: mitschabaude   File: statistics.py    MIT License 5 votes vote down vote up
def compare_pdfs(self, sample, log=True):
        t = grid(sample, 20, 0.005, log=log)
        tt = grid(sample, 100, 0.005, log=log)
        t, epdf = empirical_pdf(t, sample, log=log)
        plt.plot(t, epdf, "o")
        self.plot_pdf(tt, log=log)
        if log:
            plt.xscale("log") 
Example 37
Project: nanopores   Author: mitschabaude   File: utilities.py    MIT License 5 votes vote down vote up
def saveplots(name="plot", meta=None, uid=False):
    # collect data from every open figure
    plots = []
    figs = map(plt.figure, plt.get_fignums())
    for fig in figs:
        for ax in fig.axes:
            plot = dict(
                xlabel = ax.get_xlabel(),
                ylabel = ax.get_ylabel(),
                xscale = ax.get_xscale(),
                yscale = ax.get_yscale(),
                data = [])
            for line in ax.lines:
                x, y = line.get_data()
                marker = line.get_marker()
                if marker == "None":
                    marker = ""
                data = dict(
                    x = x,
                    y = y,
                    style = marker + line.get_linestyle(),
                    label = line.get_label())
                plot["data"].append(data)
            plots.append(plot)
    # add metadata if provided
    meta = {} if meta is None else meta
    data = dict(plots=plots, meta=meta)
    # save to txt file in DATADIR
    DIR = os.path.join(DATADIR, "plots")
    name = name + "_" + str(unique_id()) if uid else name
    save_dict(data, DIR, name)
    return plots 
Example 38
Project: hdp   Author: ZewenShen   File: plot.py    MIT License 5 votes vote down vote up
def test_6d_conv(self):
        N = np.array([4**6, 8**6, 16**6, 32**6])
        err = np.array([1.3e-01, 3.5e-03, 3.4e-04, 1.7e-05])
        plt.plot(N, err, '--o')
        plt.xscale('log')
        plt.yscale('log')
        plt.xlabel('Number of grid points')
        plt.ylabel('Relative error')
        plt.legend(['FFT Conv'])
        # plt.title("FFT Conv method's accuracy versus number of grid points")
        plt.savefig("conv6d.png", dpi=1500)
        plt.show() 
Example 39
Project: hdp   Author: ZewenShen   File: plot.py    MIT License 5 votes vote down vote up
def test_6d_acc_vs_time(self):
        vanilla_t = np.array([0.67, 1.33, 2.72, 5.52, 22.17])
        vanilla_e = np.array([7.0e-03, 1.1e-02, 5.4e-03, 2.4e-03, 7.7e-04])
        anti_t = np.array([0.21, 0.37, 0.65, 1.31, 2.63, 5.31, 10.65, 21.34])
        anti_e = np.array([9.6e-03, 4.5e-03, 4.7e-03, 7.6e-03, 5.1e-03, 1.6e-04, 2.9e-03, 3.4e-04])
        ctrl_t = np.array([0.57, 1.00, 2.01, 4.01, 16.25])
        ctrl_e = np.array([7.6e-03, 9.4e-03, 6.3e-03, 4.1e-04, 4.6e-04])
        sobol_t = np.array([0.76, 1.49, 2.96, 5.97, 11.94, 24.08])
        sobol_e = np.array([2.7e-04, 5.9e-04, 8.3e-04, 2.2e-04, 5.9e-05, 4.6e-06])
        sobctrl_t = np.array([0.86, 1.52, 3.06, 6.09, 12.31, 24.73])
        sobctrl_e = np.array([1.8e-04, 8.5e-04, 9.6e-04, 2.9e-04, 1.9e-05, 2.4e-05])
        fft_t = np.array([0.19, 16.4])
        fft_e = np.array([3.5e-03, 3.4e-04])
        # plt.plot(vanilla_t, vanilla_e, '--o', anti_t, anti_e, '--o', ctrl_t, ctrl_e, '--o',\
        #          sobol_t, sobol_e, '--o', sobctrl_t, sobctrl_e, '--o', fft_t, fft_e, '--o')
        plt.plot(vanilla_t, vanilla_e, '--o', ctrl_t, ctrl_e, '--o',\
                 sobol_t, sobol_e, '--o', fft_t, fft_e, '--o')
        # plt.legend(['vanilla MC', 'antithetic variates', 'control variates', 'sobol seq', 'sobol seq + ctrl var', 'FFT Conv'])
        plt.legend(['vanilla MC', 'control variates', 'sobol seq', 'FFT Conv'])
        plt.xscale('log')
        plt.yscale('log')
        plt.xlabel('second')
        plt.ylabel('Relative error')
        # plt.title('Standard Deviation of Different Variation Reduction Techniques')
        # plt.savefig("std.png", dpi=1000)
        plt.show() 
Example 40
Project: planetplanet   Author: rodluger   File: timing.py    GNU General Public License v3.0 5 votes vote down vote up
def plot():
    '''
    
    '''
    
    # Register the functions
    builtins.__dict__.update(globals())
    
    # Loop over various dataset sizes
    Narr = np.logspace(0, 5, 5)
    tpp = np.zeros_like(Narr)
    tbm = np.zeros_like(Narr)
    tps = np.zeros_like(Narr)
    for i, N in enumerate(Narr):
        tpp[i] = timeit.timeit('run_pp(%d)' % N, number = 10) / 10.
        if batman is not None:
            tbm[i] = timeit.timeit('run_bm(%d)' % N, number = 10) / 10.
        if ps is not None:
            tps[i] = timeit.timeit('run_ps(%d)' % N, number = 10) / 10.
    
    pl.plot(Narr, tpp, '-o', label = 'planetplanet')
    if batman is not None:
        pl.plot(Narr, tbm, '-o', label = 'batman')
    if ps is not None:
        pl.plot(Narr, tps, '-o', label = 'pysyzygy')
    pl.legend()
    pl.yscale('log')
    pl.xscale('log')
    pl.ylabel('Time [seconds]', fontweight = 'bold')
    pl.xlabel('Number of datapoints', fontweight = 'bold') 
Example 41
Project: medvision   Author: kyle0x54   File: draw_curve.py    Apache License 2.0 5 votes vote down vote up
def draw_froc_curve(average_fps,
                    sensitivity,
                    save_path=None,
                    bLogPlot=True,
                    **kwargs):
    """ Plot the FROC curve.

    Args:
        average_fps (list): A list containing the average number of false
        positives per image for different thresholds.
        sensitivity (list):  A list containing overall sensitivity for
        different thresholds.
        save_path (str): path to save the froc curve drawing.
    """
    average_fps = np.append(average_fps, 64)
    sensitivity = np.append(sensitivity, sensitivity[-1])
    plt.figure()
    plt.plot(average_fps, sensitivity, **kwargs)
    plt.xlabel('Average number of false positives per scan')
    plt.ylabel('Sensitivity')
    plt.title('FROC Curve')
    plt.xlim(0.125, 64)
    plt.ylim([0, 1])
    plt.legend(loc='lower right')

    ax = plt.gca()
    xaxis = [0.125, 0.25, 0.5, 1, 2, 4, 8, 16, 32, 64]
    if bLogPlot:
        plt.xscale('log', basex=2)
        ax.xaxis.set_major_formatter(FixedFormatter(xaxis))

    # set your ticks manually
    ax.xaxis.set_ticks(xaxis)
    ax.yaxis.set_ticks(np.arange(0, 1.1, 0.1))
    plt.grid(b=True, which='both')
    plt.tight_layout()

    if save_path is not None:
        plt.savefig(save_path)
    else:
        plt.show() 
Example 42
Project: transmutagen   Author: ergs   File: analysis.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def analyze_eigenvals(*, pwru50_data=None, file=None, title=True):
    if not pwru50_data:
        pwru50_data = os.path.join(os.path.dirname(__file__), 'tests', 'data', 'pwru50_400000000000000.0.npz')

    nucs, matpwru50 = load_sparse_csr(pwru50_data)
    matdecay = decay_matrix()
    for desc, mat in {'pwru50': matpwru50, 'decay': matdecay}.items():
        plt.clf()
        print("analyzing eigenvalues of", desc)
        eigvals, eigvects = scipy.sparse.linalg.eigen.eigs(mat, mat.shape[0]-2)
        plt.scatter(np.real(eigvals), np.imag(eigvals))
        plt.yscale('symlog', linthreshy=1e-20)
        plt.xscale('symlog')
        # plt.xlim([np.min(np.real(eigvals))*2, 1])
        plt.ylim([np.min(np.imag(eigvals))*10, np.max(np.imag(eigvals))*10])
        plt.xticks([-10**i for i in range(1, 1+int(np.ceil(np.log10(-plt.xlim()[0]))), 2)]
            + [0]
            + [10**i for i in range(1, int(np.log10(plt.xlim()[1])), 2)])
        plt.yticks([-10**i for i in range(-19, int(np.log10(-plt.ylim()[0])), 2)]
            + [0]
            + [10**i for i in range(-19, int(np.log10(plt.ylim()[1])), 2)])
        plt.minorticks_off()
        if title:
            plt.title("Eigenvalues of transmutation matrix for " + desc)
        plt_show_in_terminal()
        if file:
            path, ext = os.path.splitext(file)
            plt.savefig(path + '_' + desc + ext) 
Example 43
Project: adVNTR   Author: mehrdadbakhtiari   File: plot.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_sensitivity_over_fallout():
    stat_file = 'FP_and_sensitivity_evalue_min_len50.0.txt'
    # stat_file2 = 'fallout_and_sensitivity_min_len50.0_seq_68.txt'
    X, Y = get_x_and_y_from_file(stat_file)

    import matplotlib.pyplot as plt
    cmap = plt.get_cmap('seismic')

    pattern_results, min_len, max_len = get_pattern_result_map(stat_file)
    for p_num in pattern_results.keys():
        if int(p_num) % 5 != 4:
            continue
        # if p_num != '19':
        #     continue
        X = []
        Y = []
        points = []
        color = None
        for FP, sens, evalue, length, TP in pattern_results[p_num]:
            points.append((FP, sens))
            color = cmap((float(length) - min_len) / (max_len - min_len))
        points.sort()
        if points[len(points)-1][1] < 0.8:
            continue
        if points[0][1] > 0.3:
            continue
        for x, y in points:
            # if x > 1000:
            #     continue
            X.append(x)
            Y.append(y)
        plt.plot(X, Y, label='Pid:%s |Pattern|: %s' % (p_num, length))
    # plt.xscale('log')
    plt.xlabel('False Positives')
    plt.ylabel('Sensitivity')
#    plt.legend(loc=4, prop={'size':9})
    # plt.colorbar()
    plt.savefig('%s.png' % stat_file)  # save the figure to file
    plt.close() 
Example 44
Project: NICERsoft   Author: paulray   File: plotutils.py    MIT License 5 votes vote down vote up
def plot_energy_spec(etable,binscale=1.0,plot_pos=None):
    'plots the energy spectrum of PI'
    bb = np.concatenate((np.arange(0.0,2.0,0.02*binscale),np.arange(2.0,15.0,0.1*binscale)))
    hh, hh_bins = np.histogram(etable['PI']*PI_TO_KEV, bins=bb)
    widths = bb[1:] - bb[:-1]
    plot.step(bb[:-1],hh/widths,where='post')
#    plot.hist(etable['PI']*PI_TO_KEV, bins=bb,
#        histtype='step',log=False,density=False)
    plot.yscale('log')
    plot.xscale('log')
    plot.xlim((0.1,20.0))

    # Default option
    if plot_pos is None:
        plot.title('PI Spectrum')
        plot.xlabel('Energy (keV)')
        plot.ylabel('Counts/keV')

    ## Options for plot_all_spec
    if plot_pos is "corner":
        plot.xlabel('Energy (keV)')
        plot.ylabel('Counts/keV')
        plot.tick_params(axis='x',which='both',bottom='on',labelbottom='on')
    if plot_pos is "left":
        plot.ylabel('Counts/keV')
        plot.tick_params(axis='x',which='both',labelbottom='off')
    if plot_pos is "bottom":
        plot.xlabel('Energy (keV)')
    if plot_pos is "center":
        plot.tick_params(axis='x',which='both',labelbottom='off')



    return
#-------------------------------THIS PLOTS THE POWER SPECTRUM (FFT)-------------- 
Example 45
Project: rebbr   Author: jervisfm   File: bbr_plot.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def make_experiment4_figure(logfile):
    """Generate high quality plot of data to reproduce figure 8.

    The logfile is a CSV of the format [congestion_control, loss_rate, goodput, rtt, capacity, specified_bw]
    """
    results = {}
    cubic = {"loss": [], "goodput": []}
    bbr = {"loss": [], "goodput": []}

    # For available options on plot() method, see: https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot
    # We prefer to use explicit keyword syntax to help code readability.

    # Create a figure.
    fig_width = 8
    fig_height = 5
    fig, axes = plt.subplots(figsize=(fig_width, fig_height))

    results = parse_results_csv(logfile)
    xmark_ticks = get_loss_percent_xmark_ticks(results)
    cubic = results['cubic']
    bbr = results['bbr']
    debug_print_verbose("CUBIC: %s" % cubic)
    debug_print_verbose("BBR: %s" % bbr)

    matplotlib.rcParams.update({'figure.autolayout': True})

    plt.plot(cubic['loss'], cubic['goodput'], color='blue', linestyle='solid', marker='o',
             markersize=7, label='CUBIC')

    plt.plot(bbr['loss'], bbr['goodput'], color='red', linestyle='solid', marker='x',
             markersize=7, label='BBR')

    plt.xscale('log')

    apply_axes_formatting(axes, deduplicate_xmark_ticks(xmark_ticks))

    plot_titles(plt, xaxis="Loss Rate (%) - Log Scale", yaxis="Goodput (Mbps)")

    plot_legend(plt, axes)

    save_figure(plt, name="figures/experiment4.png") 
Example 46
Project: NuGridPy   Author: NuGrid   File: nugrid_set.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_plot_CC_T_rho_max(self,linestyle=[],burn_limit=0.997,color=['r'],marker=['o'],markevery=500): 
		'''
			Plots 
			end_model - array, control how far in models a run is plottet, if -1 till end
			symbs_1  - set symbols of runs
		'''
		if len(linestyle)==0:
			linestyle=200*['-']
		plt.figure('CC evol')
                for i in range(len(self.runs_H5_surf)):
                        sefiles=se(self.runs_H5_out[i])
			t1_model=-1
			sefiles.get('temperature')
			sefiles.get('density')
                        mini=sefiles.get('mini')
			zini=sefiles.get('zini')
                        model=sefiles.se.cycles
                        model_list=[]
                        for k in range(0,len(model),1):
                                model_list.append(model[k])
                        rho1=sefiles.get(model_list,'rho')   #[:(t1_model-t0_model)]
                        T1=sefiles.get(model_list,'temperature')#[:(t1_model-t0_model)]
                        rho=[]
                        T=[]
			T_unit=sefiles.get('temperature_unit')
			labeldone=False
                        for k in range(len(model_list)):
				t9=np.array(T1[k])*T_unit/1e9
				T.append(max(t9))
				rho.append(max(rho1[k]))
			label=str(mini)+'$M_{\odot}$, Z='+str(zini)
			plt.plot(T,rho,label=label,color=color[i],marker=marker[i],markevery=markevery)					
		plt.xlabel('$T_{9,max} (GK)$')
		plt.ylabel(r'$\rho [cm^{-3}]$')
		plt.yscale('log')
		plt.xscale('log')
		plt.legend(loc=2) 
Example 47
Project: dave   Author: barentsen   File: plotting.py    MIT License 5 votes vote down vote up
def blsPlot(clip):
    """Plot the bls spectrum and info about the BLS search"""


    periods=clip.bls.bls_search_periods;
    bls=1e6*clip.bls.convolved_bls;
    highper=clip.bls.period;
    highdur=clip.bls.duration_hrs


    plt.subplot(211)
    plt.plot(periods,bls,'k')
    plt.plot(highper,max(bls),'rv',ms=9,alpha=.6)
    plt.xscale('log')
    plt.xlim(min(periods),1.05)
    plt.title(('%u' %(clip.value)))
    plt.ylabel('bls (ppm)')

    plt.subplot(212)
    plt.plot(periods,bls,'k')
    plt.plot(highper,max(bls),'rv',ms=9,alpha=.6)
    plt.xscale('log')
    plt.xlim(.95,max(periods))
    plt.xlabel('log10 (Period-days)')
    plt.ylabel('bls (ppm)')


    plt.figtext(.11,.97,'BLS Spectrum',color='k',fontsize=12)
    plt.figtext(.11,.94,clip['disposition.fluxVet.disp'],color='r',fontsize=12)
    plt.figtext(.65,.92,('blsP=%.2f vs. trP=%.2f days' % (clip.bls.period,clip.trapFit.period_days)),fontsize=13)
    #Mark the largest point. 
Example 48
Project: dave   Author: barentsen   File: sueplotting.py    MIT License 5 votes vote down vote up
def blsPlot(clip):
    """Plot the bls spectrum and info about the BLS search"""
    
    
    periods=clip.bls.bls_search_periods;
    bls=1e6*clip.bls.convolved_bls;
    highper=clip.bls.period;
    highdur=clip.bls.duration_hrs    
    
    
    plt.subplot(211)
    plt.plot(periods,bls,'k')
    plt.plot(highper,max(bls),'rv',ms=9,alpha=.6)
    plt.xscale('log')
    plt.xlim(min(periods),1.05)
    plt.title(('%u' %(clip.value)))
    plt.ylabel('bls (ppm)')    
    
    plt.subplot(212)
    plt.plot(periods,bls,'k')
    plt.plot(highper,max(bls),'rv',ms=9,alpha=.6)
    plt.xscale('log')
    plt.xlim(.95,max(periods))
    plt.xlabel('log10 (Period-days)')
    plt.ylabel('bls (ppm)')
    

    plt.figtext(.11,.97,'BLS Spectrum',color='k',fontsize=12)
    plt.figtext(.11,.94,clip['disposition.fluxVet.disp'],color='r',fontsize=12)
    plt.figtext(.65,.92,('blsP=%.2f vs. trP=%.2f days' % (clip.bls.period,clip.trapFit.period_days)),fontsize=13)
    #Mark the largest point.
    
    
    
    
#def setlimits(frac): 
Example 49
Project: allennlp   Author: allenai   File: find_learning_rate.py    Apache License 2.0 5 votes vote down vote up
def _save_plot(learning_rates: List[float], losses: List[float], save_path: str):
    import matplotlib

    matplotlib.use("Agg")  # noqa
    import matplotlib.pyplot as plt

    plt.ylabel("loss")
    plt.xlabel("learning rate (log10 scale)")
    plt.xscale("log")
    plt.plot(learning_rates, losses)
    logger.info(f"Saving learning_rate vs loss plot to {save_path}.")
    plt.savefig(save_path) 
Example 50
Project: reinforcement-learning-an-introduction-solutions   Author: matteocasolari   File: Exercise2.5-2.11.py    MIT License 5 votes vote down vote up
def show_results2_11(bandit_types, ARs, params):
    """
    Show the result, for exercise 2.5
    :param bandit_types: names of the algorithms used to solve the k-armed bandit problem
    :param ARs: average reward value, for each algorithm and for each fundamental parameter configuration
    :param params: parameters
    :return:
    """
    for bandit_type, ARs_ in zip(bandit_types, ARs):
        plt.figure(2)
        if bandit_type == 'sample_average' or bandit_type == 'constant_step_size':
            plt.plot(params.epsilons, ARs_, label=bandit_type)

        if bandit_type == 'gradient':
            plt.plot(params.alphas, ARs_, label=bandit_type)

        if bandit_type == 'ucb':
            plt.plot(params.cs, ARs_, label=bandit_type)

        if bandit_type == 'optimistic_init':
            plt.plot(params.initializations, ARs_, label=bandit_type)

    plt.legend(loc='best')
    plt.xlabel('Epsilon, alpha, c, Q0')
    plt.ylabel('Average reward')
    plt.xscale('log', basex=2)