Python matplotlib.pyplot 模块,yscale() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.yscale()

项目:AnomalyDetection    作者:JayZhuCoding    | 项目源码 | 文件源码
def plot_training_parameters(self):
        fr = open("training_param.csv", "r")
        fr.readline()
        lines = fr.readlines()
        fr.close()
        n = 100
        nu = np.empty(n, dtype=np.float64)
        gamma = np.empty(n, dtype=np.float64)
        diff = np.empty([n, n], dtype=np.float64)
        for row in range(len(lines)):
            m = lines[row].strip().split(",")
            i = row / n
            j = row % n
            nu[i] = Decimal(m[0])
            gamma[j] = Decimal(m[1])
            diff[i][j] = Decimal(m[2])
        plt.pcolor(gamma, nu, diff, cmap="coolwarm")
        plt.title("The Difference of Guassian Classifier with Different nu, gamma")
        plt.xlabel("gamma")
        plt.ylabel("nu")
        plt.xscale("log")
        plt.yscale("log")
        plt.colorbar()
        plt.show()
项目:planetplanet    作者:rodluger    | 项目源码 | 文件源码
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')
项目:scipyplot    作者:robertocalandra    | 项目源码 | 文件源码
def training_process_3d(data, fontsizefig=18):
    """

    :param data: List of arrays, each containing a "loss trajectory" as a numpy array [3 x T]
    (Note: The loss trajectories can have different lenght)
    :return:
    """
    n_traj = len(data)
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    for i in range(n_traj):
        assert data[i].shape[0] == 3
        #ax.plot(data[i][0, :], data[i][1, :], data[i][2, :], c='r', marker='-o')
        ax.plot(data[i][0, :], data[i][1, :], data[i][2, :])

    ax.set_xlabel('Training set', fontsize=fontsizefig)
    ax.set_ylabel('Test set', fontsize=fontsizefig)
    ax.set_zlabel('Validation set', fontsize=fontsizefig)
    #plt.xscale('log')
    #plt.yscale('log')
    #plt.zscale('log')
    plt.show()

    return 0
项目:nanopores    作者:mitschabaude    | 项目源码 | 文件源码
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
项目:ase16    作者:txt    | 项目源码 | 文件源码
def coced3(max=1000, rounds=20):
  random.seed(1)
  c = Cocomo()

  import matplotlib.pyplot as plt

  # plt.yscale('log')
  plt.ylabel('effort')
  plt.xlabel('all efforts, sorted')
  styles = ["r-", "m-", "c-", "y-", "k-", "b-", "g-"]
  plots = []
  legends = []
  coced3a(
      0,
      len(styles) - 1,
      c,
      max,
      plt,
      styles,
      plots=plots,
      legends=legends)
  plt.legend(plots, legends, loc=2)
  plt.xlim(0, 1050)
  plt.show()
项目:ase16    作者:txt    | 项目源码 | 文件源码
def coced4(samples=1000, rounds=15):
  # random.seed(1)
  c = Cocomo()
  import matplotlib.pyplot as plt
  # plt.yscale('log')
  xs = []
  medians = []
  spreads = []
  mosts = []
  coced4a(0, rounds, c, samples, {}, xs, medians, spreads, mosts)
  plt.ylabel('effort')
  plt.xlabel('round')
  plt.legend([plt.plot(xs, medians), plt.plot(xs, spreads)],
             ["median", "spread"],
             loc=1)
  plt.xlim(-0.5, len(medians) + 0.5)
  plt.ylim(0, 1.05 * max(medians + spreads + mosts))
  plt.show()
项目:mlprojects-py    作者:srinathperera    | 项目源码 | 文件源码
def show_errors_by_feature(error_data):
    plt.figure(1, figsize=(20,10))
    plt.subplot(321)
    plt.xlabel('Producto_ID', fontsize=18)
    plt.ylabel('Error', fontsize=18)
    #plt.yscale('log')
    #plt.xscale('log')
    plt.scatter(error_data['Producto_ID'].values, error_data['mean'].values, alpha=0.5)

    plt.subplot(322)
    plt.xlabel('Cluster', fontsize=18)
    plt.ylabel('Error Sum', fontsize=18)
    plt.scatter(error_data['Cluster'].values, error_data['mean'].values, alpha=0.5)

    plt.subplot(323)
    plt.xlabel('Percent', fontsize=18)
    plt.ylabel('Error Sum', fontsize=18)
    plt.scatter(error_data['percent'].values, error_data['mean'].values, alpha=0.5)

    plt.tight_layout()
    plt.show()
项目:TurbPlasma    作者:tulasinandan    | 项目源码 | 文件源码
def scpdf(d,a=None,b=None,mag=1.,sav='n'):
   import matplotlib.pyplot as plt
   ms = str(mag)+'$\sigma$'
   rmsa = np.sqrt(np.mean(d[a]**2))
   rmsb = np.sqrt(np.mean(d[b]**2)); mag=mag*rmsb; 
   bn,pn=calc_pdf(d[a][np.where( d[b] < -mag)])
   bs,ps=calc_pdf(d[a][np.where((d[b] < mag) & (d[b] > -mag))])
   bp,pp=calc_pdf(d[a][np.where( d[b] > mag)])
   plt.clf()
   plt.plot(bn*rmsa,pn,label=b+' < -'+ms)
   plt.plot(bs*rmsa,ps,label='|'+b+'| < '+ms)
   plt.plot(bp*rmsa,pp,label=b+' >  '+ms)
   plt.xlabel(a)
   plt.yscale('log')
   plt.legend(loc='best')
   if sav == 'y':
      plt.savefig(a+'-conditioned-on-'+b+'-signed.png',dpi=100)
   return {'bn':bn,'pn':pn,'bs':bs,'ps':ps,'bp':bp,'pp':pp, 'rmsbn':rmsa}

##
## Conditional PDFs on unsigned variable
##
项目:TurbPlasma    作者:tulasinandan    | 项目源码 | 文件源码
def ucpdf(d,a=None,b=None,mag=1.,sav='n'):
   import matplotlib.pyplot as plt
   ms  = str(mag)+'$\sigma$'
   ms2 = str(2*mag)+'$\sigma$'
   rmsa = np.sqrt(np.mean(d[a]**2))
   rmsb = np.sqrt(np.mean(d[b]**2)); mag=mag*rmsb; 
   bn,pn=calc_pdf(d[a][np.where( abs(d[b]) < mag)])
   bs,ps=calc_pdf(d[a][np.where((abs(d[b]) > mag) & (abs(d[b]) < 2*mag))])
   bp,pp=calc_pdf(d[a][np.where( abs(d[b]) > 2*mag)])
   plt.clf()
   plt.plot(bn*rmsa,pn,label='|'+b+'| < '+ms)
   plt.plot(bs*rmsa,ps,label=ms+'< |'+b+'| < '+ms2)
   plt.plot(bp*rmsa,pp,label='|'+b+'| > '+ms2)
   plt.xlabel(a)
   plt.yscale('log')
   plt.legend(loc='best')
   if sav == 'y':
      plt.savefig(a+'-conditioned-on-'+b+'-usigned.png',dpi=100)
   return {'bn':bn,'pn':pn,'bs':bs,'ps':ps,'bp':bp,'pp':pp, 'rmsbn':rmsa}
项目:Polymers    作者:FracturedRocketSpace    | 项目源码 | 文件源码
def plotEndtoendSq(weightedEndtoendSq,weightedEndtoendSqStd,fittedWeightedEndtoendSq,popSize):

    x = np.linspace(1,c.nBeads, c.nBeads);

    # Plot the end-to-end distance squared
    plt.figure(5)
    plt.xlabel('Number of beads')
    plt.xlim(0,c.nBeads)
    plt.ylabel('End-to-end distance squared')
    plt.errorbar(x,weightedEndtoendSq,yerr=weightedEndtoendSqStd, label='Data')
    plt.plot(x,fittedWeightedEndtoendSq,color = "r", label='Fit')
    plt.plot(popSize, color = "g", label='Population')
    plt.xscale('log')
    plt.yscale('log')
    plt.xlim([3,c.nBeads])
    plt.legend(loc='best')
项目:Polymers    作者:FracturedRocketSpace    | 项目源码 | 文件源码
def plotGyradiusSq(weightedGyradiusSq,weightedGyradiusSqStd,fittedGyradius,popSize):

    x = np.linspace(1,c.nBeads, c.nBeads);

    # Plot the gyradius
    plt.figure(6)
    plt.xlabel('Number of beads')
    plt.xlim(0,c.nBeads)
    plt.ylabel('Ensemble average $R_g^2$')
    plt.errorbar(x,weightedGyradiusSq,yerr=weightedGyradiusSqStd, label='Data')
    plt.plot(x,fittedGyradius,color = "r", label='Fit')
    plt.plot(popSize, color = "g", label='Population')
    plt.xscale('log')
    plt.yscale('log')
    plt.xlim([3,c.nBeads])
    plt.legend(loc='best')
项目:tf-sparql    作者:derdav3    | 项目源码 | 文件源码
def plot_res(test_err, train_batch_loss, benchmark_err, epoch):
    flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"]

    test_x_val = np.array(list(x * 3 for x in range(0, len(test_err))))

    plt.plot(train_batch_loss[0],train_batch_loss[1], label="Training error", c=flatui[1], alpha=0.5)
    plt.plot(test_x_val, np.array(test_err), label="Test error", c=flatui[0])
    plt.axhline(y=benchmark_err[1], linestyle='dashed', label="No-modell error", c=flatui[2])
    plt.axhline(y=0.098, linestyle='dashed', label="State of the art error", c=flatui[3])

    plt.suptitle("Model error - cold queries")
    plt.yscale('log', nonposy='clip')
    plt.xlim([0,epoch+1])
    # second_axes = plt.twinx() # create the second axes, sharing x-axis
    # second_axes.set_yticks([0.2,0.4]) # list of your y values
    plt.xlabel('epoch')
    plt.ylabel('error')
    plt.legend(loc='upper right')
    plt.show()
项目:ZOGY    作者:pmvreeswijk    | 项目源码 | 文件源码
def plot_scatter (x, y, limits, corder, cmap='rainbow_r', symbol='o',
                  xlabel='', ylabel='', legendlabel='', title='', filename='',
                  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!='':
        plt.legend(numpoints=1, fontsize='medium')
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.title(title)
    if filename != '':
        plt.savefig(filename)
    if show_plots: plt.show()
    plt.close()

################################################################################
项目:Python_Learning    作者:mafanhe    | 项目源码 | 文件源码
def plot_ranks(hist, scale='log'):
    """Plots frequency vs. rank.

    hist: map from word to frequency
    scale: string 'linear' or 'log'
    """
    t = rank_freq(hist)
    rs, fs = zip(*t)

    plt.clf()
    plt.xscale(scale)
    plt.yscale(scale)
    plt.title('Zipf plot')
    plt.xlabel('rank')
    plt.ylabel('frequency')
    plt.plot(rs, fs, 'r-', linewidth=3)
    plt.show()
项目:hippylib    作者:hippylib    | 项目源码 | 文件源码
def plot_eigenvalues(d, mytitle = None, subplot_loc=None):
    k = d.shape[0]
    if subplot_loc is not None:
        plt.subplot(subplot_loc)
    plt.plot(range(0,k), d, 'b*', range(0,k), np.ones(k), '-r')
    plt.yscale('log')
    if mytitle is not None:
        plt.title(mytitle)
项目:NuGridPy    作者:NuGrid    | 项目源码 | 文件源码
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)
项目:scipyplot    作者:robertocalandra    | 项目源码 | 文件源码
def training_process_2d(data):
    """

    :param data: "loss trajectory" as a numpy array [3 x T]
    :return:
    """
    assert data.shape[0] == 3
    n_traj = len(data)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    h = ax.plot(data.transpose())
    plt.yscale('log')
    ax.legend(h, ['Training set', 'Test set', 'Validation set'])
    plt.show()
    return 0
项目:scipyplot    作者:robertocalandra    | 项目源码 | 文件源码
def test_rplot_data_yscale(self):
        y = [np.absolute(np.random.rand(100, 100)) + 0.00001]
        x = np.random.rand(100)
        h = spp.rplot_data(data=y)
        plt.yscale('log')
项目:nanopores    作者:mitschabaude    | 项目源码 | 文件源码
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
项目:transmutagen    作者:ergs    | 项目源码 | 文件源码
def plot_matrix_sum_histogram(m, *, title='', axis=0, file=None):
    plt.clf()
    plt.hist(np.asarray(np.sum(m, axis=axis)).flatten())
    plt.yscale('log', nonposy='clip')
    if title:
        plt.title(title)
    plt_show_in_terminal()
    if file:
        plt.savefig(file)
    plt.close()
项目:transmutagen    作者:ergs    | 项目源码 | 文件源码
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([0] +
            [-10**i for i in range(1, 1+int(np.ceil(np.log10(-plt.xlim()[0]))), 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)
项目:transmutagen    作者:ergs    | 项目源码 | 文件源码
def analyze_degrees(*, pwru50_data=None, file=None):
    if not pwru50_data:
        pwru50_data = os.path.join(os.path.dirname(__file__), 'tests', 'data', 'pwru50_400000000000000.0.npz')

    nucs, data = load_sparse_csr(pwru50_data)

    ns = list(range(30, 2, -2)) # [30, 28, ..., 4]
    print("Computing CRAM functions")
    fs = []
    for n in ns + [ns[-1] - 2]:
        print(n)
        fs.append(CRAM_matrix_exp_lambdify(n, 200))
    b = initial_vector("U235", nucs)

    print("Computing the exponential of the matrices")
    xs = {}
    diffs = {}
    for t in TIME_STEPS:
        xs[t] = [f(-data*t, b) for f in fs]
        diffs[t] = list(zip(xs[t][:-1], xs[t][1:]))

    plt.clf()
    for t in sorted(TIME_STEPS):
        plt.plot(ns, [np.max(np.abs(a - b)) for a, b in diffs[t]],
            label=TIME_STEPS[t])
    plt.legend()
    plt.xticks(ns)
    plt.yscale('log')
    plt.ylabel(r"$\mathrm{max}(|\hat{r}_{n,n}(-At)b - \hat{r}_{n-2,n-2}(-At)b|)$")
    plt.xlabel(r"$n$")
    if file:
        plt.savefig(file)
    plt_show_in_terminal()
项目:ImSimDeep    作者:jchiang87    | 项目源码 | 文件源码
def plot_instcat_offset_hists(pointSource, sersic, visit_name, component,
                              fontsize='x-small'):
    """
    Overlay histograms of the measured position offsets for the pointSource
    and sersic objects.

    Parameters
    ----------
    pointSource : pandas.DataFrame
        Data frame containing the true and measured coordinates and
        magnitudes and position offsets for the pointSource objects.
    sersic : pandas.DataFrame
        Data frame containing the true and measured coordinates and
        magnitudes and position offsets for the sersic objects.
    visit_name : str
        Visit name combining the visit number and filter, e.g., 'v230-fr'.
    component : str
        Name of the component, e.g., 'R2:2' (for the full center raft),
        'R:2,2 S:1,1' (for the central chip).
    fontsize : str or int, optional
        Font size to use in plots.  Default: 'x-small'
    """
    x_range = (min(min(pointSource['offset']), min(sersic['offset'])),
               max(max(pointSource['offset']), max(sersic['offset'])))
    plt.hist(pointSource['offset'], bins=50, histtype='step',
             label='pointSource', range=x_range)
    plt.hist(sersic['offset'], bins=50, histtype='step', label='sersic',
             range=x_range)
    plt.yscale('log')
    xmin, xmax, ymin, ymax = plt.axis()
    plt.axis([xmin, xmax, 0.5, ymax])
    plt.xlabel('offset from nearest instcat source (arcsec)', fontsize=fontsize)
    plt.ylabel('\nentries / bin', fontsize=fontsize)
    plt.title('%(visit_name)s, %(component)s' % locals(), fontsize=fontsize)
    plt.legend(loc=1, fontsize=fontsize)
项目:vic-tensorflow    作者:sygi    | 项目源码 | 文件源码
def add(self, point, color='b', marker='.', averages=False):
        self.points.append(point)  # TODO: refactor # TODO: some colors
        self.it += 1
        plt.figure(self.figure_id)
        if self.log_scale:
            plt.yscale('log')
        plt.scatter(self.it, point, marker=marker, color=color)

        plt.xlim(0, self.it - self.it % 100 + 100)
        if averages and self.it % 200 == 0:
            ave = sum(self.points[-200:])/len(self.points[-200:])
            plt.plot([self.it - 200, self.it], [ave, ave], color='black')

        plt.legend([self.label], loc='upper left')
        plt.pause(0.0001)
项目:nmt-repr-analysis    作者:boknilev    | 项目源码 | 文件源码
def plot_accuracy_by_freq_compare(freqs1, accuracies1, freqs2, accuracies2, label1, label2, title, filename=None, scale_acc=1.00, yscale_base=10.0, alpha=0.8, tags=None):

    plt.plot(freqs1, accuracies1, marker='o', color='r', label=label1, linestyle='None', fillstyle='none', alpha=alpha)
    plt.plot(freqs2, accuracies2, marker='+', color='c', label=label2, linestyle='None', fillstyle='none', alpha=alpha)

    if tags:
        print 'tags:', tags, 'len:', len(tags)
        print 'len(freqs1):', len(freqs1), 'len(freqs2)', len(freqs2)
        print 'len(accuracies1):', len(accuracies1), 'len(accuracies2)', len(accuracies2)
        if len(tags) == len(freqs1) and len(tags) == len(freqs2):
            print 'annotating tags'
            for i, tag in enumerate(tags):
                plt.annotate(tag, (freqs[1][i], accuracies[1][i]))


    plt.xscale('symlog')
    #plt.yscale('log', basey=yscale_base)
    plt.legend(loc='lower right', prop={'size':14})
    plt.xlabel('Frequency', size='large', fontweight='demibold')
    plt.ylabel('Accuracy', size='large', fontweight='demibold')
    plt.ylim(ymax=1.01*scale_acc)
    plt.title(title, fontweight='demibold')
    plt.tight_layout()
    if filename:
        print 'saving plot to:', filename
        plt.savefig(filename)
项目:nmt-repr-analysis    作者:boknilev    | 项目源码 | 文件源码
def plot_accuracy_by_tag_compare(accuracies1, accuracies2, tags, tag_freq_dict, label1, label2, title, filename=None, scale_acc=1.00, yscale_base=10.0, alpha=0.5):
    #from adjustText import adjust_text 
    tag_freqs = [tag_freq_dict[tag] for tag in tags]
    #plt.plot(tag_freqs, accuracies1, marker='o', color='r', label=label1, linestyle='None', fillstyle='none', alpha=alpha)
    #plt.plot(tag_freqs, accuracies2, marker='+', color='y', label=label2, linestyle='None', fillstyle='none', alpha=alpha)
    # plt.plot(tag_freqs, accuracies2-accuracies1, marker='o', color='c', label=label2, linestyle='None', fillstyle='none', alpha=alpha)
    plt.scatter(tag_freqs, accuracies2-accuracies1, s=np.pi * (0.5 * (accuracies2-accuracies1)+10 )**2, c = np.random.rand(len(tag_freqs)), alpha=0.5)

    print 'annotating tags'
    texts = []
    for i, tag in enumerate(tags):
        #plt.annotate(tag, (tag_freqs[i], accuracies1[i]), xytext=(-10,10), \
        #        textcoords='offset points', ha='right', va='bottom', \
        #        arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))
        #plt.annotate(tag, (tag_freqs[i], accuracies1[i]))
        #plt.annotate(tag, (tag_freqs[i], accuracies2[i]))
        plt.annotate(tag, (tag_freqs[i], accuracies2[i]-accuracies1[i]), horizontalalignment='center', verticalalignment='center', size=10+0.05*(accuracies2[i]-accuracies1[i]))
        #texts.append(plt.text(tag_freqs[i], accuracies1[i], tag))
    #adjust_text(texts, force_text=0.05, arrowprops=dict(arrowstyle="-|>", color='r', alpha=0.5))

    plt.xscale('symlog')
    #plt.yscale('log', basey=yscale_base)
    #plt.legend(loc='lower right', prop={'size':14})
    plt.xlabel('Frequency', size='large', fontweight='demibold')
    plt.ylabel('Increase in Accuracy', size='large', fontweight='demibold')
    #plt.ylim(ymax=1.05*scale_acc)
    plt.ylim(ymax=1.15*max(accuracies2-accuracies1))
    plt.xlim(min(tag_freqs) / 2, max(tag_freqs) * 5)
    plt.title(title, fontweight='demibold')
    plt.tight_layout()
    if filename:
        print 'saving plot to:', filename
        plt.savefig(filename)
项目:ase16    作者:txt    | 项目源码 | 文件源码
def coced1(max=1000):
  import matplotlib.pyplot as plt

  random.seed(1)
  c = Cocomo()
  n = 0
  out = sorted([c.xy() for x in range(max)],
               key=lambda x: x[1])
  xs = []
  ys = []
  for x, y in out:
    n += 1
    xs.append(n)
    ys.append(y)
  p1, = plt.plot(xs, ys, 'ro')
  p2, = plt.plot(xs, [x * 2 for x in ys], 'bo')
  plt.legend([p2, p1], ["small", "bigger"], loc=4)
  plt.xlim(0, 1050)
  plt.yscale('log')
  plt.ylabel('effort')
  plt.xlabel('all efforts, sorted')

  plt.show()
  # plt.savefig('coced1.png')

# coced1()
项目:mlprojects-py    作者:srinathperera    | 项目源码 | 文件源码
def draw_timeseries_chart(data, headers, maxEntries=50):
    #y_pred_limit = min(maxEntries, len(y_test))
    length = min(maxEntries,data.shape[0])
    xdata = np.array(range(length))
    for i in range(data.shape[1]):
        plt.plot(xdata, data[:,i], label=headers[i], linewidth=1) #see http://matplotlib.org/api/pyplot_api.html for other type of lines

        #plt.plot(y_pred_limit, y_pred1, '--', color='r', linewidth=2, label='prediction1')

    plt.legend(loc=0)
    plt.yscale('log')
    plt.show()
项目:mlprojects-py    作者:srinathperera    | 项目源码 | 文件源码
def draw_dl_loss(loss_data, val_loss_data, headers, maxEntries=50):
    #y_pred_limit = min(maxEntries, len(y_test))
    length = min(maxEntries,loss_data.shape[0])
    xdata = np.array(range(length))
    for i in range(loss_data.shape[1]):
        #print xdata.shape, loss_data[:,i].shape, val_loss_data[:,i].shape
        plt.plot(xdata, loss_data[:,i], '-', label=headers[i], linewidth=1)
        plt.plot(xdata, val_loss_data[:,i], '--', label='val_'+headers[i], linewidth=1)

    plt.legend(loc=0)
    plt.xlabel('Loss', fontsize=18)
    plt.ylabel('Number of epoches', fontsize=18)

    #plt.yscale('log')
    plt.show()
项目:mlprojects-py    作者:srinathperera    | 项目源码 | 文件源码
def analyze_error():
    df = pd.read_csv('forecast_with_data.csv')

    df['error'] = np.abs(np.log(df['actual'].values +1) - np.log(df['predictions'].values + 1))
    df['Slopes'] = np.round(df['Slopes'].values)

    print df.describe()



    plt.figure(1, figsize=(20,10))
    plt.subplot(321)
    plt.xlabel('Error', fontsize=18)
    plt.ylabel('Slope', fontsize=18)
    #plt.yscale('log')
    #plt.xscale('log')
    plt.scatter(df['Slopes'].values, df['error'].values, alpha=0.5)

    groupe2d = df.groupby(['Slopes'])['error'].mean()
    plt.subplot(322)
    plt.xlabel('Slope', fontsize=18)
    plt.ylabel('Mean Error', fontsize=18)
    plt.scatter(groupe2d.index.values, groupe2d.values, alpha=0.5)

    df['groupedStd'] = np.round(df['groupedStd'].values)
    groupe2d = df.groupby(['groupedStd'])['error'].mean()
    plt.subplot(323)
    plt.xlabel('groupedStd', fontsize=18)
    plt.ylabel('Mean Error', fontsize=18)
    plt.scatter(groupe2d.index.values, groupe2d.values, alpha=0.5)

    df['groupedMeans'] = np.round(df['groupedMeans'].values)
    groupe2d = df.groupby(['groupedMeans'])['error'].mean()
    plt.subplot(324)
    plt.xlabel('groupedMeans', fontsize=18)
    plt.ylabel('Mean Error', fontsize=18)
    plt.scatter(groupe2d.index.values, groupe2d.values, alpha=0.5)
项目:mlprojects-py    作者:srinathperera    | 项目源码 | 文件源码
def analyze_error():
    df = pd.read_csv('forecast_with_data.csv')

    df['error'] = np.abs(np.log(df['actual'].values +1) - np.log(df['predictions'].values + 1))
    df['Slopes'] = np.round(df['Slopes'].values)

    print df.describe()



    plt.figure(1, figsize=(20,10))
    plt.subplot(321)
    plt.xlabel('Error', fontsize=18)
    plt.ylabel('Slope', fontsize=18)
    #plt.yscale('log')
    #plt.xscale('log')
    plt.scatter(df['Slopes'].values, df['error'].values, alpha=0.5)

    groupe2d = df.groupby(['Slopes'])['error'].mean()
    plt.subplot(322)
    plt.xlabel('Slope', fontsize=18)
    plt.ylabel('Mean Error', fontsize=18)
    plt.scatter(groupe2d.index.values, groupe2d.values, alpha=0.5)

    df['groupedStd'] = np.round(df['groupedStd'].values)
    groupe2d = df.groupby(['groupedStd'])['error'].mean()
    plt.subplot(323)
    plt.xlabel('groupedStd', fontsize=18)
    plt.ylabel('Mean Error', fontsize=18)
    plt.scatter(groupe2d.index.values, groupe2d.values, alpha=0.5)

    df['groupedMeans'] = np.round(df['groupedMeans'].values)
    groupe2d = df.groupby(['groupedMeans'])['error'].mean()
    plt.subplot(324)
    plt.xlabel('groupedMeans', fontsize=18)
    plt.ylabel('Mean Error', fontsize=18)
    plt.scatter(groupe2d.index.values, groupe2d.values, alpha=0.5)
项目:mlprojects-py    作者:srinathperera    | 项目源码 | 文件源码
def show_error_by_feature(df, feature_name, chartloc, redo_x = True):
    start  = time.time()
    group1 = df.groupby([feature_name])['error']
    errors_by_feature = g2df_sum_mean(group1).sort("mean")


    #plt.subplot(chartloc)
    #plt.xlabel(feature_name + " in sorted order by Mean", fontsize=18)
    #plt.ylabel('Mean Error/Rank', fontsize=18)
    #plt.yscale('log')
    #plt.xscale('log')
    #plt.scatter(errors_by_feature[feature_name].values, errors_by_feature['mean'].values, alpha=0.5)
    if redo_x:
        x = range(0, errors_by_feature.shape[0])
    else:
        x = errors_by_feature[feature_name]

    data = [(x, errors_by_feature['mean'].values), (x, np.log(errors_by_feature['rank'].values))]
    draw_scatterplot(data, "Mean Error, Rank vs. "+ feature_name, chartloc, c =['b', 'r'])

    #plt.scatter(x, errors_by_feature['mean'].values, alpha=0.5, color='b', s=5)
    #plt.scatter(x, np.log(errors_by_feature['rank'].values), alpha=0.5, color='r', s=5)

    print "show_error_by_feature", feature_name, "took", (time.time() - start), "s"

    return errors_by_feature
项目:KDDCUP2016    作者:hugochan    | 项目源码 | 文件源码
def cdf(v, title='', 
                xlabel='', ylabel='', 
                xlim=(), ylim=(), 
                xscale='linear', yscale='linear', 
                linewidth=1.5, 
                outfile=None) :

    fs = count(v)
    values, freqs = zip(*sorted(fs.items()))  # Split values and frequencies sorting by the values

    cum  = np.cumsum(freqs, dtype=np.float64)
    cum /= np.sum(freqs)

    pp.clf()

    matplotlib.rc('font', size=24)

    pp.title(title) #, {'fontsize' : 22}
    pp.xlabel(xlabel)
    pp.ylabel(ylabel)
    pp.xscale(xscale)
    pp.yscale(yscale)
    pp.grid()
#   pp.tight_layout(pad=0.2)

#   pp.yscale('log')

    if xlim : pp.xlim(xlim)
    if ylim : pp.ylim(ylim)

    pp.tight_layout(pad=0.10)
    pp.plot(values, cum, lw=linewidth)
#   pp.show()

    if outfile:
        pp.savefig(outfile)
项目:KDDCUP2016    作者:hugochan    | 项目源码 | 文件源码
def rank(v, title='', xlabel='', ylabel='', xlim=(), ylim=(), xscale='linear', yscale='linear', linewidth=2, outfile='') :

    v.sort(reverse=True)

    pp.clf()
    pp.title(title)
    pp.xlabel(xlabel)
    pp.ylabel(ylabel)
    pp.xscale(xscale)
    pp.yscale(yscale)
    pp.grid()


    if xlim : pp.xlim(xlim)
    if ylim : pp.ylim(ylim)

    # Remove zeros
    v = filter(lambda x: x>0, v)

    cum =  np.cumsum(v, dtype=np.float64)
    cum /= cum[-1]

    pp.plot(np.arange(1, len(cum)+1), cum, lw=linewidth)

#   pp.plot(values, cum, lw=linewidth)
    if outfile:
        pp.savefig(outfile)

    else:
        show()
项目:parametrix    作者:vincentchoqueuse    | 项目源码 | 文件源码
def plot(self):

        for column_index,column_name in enumerate(self.get_column_names()):

            if self.hold_on is False:
                plt.figure()

            plt.title("Parameter %s" % column_name)

            for index_technique,technique in enumerate(self.technique_list):
                y=self.Values[:,index_technique,column_index]
                plt.plot(self.row_values,y,label="Exp: %s" %technique)

            for index_statistic,statistic in enumerate(self.statistic_list):
                y=np.ravel(self.Statistics[:,index_statistic,column_index])
                plt.plot(self.row_values,y,label="Theo: %s" %statistic)

            plt.xlabel(self.row_name)
            plt.legend(loc="best")

            try:
                plt.xscale(self.xscale)
                plt.yscale(self.yscale)
            except:
                print("cannot change scale")

            if self.ylim is not None:
                plt.ylim(self.ylim)
项目:pymake    作者:dtrckd    | 项目源码 | 文件源码
def plot_degree_poly_l(Y):
    """ Same than plot_degree_poly, but for a list of random graph ie plot errorbar."""
    x, y, yerr = random_degree(Y)

    plt.xscale('log'); plt.yscale('log')

    fit = np.polyfit(np.log(x), np.log(y), deg=1)
    plt.plot(x,np.exp(fit[0] *np.log(x) + fit[1]), 'm:', label='model power %.2f' % fit[1])
    leg = plt.legend(loc='upper right',prop={'size':10})

    plt.errorbar(x, y, yerr=yerr, fmt='o')

    plt.xlim(left=1)
    plt.ylim((.9,1e3))
    plt.xlabel('Degree'); plt.ylabel('Counts')
项目:dd_performances    作者:jolibrain    | 项目源码 | 文件源码
def gen_platform():
  #concat array to compare each platform
  x = [1,2,3,4] #4 platforms place holder 
  for i in range(13):#13models currently
    a1 = gtx[:,i]
    a2 = tx1[:,i]
    a3 = tk1[:,i]
    a4 = raspi[:,i]

    out = np.concatenate((a1,a2,a3,a4),axis = 1)
    out = out.transpose()

  #plot formatting
    #uncomment for custom dimension
    #plt.figure(figsize=(10,6))
    plt.ylabel('log time per image(ms)') 
    plt.yscale('log')
    plt.xticks(x,platform_dd)
    plt.xlabel('platform')
    plt.title(y_dd[i])
    plt.ylim([1,10000])

    lines = plt.plot(x,out,'--o')

    ## mask to prevent adding of legend with no data based on the gtx1080Ti
    filtre = np.asarray(np.isnan(gtx[:,i])).transpose()[0]
    temp = len(lines)
    for k in reversed(range(temp)):
      if filtre[k]:
        lines.remove(lines[k])

    x_dd_masked = np.asarray(x_dd)
    x_dd_masked[filtre] = np.ma.masked
    #adding lengends
    legend = plt.legend(lines,[x_dd_masked[j] for j in range(len(lines))])

    ## uncomment to generate image files##
    plt.savefig(y_dd[i]+'.png', bbox_inches='tight')
    plt.clf()
    # plt.show()
    plt.close()
项目:dd_performances    作者:jolibrain    | 项目源码 | 文件源码
def gen_depthwise():
  gtx_ = np.asarray(gtx[:,0:2]).transpose()
  tx1_ = np.asarray(tx1[:,0:2]).transpose()
  tk1_ = np.asarray(tk1[:,0:2]).transpose()
  raspi_ = np.asarray(raspi[:,0:2]).transpose()

  out = [gtx_, tx1_, tk1_, raspi_] 

  for i in range(len(platform_dd)):
    plt.ylabel('log time per image(ms)')
    plt.yscale('log')
    plt.ylim([0.5, 300*10**(i+1) + 8**(i+1)]) #manipulating axis
    plt.xlabel('batch size')
    plt.xscale('log')
    plt.xlim([0.5,256])
    plt.xticks(x_dd,x_dd)
    plt.figtext(.5,.93,platform_dd[i], fontsize=18, ha='center')
    plt.figtext(.5,.9,'mobilenet improvement by depthwise convolution',fontsize=10,ha='center')        
    plt.minorticks_off()

    line = plt.plot(x_dd,out[i][0],'--o', label='mobilenet')
    line1 = plt.plot(x_dd,out[i][1],'--o', label='mobilenet depthwise')

    plt.legend()      
    #plt.show()
    plt.savefig('mobilenet_'+platform_dd[i]+'.png', bbox_inches='tight')
    plt.clf()
    plt.close()

##run stuff here
#gen_platform()
#gen_cost()
#gen_small_cost()
#gen_depthwise()
项目:DistributedMNIST    作者:agnusmaximus    | 项目源码 | 文件源码
def plot_step_loss(outdir):
    plt.cla()
    plt.xlabel("step")
    plt.ylabel("losses")
    files = glob.glob(outdir + "/*evaluator*")
    cmap = plt.get_cmap('jet')
    colors = cmap(np.linspace(0, 1.0, len(files)))
    plt.yscale('log')
    #plt.xscale('log')
    for i, fname in enumerate(files):
        label = fname.split("/")[-1]
        times, losses, precisions, steps = extract_times_losses_precision(fname)
        plt.plot(steps, losses, linestyle='solid', label=label, color=colors[i])
    plt.legend(loc="upper right", fontsize=8)
    plt.savefig("step_losses.png")
项目:DistributedMNIST    作者:agnusmaximus    | 项目源码 | 文件源码
def plot_time_loss(outdir):
    plt.cla()
    plt.xlabel("time (s)")
    plt.ylabel("loss")
    files = glob.glob(outdir + "/*evaluator*")
    cmap = plt.get_cmap('jet')
    colors = cmap(np.linspace(0, 1.0, len(files)))
    plt.yscale('log')
    #plt.xscale('log')
    for i, fname in enumerate(files):
        label = fname.split("/")[-1]
        times, losses, precisions, steps = extract_times_losses_precision(fname)
        plt.plot(times, losses, linestyle='solid', label=label, color=colors[i])
    plt.legend(loc="upper right", fontsize=8)
    plt.savefig("time_loss.png")
项目:HiCembler    作者:lpryszcz    | 项目源码 | 文件源码
def main(fn, method="ward"): #
    d, bin_chr, bin_position, contig2size = load_matrix(fn, remove_shorter=0)
    sizes = np.diff(bin_position, axis=1)[:, 0] / 1000
    contacts = d.diagonal()
    print d.sum(), d.diagonal().sum()
    # get bins
    bins = np.arange(1, 101, 5)

    # get counts
    contacts = [[] for i in range(len(bins)+1)]
    for s, c in zip(np.digitize(sizes, bins, right=1), d.diagonal()):
        contacts[s].append(c)
    print len(contacts), len(bins), len(sizes)#, contacts# np.digitize(sizes, bins, right=1)
    plt.title("HiC contacts at given distance")
    plt.boxplot(contacts[:-1], 1, '', positions=bins, widths=.75*bins[0])#; plt.legend("HiC data")
    plt.xticks(rotation=90)

    plt.xlabel("contig size [kb]")
    plt.ylabel("self contacts")
    plt.xlim(xmin=-bins[0])
    plt.ylim(ymin=0)#, ymax=20)
    #plt.yscale('log')
    #plt.show()
    outfn = fn+".selfcontacts.png"
    plt.savefig(outfn)
    print "Figure saved as: %s"%outfn
项目:scanpy    作者:theislab    | 项目源码 | 文件源码
def filter_genes_dispersion(result, log=False, save=None, show=None):
    """Plot dispersions vs. means for genes.

    Produces Supp. Fig. 5c of Zheng et al. (2017) and MeanVarPlot() of Seurat.

    Parameters
    ----------
    result: np.recarray
        Result of sc.pp.filter_genes_dispersion.
    log : bool
        Plot on logarithmic axes.
    """
    gene_subset = result.gene_subset
    means = result.means
    dispersions = result.dispersions
    dispersions_norm = result.dispersions_norm
    for id, d in enumerate([dispersions_norm, dispersions]):
        pl.figure(figsize=rcParams['figure.figsize'])
        for label, color, mask in zip(['highly variable genes', 'other genes'],
                                      ['black', 'grey'],
                                      [gene_subset, ~gene_subset]):
            if False: means_, disps_ = np.log10(means[mask]), np.log10(d[mask])
            else: means_, disps_ = means[mask], d[mask]
            pl.scatter(means_, disps_, label=label, c=color, s=1)
        if log:  # there's a bug in autoscale
            pl.xscale('log')
            pl.yscale('log')
            min_dispersion = np.min(dispersions)
            y_min = 0.95*min_dispersion if min_dispersion > 0 else 1e-1
            pl.xlim(0.95*np.min(means), 1.05*np.max(means))
            pl.ylim(y_min, 1.05*np.max(dispersions))
        pl.legend()
        pl.xlabel(('$log_{10}$ ' if False else '') + 'mean expression of gene')
        pl.ylabel(('$log_{10}$ ' if False else '') + 'dispersion of gene'
                  + (' (normalized)' if id == 0 else ' (not normalized)'))
    utils.savefig_or_show('filter_genes_dispersion', show=show, save=save)
项目:reinforcement-learning-an-introduction    作者:ShangtongZhang    | 项目源码 | 文件源码
def figure10_2():
    runs = 10
    episodes = 500
    numOfTilings = 8
    alphas = [0.1, 0.2, 0.5]

    steps = np.zeros((len(alphas), episodes))
    for run in range(0, runs):
        valueFunctions = [ValueFunction(alpha, numOfTilings) for alpha in alphas]
        for index in range(0, len(valueFunctions)):
            for episode in range(0, episodes):
                print('run:', run, 'alpha:', alphas[index], 'episode:', episode)
                step = semiGradientNStepSarsa(valueFunctions[index])
                steps[index, episode] += step

    steps /= runs

    global figureIndex
    plt.figure(figureIndex)
    figureIndex += 1
    for i in range(0, len(alphas)):
        plt.plot(steps[i], label='alpha = '+str(alphas[i])+'/'+str(numOfTilings))
    plt.xlabel('Episode')
    plt.ylabel('Steps per episode')
    plt.yscale('log')
    plt.legend()

# Figure 10.3, one-step semi-gradient Sarsa vs multi-step semi-gradient Sarsa
项目:reinforcement-learning-an-introduction    作者:ShangtongZhang    | 项目源码 | 文件源码
def figure10_3():
    runs = 10
    episodes = 500
    numOfTilings = 8
    alphas = [0.5, 0.3]
    nSteps = [1, 8]

    steps = np.zeros((len(alphas), episodes))
    for run in range(0, runs):
        valueFunctions = [ValueFunction(alpha, numOfTilings) for alpha in alphas]
        for index in range(0, len(valueFunctions)):
            for episode in range(0, episodes):
                print('run:', run, 'steps:', nSteps[index], 'episode:', episode)
                step = semiGradientNStepSarsa(valueFunctions[index], nSteps[index])
                steps[index, episode] += step

    steps /= runs
    global figureIndex
    plt.figure(figureIndex)
    figureIndex += 1
    for i in range(0, len(alphas)):
        plt.plot(steps[i], label='n = '+str(nSteps[i]))
    plt.xlabel('Episode')
    plt.ylabel('Steps per episode')
    plt.yscale('log')
    plt.legend()

# Figure 10.4, effect of alpha and n on multi-step semi-gradient Sarsa
项目:core    作者:cherab    | 项目源码 | 文件源码
def mapping_caching2d_resolution(function2d, space_area):
    """
    Plot a map of the mean relative error when caching function2d with different resolutions.
    :param function2d: 2D function to be cached
    :param space_area: area where the function has to be cached: (minx, maxx, miny, maxy)
    """

    minx, maxx, miny, maxy = space_area
    nb_samplesx = 50
    nb_samplesy = 50

    errors = np.empty((20, 20))
    resolutionsx = np.logspace(np.log10(maxx - minx) - 2, np.log10(maxx - minx), 20)
    resolutionsy = np.logspace(np.log10(maxy - miny) - 2, np.log10(maxy - miny), 20)

    for i in range(20):
        for j in range(20):

            print(i, j)
            resolutionx = resolutionsx[i]
            resolutiony = resolutionsy[j]
            cached_function = Caching2D(function2d, space_area, (resolutionx, resolutiony))
            error = 0.
            nb_zeros = 0
            for x in np.linspace(minx, maxx, nb_samplesx):
                for y in np.linspace(miny, maxy, nb_samplesy):
                    ref_value = function2d(x, y)
                    if ref_value != 0:
                        error += abs((cached_function(x, y) - ref_value) / ref_value)
                    else:
                        nb_zeros += 1
            error /= nb_samplesx * nb_samplesy - nb_zeros
            errors[i, j] = error

    plt.contourf(resolutionsx, resolutionsy, errors.T)
    plt.xlabel('resolution x')
    plt.ylabel('resolution y')
    plt.xscale('log')
    plt.yscale('log')
    plt.colorbar()
    plt.show()
项目:chainer-DenseNet    作者:t-hanya    | 项目源码 | 文件源码
def main():
    # define command line argument
    parser = argparse.ArgumentParser(description='Visualize training result')
    parser.add_argument('log', help='log file path to visuzlize')
    parser.add_argument('--out', '-o', default='.', help='output directory')
    args = parser.parse_args()

    # prepare output directory
    if not os.path.exists(args.out):
        os.makedirs(args.out)

    # visualize training loss
    data = json.load(open(args.log))
    epoch = np.array([d["epoch"] for d in data])
    training_loss = np.array([d["main/loss"] for d in data])

    plt.plot(epoch, training_loss)
    plt.yscale('log')
    plt.ylabel('training loss')
    plt.xlabel('epoch')
    plt.grid(True)

    png_path = os.path.join(args.out, 'training_loss.png')
    plt.savefig(png_path)
    plt.close()

    # visualize test error
    test_acc = np.array([d["validation/main/accuracy"] for d in data])
    test_error = (1. - test_acc) * 100

    plt.plot(epoch, test_error)
    plt.yscale('linear')
    plt.ylabel('test_error [%]')
    plt.xlabel('epoch')
    plt.grid(True)
    plt.ylim([0, 20])

    png_path = os.path.join(args.out, 'test_error.png')
    plt.savefig(png_path)
    plt.close()
项目:cnn_workshop    作者:Alfredvc    | 项目源码 | 文件源码
def visualize_learning(net):
    train_loss = np.array([i["train_loss"] for i in net.train_history_])
    valid_loss = np.array([i["valid_loss"] for i in net.train_history_])
    pyplot.plot(train_loss, linewidth=3, label="train")
    pyplot.plot(valid_loss, linewidth=3, label="valid")
    pyplot.grid()
    pyplot.legend()
    pyplot.xlabel("epoch")
    pyplot.ylabel("loss")
    ymax = max(np.max(valid_loss), np.max(train_loss))
    ymin = min(np.min(valid_loss), np.min(train_loss))
    pyplot.ylim(ymin * 0.8, ymax * 1.2)
    pyplot.yscale("log")
    pyplot.show()
项目:acl2017-interactive_summarizer    作者:UKPLab    | 项目源码 | 文件源码
def plot_scores(self, labels, scores, filename):
        self.users = 2
        f, axis = plt.subplots(2, sharex=True, sharey=False, figsize=(4, 6))
        colors = ['g','b','r', '#8E4585']
        linestyles = ['->', '-o', '-', '-x']
        iterations= 8

        for i in range(self.users):
            for index, score in enumerate(scores):
                y = score
                if index == 0:
                    axis[i].plot(range(len(y[i][1:])), len(y[i][1:]) *[y[i][0]], 'k--', label = 'Upper bound', linewidth=2)
                #axis[i].plot(range(len(y[i][1:])), len(y[i][1:]) *[y[i][0]], 'k--', label = 'Upper-bound')
                if i>0:
                    axis[i].plot(range(len(y[i][1:])), y[i][1:], linestyles[index], color=colors[index], label='%s' % labels[index], linewidth=2)
                else:
                    axis[i].plot(range(len(y[i][1:])), y[i][1:], linestyles[index], color=colors[index], label='%s' % labels[index], linewidth=2)
            axis[i].set_title('User:%s' % str(i+1))
            axis[i].set_xticks(np.arange(0, iterations, 1))
            axis[i].set_xticklabels(np.arange(0, iterations, 1))
            axis[i].set_ylabel('ROUGE 2', fontsize=13)
            axis[i].grid(True)

        plt.legend(loc="best", fontsize=9)
        plt.xlabel("\# Iterations", fontsize=15)
        plt.yscale("linear")
        plt.xlim(0,iterations)
        plt.tight_layout()
        savefig(filename)
项目:acl2017-interactive_summarizer    作者:UKPLab    | 项目源码 | 文件源码
def plot_scores(self, rouge_type='R1_score'):
        ub_scores = self.rows[0]
        users = len(ub_scores[1:])/self.info_num

        y = [[] for user in range(users)]
        for iteration in range(0,len(self.rows)):
            row = self.rows[iteration]
            for user in range(users):
                if rouge_type == 'R1_score':
                    val = row[1+user*self.info_num]
                    if val != "":
                        y[user].append(float(val))
                if rouge_type == 'R2_score':
                    val = row[2+user*self.info_num]
                    if val != "":
                        y[user].append(float(val))


        plt.subplot(211)
        plt.plot(range(len(y[0][1:])), len(y[0][1:]) *[y[0][0]], 'k--', label='UB1')
        plt.plot(range(len(y[0][1:])), y[0][1:], 'r', label='User 1')
        plt.plot(range(len(y[1][1:])), len(y[1][1:]) *[y[1][0]], 'k--', label='UB2')
        plt.plot(range(len(y[1][1:])), y[1][1:], 'b', label='User 2')

        plt.legend(loc="lower right")

        plt.subplot(212)
        plt.plot(range(len(y[2][1:])), len(y[2][1:]) *[y[2][0]], 'k--', label='UB3')
        plt.plot(range(len(y[2][1:])), y[2][1:],'y', label='User 3')
        plt.plot(range(len(y[3][1:])), len(y[3][1:]) *[y[3][0]], 'k--', label='UB4')
        plt.plot(range(len(y[3][1:])), y[3][1:], 'g', label='User 4')

        plt.legend(loc="lower right")
        plt.xlabel("No. of iterations")
        plt.ylabel(rouge_type)
        plt.yscale("linear")
        plt.show()
项目:tf-sparql    作者:derdav3    | 项目源码 | 文件源码
def plot_res(test_err, train_batch_loss, benchmark_err, epoch):
    '''Plot result of model

    Args:
        test_err: 'float', test error of model
        train_batch_loss: 'tuple', tuple of train error of model x & y
        benchmark_err: 'tuple', error of using no model
        epoch: 'int', current epoch

    '''
    flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"]

    test_x_val = np.array(list(x * 3 for x in range(0, len(test_err))))

    plt.plot(train_batch_loss[0],train_batch_loss[1], label="Training error", c=flatui[1], alpha=0.5)
    plt.plot(test_x_val, np.array(test_err), label="Test error", c=flatui[0])
    plt.axhline(y=benchmark_err[1], linestyle='dashed', label="No-modell error", c=flatui[2])
    plt.axhline(y=0.098, linestyle='dashed', label="State of the art error", c=flatui[3])

    plt.suptitle("Model error - cold queries")
    plt.yscale('log', nonposy='clip')
    plt.xlim([0,epoch+1])
    plt.xlabel('epoch')
    plt.ylabel('error')
    plt.legend(loc='upper right')
    plt.show()