Python matplotlib.pylab.title() Examples

The following are 30 code examples of matplotlib.pylab.title(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.pylab , or try the search function .
Example #1
Source File: utils.py    From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License 6 votes vote down vote up
def plot_roc(auc_score, name, tpr, fpr, label=None):
    pylab.clf()
    pylab.figure(num=None, figsize=(5, 4))
    pylab.grid(True)
    pylab.plot([0, 1], [0, 1], 'k--')
    pylab.plot(fpr, tpr)
    pylab.fill_between(fpr, tpr, alpha=0.5)
    pylab.xlim([0.0, 1.0])
    pylab.ylim([0.0, 1.0])
    pylab.xlabel('False Positive Rate')
    pylab.ylabel('True Positive Rate')
    pylab.title('ROC curve (AUC = %0.2f) / %s' %
                (auc_score, label), verticalalignment="bottom")
    pylab.legend(loc="lower right")
    filename = name.replace(" ", "_")
    pylab.savefig(
        os.path.join(CHART_DIR, "roc_" + filename + ".png"), bbox_inches="tight") 
Example #2
Source File: plot_kmeans_example.py    From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License 6 votes vote down vote up
def plot_clustering(x, y, title, mx=None, ymax=None, xmin=None, km=None):
    pylab.figure(num=None, figsize=(8, 6))
    if km:
        pylab.scatter(x, y, s=50, c=km.predict(list(zip(x, y))))
    else:
        pylab.scatter(x, y, s=50)

    pylab.title(title)
    pylab.xlabel("Occurrence word 1")
    pylab.ylabel("Occurrence word 2")

    pylab.autoscale(tight=True)
    pylab.ylim(ymin=0, ymax=1)
    pylab.xlim(xmin=0, xmax=1)
    pylab.grid(True, linestyle='-', color='0.75')

    return pylab 
Example #3
Source File: testfuncs.py    From Computable with MIT License 6 votes vote down vote up
def plotallfuncs(allfuncs=allfuncs):
    from matplotlib import pylab as pl
    pl.ioff()
    nnt = NNTester(npoints=1000)
    lpt = LinearTester(npoints=1000)
    for func in allfuncs:
        print(func.title)
        nnt.plot(func, interp=False, plotter='imshow')
        pl.savefig('%s-ref-img.png' % func.func_name)
        nnt.plot(func, interp=True, plotter='imshow')
        pl.savefig('%s-nn-img.png' % func.func_name)
        lpt.plot(func, interp=True, plotter='imshow')
        pl.savefig('%s-lin-img.png' % func.func_name)
        nnt.plot(func, interp=False, plotter='contour')
        pl.savefig('%s-ref-con.png' % func.func_name)
        nnt.plot(func, interp=True, plotter='contour')
        pl.savefig('%s-nn-con.png' % func.func_name)
        lpt.plot(func, interp=True, plotter='contour')
        pl.savefig('%s-lin-con.png' % func.func_name)
    pl.ion() 
Example #4
Source File: demo_mi.py    From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License 6 votes vote down vote up
def plot_entropy():
    pylab.clf()
    pylab.figure(num=None, figsize=(5, 4))

    title = "Entropy $H(X)$"
    pylab.title(title)
    pylab.xlabel("$P(X=$coin will show heads up$)$")
    pylab.ylabel("$H(X)$")

    pylab.xlim(xmin=0, xmax=1.1)
    x = np.arange(0.001, 1, 0.001)
    y = -x * np.log2(x) - (1 - x) * np.log2(1 - x)
    pylab.plot(x, y)
    # pylab.xticks([w*7*24 for w in [0,1,2,3,4]], ['week %i'%(w+1) for w in
    # [0,1,2,3,4]])

    pylab.autoscale(tight=True)
    pylab.grid(True)

    filename = "entropy_demo.png"
    pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight") 
Example #5
Source File: kNN.py    From statistical-learning-methods-note with Apache License 2.0 6 votes vote down vote up
def plotKChart(self, misClassDict, saveFigPath):
        kList = []
        misRateList = []
        for k, misClassNum in misClassDict.iteritems():
            kList.append(k)
            misRateList.append(1.0 - 1.0/k*misClassNum)

        fig = plt.figure(saveFigPath)
        plt.plot(kList, misRateList, 'r--')
        plt.title(saveFigPath)
        plt.xlabel('k Num.')
        plt.ylabel('Misclassified Rate')
        plt.legend(saveFigPath)
        plt.grid(True)
        plt.savefig(saveFigPath)
        plt.show()

################################### PART3 TEST ########################################
# 例子 
Example #6
Source File: utils.py    From ndvr-dml with Apache License 2.0 6 votes vote down vote up
def plot_pr_curve(pr_curve_dml, pr_curve_base, title):
    """
      Function that plots the PR-curve.

      Args:
        pr_curve: the values of precision for each recall value
        title: the title of the plot
    """
    plt.figure(figsize=(16, 9))
    plt.plot(np.arange(0.0, 1.05, 0.05),
             pr_curve_base, color='r', marker='o', linewidth=3, markersize=10)
    plt.plot(np.arange(0.0, 1.05, 0.05),
             pr_curve_dml, color='b', marker='o', linewidth=3, markersize=10)
    plt.grid(True, linestyle='dotted')
    plt.xlabel('Recall', color='k', fontsize=27)
    plt.ylabel('Precision', color='k', fontsize=27)
    plt.yticks(color='k', fontsize=20)
    plt.xticks(color='k', fontsize=20)
    plt.ylim([0.0, 1.05])
    plt.xlim([0.0, 1.0])
    plt.title(title, color='k', fontsize=27)
    plt.tight_layout()
    plt.show() 
Example #7
Source File: dataset.py    From Image-Restoration with MIT License 6 votes vote down vote up
def show_pred(images, predictions, ground_truth):
    # choose 10 indice from images and visualize them
    indice = [np.random.randint(0, len(images)) for i in range(40)]
    for i in range(0, 40):
        plt.figure()
        plt.subplot(1, 3, 1)
        plt.tight_layout()
        plt.title('deformed image')
        plt.imshow(images[indice[i]])
        plt.subplot(1, 3, 2)
        plt.tight_layout()
        plt.title('predicted mask')
        plt.imshow(predictions[indice[i]])
        plt.subplot(1, 3, 3)
        plt.tight_layout()
        plt.title('ground truth label')
        plt.imshow(ground_truth[indice[i]])
    plt.show()

# Load Data Science Bowl 2018 training dataset 
Example #8
Source File: utils.py    From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License 6 votes vote down vote up
def plot_confusion_matrix(cm, genre_list, name, title):
    pylab.clf()
    pylab.matshow(cm, fignum=False, cmap='Blues', vmin=0, vmax=1.0)
    ax = pylab.axes()
    ax.set_xticks(range(len(genre_list)))
    ax.set_xticklabels(genre_list)
    ax.xaxis.set_ticks_position("bottom")
    ax.set_yticks(range(len(genre_list)))
    ax.set_yticklabels(genre_list)
    pylab.title(title)
    pylab.colorbar()
    pylab.grid(False)
    pylab.show()
    pylab.xlabel('Predicted class')
    pylab.ylabel('True class')
    pylab.grid(False)
    pylab.savefig(
        os.path.join(CHART_DIR, "confusion_matrix_%s.png" % name), bbox_inches="tight") 
Example #9
Source File: evaluate.py    From text-classifier with Apache License 2.0 6 votes vote down vote up
def plot_pr(auc_score, precision, recall, label=None, figure_path=None):
    """绘制R/P曲线"""
    try:
        from matplotlib import pylab
        pylab.figure(num=None, figsize=(6, 5))
        pylab.xlim([0.0, 1.0])
        pylab.ylim([0.0, 1.0])
        pylab.xlabel('Recall')
        pylab.ylabel('Precision')
        pylab.title('P/R (AUC=%0.2f) / %s' % (auc_score, label))
        pylab.fill_between(recall, precision, alpha=0.5)
        pylab.grid(True, linestyle='-', color='0.75')
        pylab.plot(recall, precision, lw=1)
        pylab.savefig(figure_path)
    except Exception as e:
        print("save image error with matplotlib")
        pass 
Example #10
Source File: utils.py    From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License 6 votes vote down vote up
def plot_feat_importance(feature_names, clf, name):
    pylab.clf()
    coef_ = clf.coef_
    important = np.argsort(np.absolute(coef_.ravel()))
    f_imp = feature_names[important]
    coef = coef_.ravel()[important]
    inds = np.argsort(coef)
    f_imp = f_imp[inds]
    coef = coef[inds]
    xpos = np.array(range(len(coef)))
    pylab.bar(xpos, coef, width=1)

    pylab.title('Feature importance for %s' % (name))
    ax = pylab.gca()
    ax.set_xticks(np.arange(len(coef)))
    labels = ax.set_xticklabels(f_imp)
    for label in labels:
        label.set_rotation(90)
    filename = name.replace(" ", "_")
    pylab.savefig(os.path.join(
        CHART_DIR, "feat_imp_%s.png" % filename), bbox_inches="tight") 
Example #11
Source File: mediator_utils.py    From whynot with MIT License 6 votes vote down vote up
def error_bar_plot(experiment_data, results, title="", ylabel=""):

    true_effect = experiment_data.true_effects.mean()
    estimators = list(results.keys())

    x = list(estimators)
    y = [results[estimator].ate for estimator in estimators]

    cis = [
        np.array(results[estimator].ci) - results[estimator].ate
        if results[estimator].ci is not None
        else [0, 0]
        for estimator in estimators
    ]
    err = [[abs(ci[0]) for ci in cis], [abs(ci[1]) for ci in cis]]

    plt.figure(figsize=(12, 5))
    (_, caps, _) = plt.errorbar(x, y, yerr=err, fmt="o", markersize=8, capsize=5)
    for cap in caps:
        cap.set_markeredgewidth(2)
    plt.plot(x, [true_effect] * len(x), label="True Effect")
    plt.legend(fontsize=12, loc="lower right")
    plt.ylabel(ylabel)
    plt.title(title) 
Example #12
Source File: efficient_frontier.py    From FinQuant with MIT License 6 votes vote down vote up
def plot_efrontier(self):
        """Plots the Efficient Frontier."""
        if self.efrontier is None:
            # compute efficient frontier first
            self.efficient_frontier()
        plt.plot(
            self.efrontier[:, 0],
            self.efrontier[:, 1],
            linestyle="-.",
            color="black",
            lw=2,
            label="Efficient Frontier",
        )
        plt.title("Efficient Frontier")
        plt.xlabel("Volatility")
        plt.ylabel("Expected Return")
        plt.legend() 
Example #13
Source File: utils.py    From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License 6 votes vote down vote up
def plot_feat_importance(feature_names, clf, name):
    pylab.clf()
    coef_ = clf.coef_
    important = np.argsort(np.absolute(coef_.ravel()))
    f_imp = feature_names[important]
    coef = coef_.ravel()[important]
    inds = np.argsort(coef)
    f_imp = f_imp[inds]
    coef = coef[inds]
    xpos = np.array(range(len(coef)))
    pylab.bar(xpos, coef, width=1)

    pylab.title('Feature importance for %s' % (name))
    ax = pylab.gca()
    ax.set_xticks(np.arange(len(coef)))
    labels = ax.set_xticklabels(f_imp)
    for label in labels:
        label.set_rotation(90)
    filename = name.replace(" ", "_")
    pylab.savefig(os.path.join(
        CHART_DIR, "feat_imp_%s.png" % filename), bbox_inches="tight") 
Example #14
Source File: testfuncs.py    From neural-network-animation with MIT License 6 votes vote down vote up
def plotallfuncs(allfuncs=allfuncs):
    from matplotlib import pylab as pl
    pl.ioff()
    nnt = NNTester(npoints=1000)
    lpt = LinearTester(npoints=1000)
    for func in allfuncs:
        print(func.title)
        nnt.plot(func, interp=False, plotter='imshow')
        pl.savefig('%s-ref-img.png' % func.__name__)
        nnt.plot(func, interp=True, plotter='imshow')
        pl.savefig('%s-nn-img.png' % func.__name__)
        lpt.plot(func, interp=True, plotter='imshow')
        pl.savefig('%s-lin-img.png' % func.__name__)
        nnt.plot(func, interp=False, plotter='contour')
        pl.savefig('%s-ref-con.png' % func.__name__)
        nnt.plot(func, interp=True, plotter='contour')
        pl.savefig('%s-nn-con.png' % func.__name__)
        lpt.plot(func, interp=True, plotter='contour')
        pl.savefig('%s-lin-con.png' % func.__name__)
    pl.ion() 
Example #15
Source File: testfuncs.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def plotallfuncs(allfuncs=allfuncs):
    from matplotlib import pylab as pl
    pl.ioff()
    nnt = NNTester(npoints=1000)
    lpt = LinearTester(npoints=1000)
    for func in allfuncs:
        print(func.title)
        nnt.plot(func, interp=False, plotter='imshow')
        pl.savefig('%s-ref-img.png' % func.func_name)
        nnt.plot(func, interp=True, plotter='imshow')
        pl.savefig('%s-nn-img.png' % func.func_name)
        lpt.plot(func, interp=True, plotter='imshow')
        pl.savefig('%s-lin-img.png' % func.func_name)
        nnt.plot(func, interp=False, plotter='contour')
        pl.savefig('%s-ref-con.png' % func.func_name)
        nnt.plot(func, interp=True, plotter='contour')
        pl.savefig('%s-nn-con.png' % func.func_name)
        lpt.plot(func, interp=True, plotter='contour')
        pl.savefig('%s-lin-con.png' % func.func_name)
    pl.ion() 
Example #16
Source File: testfuncs.py    From ImageFusion with MIT License 6 votes vote down vote up
def plotallfuncs(allfuncs=allfuncs):
    from matplotlib import pylab as pl
    pl.ioff()
    nnt = NNTester(npoints=1000)
    lpt = LinearTester(npoints=1000)
    for func in allfuncs:
        print(func.title)
        nnt.plot(func, interp=False, plotter='imshow')
        pl.savefig('%s-ref-img.png' % func.__name__)
        nnt.plot(func, interp=True, plotter='imshow')
        pl.savefig('%s-nn-img.png' % func.__name__)
        lpt.plot(func, interp=True, plotter='imshow')
        pl.savefig('%s-lin-img.png' % func.__name__)
        nnt.plot(func, interp=False, plotter='contour')
        pl.savefig('%s-ref-con.png' % func.__name__)
        nnt.plot(func, interp=True, plotter='contour')
        pl.savefig('%s-nn-con.png' % func.__name__)
        lpt.plot(func, interp=True, plotter='contour')
        pl.savefig('%s-lin-con.png' % func.__name__)
    pl.ion() 
Example #17
Source File: ClimatologySpark2.py    From incubator-sdap-nexus with Apache License 2.0 5 votes vote down vote up
def contourMap(var, variable, coordinates, n, plotFile):
    '''Make contour plot for the var array using coordinates vector for lat/lon coordinates.'''
    # TODO: Downscale variable array (SST) before contouring, matplotlib is TOO slow on large arrays
    # Fixed color scale, write file, turn off auto borders, set title, etc.
    lats = coordinates[0][:]
    lons = coordinates[1][:]
    if lats[1] < lats[0]:  # if latitudes decreasing, reverse
        lats = N.flipud(lats)
        var = N.flipud(var[:])

    imageMap(lons, lats, var,
             vmin=-2., vmax=45., outFile=plotFile, autoBorders=False,
             title='%s %d-day Mean from %s' % (variable.upper(), n, os.path.splitext(plotFile)[0]))
    print >> sys.stderr, 'Writing contour plot to %s' % plotFile
    return plotFile 
Example #18
Source File: kernridgeregress_class.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def example1():
    m,k = 500,4
    upper = 6
    scale=10
    xs1a = np.linspace(1,upper,m)[:,np.newaxis]
    xs1 = xs1a*np.ones((1,4)) + 1/(1.0+np.exp(np.random.randn(m,k)))
    xs1 /= np.std(xs1[::k,:],0)   # normalize scale, could use cov to normalize
    y1true = np.sum(np.sin(xs1)+np.sqrt(xs1),1)[:,np.newaxis]
    y1 = y1true + 0.250 * np.random.randn(m,1)

    stride = 2 #use only some points as trainig points e.g 2 means every 2nd
    gp1 = GaussProcess(xs1[::stride,:],y1[::stride,:], kernel=kernel_euclid,
                       ridgecoeff=1e-10)
    yhatr1 = gp1.predict(xs1)
    plt.figure()
    plt.plot(y1true, y1,'bo',y1true, yhatr1,'r.')
    plt.title('euclid kernel: true y versus noisy y and estimated y')
    plt.figure()
    plt.plot(y1,'bo-',y1true,'go-',yhatr1,'r.-')
    plt.title('euclid kernel: true (green), noisy (blue) and estimated (red) '+
              'observations')

    gp2 = GaussProcess(xs1[::stride,:],y1[::stride,:], kernel=kernel_rbf,
                       scale=scale, ridgecoeff=1e-1)
    yhatr2 = gp2.predict(xs1)
    plt.figure()
    plt.plot(y1true, y1,'bo',y1true, yhatr2,'r.')
    plt.title('rbf kernel: true versus noisy (blue) and estimated (red) observations')
    plt.figure()
    plt.plot(y1,'bo-',y1true,'go-',yhatr2,'r.-')
    plt.title('rbf kernel: true (green), noisy (blue) and estimated (red) '+
              'observations')
    #gp2.plot(y1) 
Example #19
Source File: ClimatologySpark2.py    From incubator-sdap-nexus with Apache License 2.0 5 votes vote down vote up
def histogram(vals, variable, n, outFile):
    figFile = os.path.splitext(outFile)[0] + '_hist.png'
    M.clf()
    #    M.hist(vals, 47, (-2., 45.))
    M.hist(vals, 94)
    M.xlim(-5, 45)
    M.xlabel('SST in degrees Celsius')
    M.ylim(0, 300000)
    M.ylabel('Count')
    M.title('Histogram of %s %d-day Mean from %s' % (variable.upper(), n, outFile))
    M.show()
    print >> sys.stderr, 'Writing histogram plot to %s' % figFile
    M.savefig(figFile)
    return figFile 
Example #20
Source File: plotlib.py    From incubator-sdap-nexus with Apache License 2.0 5 votes vote down vote up
def plotTllv(inFile, markerType='kx', outFile=None, groupBy=None, **options):
    """Plot the lat/lon locations of points from a time/lat/lon/value file."""
    fields = N.array([map(float, line.split()) for line in open(inFile, 'r')])
    lons = fields[:,2]; lats = fields[:,1]
    marksOnMap(lons, lats, markerType, outFile, \
               title='Lat/lon plot of '+inFile, **options) 
Example #21
Source File: ClimatologySpark.py    From incubator-sdap-nexus with Apache License 2.0 5 votes vote down vote up
def histogram(vals, variable, n, outFile):
    figFile = os.path.splitext(outFile)[0] + '_hist.png'
    M.clf()
#    M.hist(vals, 47, (-2., 45.))
    M.hist(vals, 94)
    M.xlim(-5, 45)
    M.xlabel('SST in degrees Celsius')
    M.ylim(0, 300000)
    M.ylabel('Count')
    M.title('Histogram of %s %d-day Mean from %s' % (variable.upper(), n, outFile))
    M.show()
    print >>sys.stderr, 'Writing histogram plot to %s' % figFile
    M.savefig(figFile)
    return figFile 
Example #22
Source File: climatology3Spark.py    From incubator-sdap-nexus with Apache License 2.0 5 votes vote down vote up
def contourMap(var, variable, coordinates, n, outFile):
    figFile = os.path.splitext(outFile)[0] + '_hist.png'
    # TODO: Downscale variable array (SST) before contouring, matplotlib is TOO slow on large arrays
    vals = var[variable][:]

    # Fixed color scale, write file, turn off auto borders, set title, reverse lat direction so monotonically increasing??
    imageMap(var[coordinates[1]][:], var[coordinates[0]][:], var[variable][:],
             vmin=-2., vmax=45., outFile=figFile, autoBorders=False,
             title='%s %d-day Mean from %s' % (variable.upper(), n, outFile))
    print >>sys.stderr, 'Writing contour plot to %s' % figFile
    return figFile 
Example #23
Source File: food.py    From tierpsy-tracker with MIT License 5 votes vote down vote up
def _h_smooth_cnt(food_cnt, resampling_N = 1000, smooth_window=None, _is_debug=False):
    if smooth_window is None:
        smooth_window = resampling_N//20
    
    if not _is_valid_cnt(food_cnt):
        #invalid contour arrays
        return food_cnt
        
    smooth_window = smooth_window if smooth_window%2 == 1 else smooth_window+1
    # calculate the cumulative length for each segment in the curve
    dx = np.diff(food_cnt[:, 0])
    dy = np.diff(food_cnt[:, 1])
    dr = np.sqrt(dx * dx + dy * dy)
    lengths = np.cumsum(dr)
    lengths = np.hstack((0, lengths))  # add the first point
    tot_length = lengths[-1]
    fx = interp1d(lengths, food_cnt[:, 0])
    fy = interp1d(lengths, food_cnt[:, 1])
    subLengths = np.linspace(0 + np.finfo(float).eps, tot_length, resampling_N)
    
    rx = fx(subLengths)
    ry = fy(subLengths)
    
    pol_degree = 3
    rx = savgol_filter(rx, smooth_window, pol_degree, mode='wrap')
    ry = savgol_filter(ry, smooth_window, pol_degree, mode='wrap')
    
    food_cnt_s = np.stack((rx, ry), axis=1)
    
    if _is_debug:
        import matplotlib.pylab as plt
        plt.figure()
        plt.plot(food_cnt[:, 0], food_cnt[:, 1], '.-')
        plt.plot(food_cnt_s[:, 0], food_cnt_s[:, 1], '.-')
        plt.axis('equal')
        plt.title('smoothed contour')
    
    return food_cnt_s

#%% 
Example #24
Source File: kernridgeregress_class.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def example2(m=100, scale=0.01, stride=2):
    #m,k = 100,1
    upper = 6
    xs1 = np.linspace(1,upper,m)[:,np.newaxis]
    y1true = np.sum(np.sin(xs1**2),1)[:,np.newaxis]/xs1
    y1 = y1true + 0.05*np.random.randn(m,1)

    ridgecoeff = 1e-10
    #stride = 2 #use only some points as trainig points e.g 2 means every 2nd
    gp1 = GaussProcess(xs1[::stride,:],y1[::stride,:], kernel=kernel_euclid,
                       ridgecoeff=1e-10)
    yhatr1 = gp1.predict(xs1)
    plt.figure()
    plt.plot(y1true, y1,'bo',y1true, yhatr1,'r.')
    plt.title('euclid kernel: true versus noisy (blue) and estimated (red) observations')
    plt.figure()
    plt.plot(y1,'bo-',y1true,'go-',yhatr1,'r.-')
    plt.title('euclid kernel: true (green), noisy (blue) and estimated (red) '+
              'observations')

    gp2 = GaussProcess(xs1[::stride,:],y1[::stride,:], kernel=kernel_rbf,
                       scale=scale, ridgecoeff=1e-2)
    yhatr2 = gp2.predict(xs1)
    plt.figure()
    plt.plot(y1true, y1,'bo',y1true, yhatr2,'r.')
    plt.title('rbf kernel: true versus noisy (blue) and estimated (red) observations')
    plt.figure()
    plt.plot(y1,'bo-',y1true,'go-',yhatr2,'r.-')
    plt.title('rbf kernel: true (green), noisy (blue) and estimated (red) '+
              'observations')
    #gp2.plot(y1) 
Example #25
Source File: plotlib.py    From incubator-sdap-nexus with Apache License 2.0 5 votes vote down vote up
def plotVtecAndJasonTracks(gtcFiles, outFile=None, names=None, makeFigure=True, show=False, **options):
    """Plot GAIM climate and assim VTEC versus JASON using at least two 'gc' files.
    First file is usually climate file, and rest are assim files.
    """
    ensureItems(options, {'title': 'GAIM vs. JASON for '+gtcFiles[0], \
                          'xlabel': 'Geographic Latitude (deg)', 'ylabel': 'VTEC (TECU)'})
    if 'show' in options:
        show = True
        del options['show']
    M.subplot(211)
    gtcFile = gtcFiles.pop(0)
    name = 'clim_'
    if names: name = names.pop(0)
    specs = [(gtcFile, 'latitude:2,jason:6,gim__:8,%s:13,iri__:10' % name)]
    name = 'assim'
    for i, gtcFile in enumerate(gtcFiles):
        label = name
        if len(gtcFiles) > 1: label += str(i+1)
        specs.append( (gtcFile, 'latitude:2,%s:13' % label) )
    plotColumns(specs, rmsDiffFrom='jason', floatFormat='%5.1f', **options)
    M.legend()
    
    M.subplot(212)
    options.update({'title': 'JASON Track Plot', 'xlabel': 'Longitude (deg)', 'ylabel': 'Latitude (deg)'})
    fields = N.array([map(floatOrMiss, line.split()) for line in open(gtcFiles[0], 'r')])
    lons = fields[:,2]; lats = fields[:,1]
    marksOnMap(lons, lats, show=show, **options)
    if outFile: M.savefig(outFile) 
Example #26
Source File: kde_subclass.py    From rmats2sashimiplot with GNU General Public License v2.0 5 votes vote down vote up
def plotkde(covfact):
    gkde.reset_covfact(covfact)
    kdepdf = gkde.evaluate(ind)
    plt.figure()
    # plot histgram of sample
    plt.hist(xn, bins=20, normed=1)
    # plot estimated density
    plt.plot(ind, kdepdf, label='kde', color="g")
    # plot data generating density
    plt.plot(ind, alpha * stats.norm.pdf(ind, loc=mlow) + 
                  (1-alpha) * stats.norm.pdf(ind, loc=mhigh),
                  color="r", label='DGP: normal mix')
    plt.title('Kernel Density Estimation - ' + str(gkde.covfact))
    plt.legend() 
Example #27
Source File: evaluate.py    From text-classifier with Apache License 2.0 5 votes vote down vote up
def plt_history(history, output_dir='output/', model_name='cnn'):
    try:
        from matplotlib import pyplot
        model_name = model_name.upper()
        fig1 = pyplot.figure()
        pyplot.plot(history.history['loss'], 'r', linewidth=3.0)
        pyplot.plot(history.history['val_loss'], 'b', linewidth=3.0)
        pyplot.legend(['Training loss', 'Validation Loss'], fontsize=18)
        pyplot.xlabel('Epochs ', fontsize=16)
        pyplot.ylabel('Loss', fontsize=16)
        pyplot.title('Loss Curves :' + model_name, fontsize=16)
        loss_path = output_dir + model_name + '_loss.png'
        fig1.savefig(loss_path)
        print('save to:', loss_path)
        # pyplot.show()

        fig2 = pyplot.figure()
        pyplot.plot(history.history['acc'], 'r', linewidth=3.0)
        pyplot.plot(history.history['val_acc'], 'b', linewidth=3.0)
        pyplot.legend(['Training Accuracy', 'Validation Accuracy'], fontsize=18)
        pyplot.xlabel('Epochs ', fontsize=16)
        pyplot.ylabel('Accuracy', fontsize=16)
        pyplot.title('Accuracy Curves : ' + model_name, fontsize=16)
        acc_path = output_dir + model_name + '_accuracy.png'
        fig2.savefig(acc_path)
        print('save to:', acc_path)
    except Exception as e:
        print("save image error with matplotlib")
        pass 
Example #28
Source File: plot_roc.py    From speaker_recognition with Apache License 2.0 5 votes vote down vote up
def plot_roc(score_list, save_dir, plot_name):

    save_path = os.path.join(save_dir, plot_name + ".jpg")
    # 按照 score 排序
    threshold_value = sorted([score for score, _ in score_list])

    threshold_num = len(threshold_value)
    accracy_array = np.zeros(threshold_num)
    precision_array = np.zeros(threshold_num)
    TPR_array = np.zeros(threshold_num)
    TNR_array = np.zeros(threshold_num)
    FNR_array = np.zeros(threshold_num)
    FPR_array = np.zeros(threshold_num)

    # calculate all the rates
    for thres in range(threshold_num):
        accracy, precision, TPR, TNR, FNR, FPR = cal_rate(score_list, threshold_value[thres])
        accracy_array[thres] = accracy
        precision_array[thres] = precision
        TPR_array[thres] = TPR
        TNR_array[thres] = TNR
        FNR_array[thres] = FNR
        FPR_array[thres] = FPR

    AUC = np.trapz(TPR_array, FPR_array)
    threshold = np.argmin(abs(FNR_array - FPR_array))
    EER = (FNR_array[threshold] + FPR_array[threshold]) / 2
    # print('EER : %f AUC : %f' % (EER, -AUC))
    plt.plot(FPR_array, TPR_array)

    plt.title('ROC')
    plt.xlabel('FPR')
    plt.ylabel('TPR')
    plt.text(0.2, 0, s="EER :{} AUC :{} Threshold:{}".format(round(EER, 4), round(-AUC, 4),
                                                             round(threshold_value[threshold], 4)), fontsize=10)
    plt.legend()
    plt.savefig(save_path)
    plt.show() 
Example #29
Source File: PybacktestChef.py    From OpenTrader with GNU Lesser General Public License v3.0 5 votes vote down vote up
def vPlotTrades(self, subset=None):
        if subset is None:
            subset = slice(None, None)
        fr = self.trades.ix[subset]
        le = fr.price[(fr.pos > 0) & (fr.vol > 0)]
        se = fr.price[(fr.pos < 0) & (fr.vol < 0)]
        lx = fr.price[(fr.pos.shift() > 0) & (fr.vol < 0)]
        sx = fr.price[(fr.pos.shift() < 0) & (fr.vol > 0)]

        import matplotlib.pylab as pylab

        pylab.plot(le.index, le.values, '^', color='lime', markersize=12,
                   label='long enter')
        pylab.plot(se.index, se.values, 'v', color='red', markersize=12,
                   label='short enter')
        pylab.plot(lx.index, lx.values, 'o', color='lime', markersize=7,
                   label='long exit')
        pylab.plot(sx.index, sx.values, 'o', color='red', markersize=7,
                   label='short exit')
        eq = self.equity.ix[subset].cumsum()
        ix = eq.index
        oOS = getattr(self.ohlc, self.open_label)
        (eq + oOS[ix[0]]).plot(color='red', style='-', label='strategy')
        # self.ohlc.O.ix[ix[0]:ix[-1]].plot(color='black', label='price')
        oOS.ix[subset].plot(color='black', label='price')
        pylab.legend(loc='best')
        pylab.title('%s\nTrades for %s' % (self, subset)) 
Example #30
Source File: utils.py    From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License 5 votes vote down vote up
def plot_k_complexity(ks, train_errors, test_errors):
    pylab.figure(num=None, figsize=(6, 5))
    pylab.ylim([0.0, 1.0])
    pylab.xlabel('k')
    pylab.ylabel('Error')
    pylab.title('Errors for for different values of $k$')
    pylab.plot(
        ks, test_errors, "--", ks, train_errors, "-", lw=1)
    pylab.legend(["test error", "train error"], loc="upper right")
    pylab.grid(True, linestyle='-', color='0.75')
    pylab.savefig(
        os.path.join(CHART_DIR, "kcomplexity.png"), bbox_inches="tight")