python类ylabel()的实例源码

xgb_param_fit2.py 文件源码 项目:model_sweeper 作者: akimovmike 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def modelfit(alg, predictors, target, useTrainCV=True, cv_folds=5, early_stopping_rounds=50):

    if useTrainCV:
        xgb_param = alg.get_xgb_params()
        xgtrain = xgb.DMatrix(predictors.values, label=target.values)
        cvresult = xgb.cv(xgb_param, xgtrain, num_boost_round=alg.get_params()['n_estimators'], nfold=cv_folds,\
            metrics=['auc'], early_stopping_rounds=early_stopping_rounds, show_progress=False)
        alg.set_params(n_estimators=cvresult.shape[0])

    #Fit the algorithm on the data
    alg.fit(predictors, target, eval_metric='auc')

    #Predict training set:
    dtrain_predictions = alg.predict(predictors)
    dtrain_predprob = alg.predict_proba(predictors)[:, 1]

    #Print model report:
    print("\nModel Report")
    print("Accuracy : %.4g" % metrics.accuracy_score(target.values, dtrain_predictions))
    print("AUC Score (Train): %f" % metrics.roc_auc_score(target, dtrain_predprob))

    feat_imp = pd.Series(alg.booster().get_fscore()).sort_values(ascending=False)
    feat_imp.plot(kind='bar', title='Feature Importances')
    plt.ylabel('Feature Importance Score')

# examples of usage
# 1
hack_dev.py 文件源码 项目:ml-projects 作者: saopayne 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def hackathon_GBC_model(clf, train, features):
    clf.fit(train[features], train["Class"])
    probab_of_predict = clf.predict_proba(train[features])[:,1]
    predict_train = clf.predict(train[features])
    cv_score = cross_val_score(clf, train[features], train["Class"], cv=5, scoring="roc_auc")
    print("----------------------Model performance-----------------------")
    print("Accuracy score: ", accuracy_score(train["Class"].values, predict_train))
    print("AUC: ", roc_auc_score(train["Class"],probab_of_predict) )
    print("CV score: Mean - {}, Max - {}, Min - {}, Std - {}".format(np.mean(cv_score), np.max(cv_score),
                                                                     np.min(cv_score), np.std(cv_score)))

    Relative_Feature_importance = pd.Series(clf.feature_importances_, features).sort_values(ascending=False)
    Relative_Feature_importance.plot(kind='bar', title='Order of Feature Importance')
    plt.ylabel('Feature Importance')
    plt.show()
plots.py 文件源码 项目:nmmn 作者: rsnemmen 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def onehist(x,xlabel='',fontsize=12):
    """ 
Script that plots the histogram of x with the corresponding xlabel. 
    """

    pylab.clf()
    pylab.rcParams.update({'font.size': fontsize})
    pylab.hist(x,histtype='stepfilled')
    pylab.legend()
    #### Change the X-axis appropriately ####
    pylab.xlabel(xlabel)
    pylab.ylabel('Number')
    pylab.draw()
    pylab.show()
Top_Trending.py 文件源码 项目:Trending-Places-in-OpenStreetMap 作者: geometalab 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def plot_graphs(df, trending_daily, day_from, day_to, limit, country_code, folder_out=None):
    days = pd.DatetimeIndex(start=day_from, end=day_to, freq='D')
    for day in days:
        fig = plt.figure()
        ax = fig.add_subplot(111)
        plt.rc('lines', linewidth=2)
        data = trending_daily.get_group(str(day.date()))
        places, clusters = top_trending(data, limit)
        for cluster in clusters:
            places.add(max_from_cluster(cluster, data))
        ax.set_prop_cycle(plt.cycler('color', ['r', 'b', 'yellow'] + [plt.cm.Accent(i) for i in np.linspace(0, 1, limit-3)]
                                     ) + plt.cycler('linestyle', ['-', '-', '-', '-', '-', '--', '--', '--', '--', '--']))
        frame = export(places, clusters, data)
        frame.sort_values('trending_rank', ascending=False, inplace=True)
        for i in range(len(frame)):
            item = frame.index[i]
            lat, lon, country = item
            result_items = ReverseGeoCode().get_address_attributes(lat, lon, 10, 'city', 'country_code')
            if 'city' not in result_items.keys():
                mark = "%s (%s)" % (manipulate_display_name(result_items['display_name']),
                                    result_items['country_code'].upper() if 'country_code' in result_items.keys() else country)
            else:
                if check_eng(result_items['city']):
                    mark = "%s (%s)" % (result_items['city'], result_items['country_code'].upper())
                else:
                    mark = "%.2f %.2f (%s)" % (lat, lon, result_items['country_code'].upper())
            gp = df.loc[item].plot(ax=ax, x='date', y='count', label=mark)
        ax.tick_params(axis='both', which='major', labelsize=10)
        ax.set_yscale("log", nonposy='clip')
        plt.xlabel('Date', fontsize='small', verticalalignment='baseline', horizontalalignment='right')
        plt.ylabel('Total number of views (log)', fontsize='small', verticalalignment='center', horizontalalignment='center', labelpad=6)
        gp.legend(loc='best', fontsize='xx-small', ncol=2)
        gp.set_title('Top 10 OSM trending places on ' + str(day.date()), {'fontsize': 'large', 'verticalalignment': 'bottom'})
        plt.tight_layout()
        db = TrendingDb()
        db.update_table_img(plt, str(day.date()), region=country_code)
        plt.close()
wordfreq_app.py 文件源码 项目:Price-Comparator 作者: Thejas-1 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def plot_word_freq_dist(text):
    fd = text.vocab()

    samples = [item for item, _ in fd.most_common(50)]
    values = [fd[sample] for sample in samples]
    values = [sum(values[:i+1]) * 100.0/fd.N() for i in range(len(values))]
    pylab.title(text.name)
    pylab.xlabel("Samples")
    pylab.ylabel("Cumulative Percentage")
    pylab.plot(values)
    pylab.xticks(range(len(samples)), [str(s) for s in samples], rotation=90)
    pylab.show()
texttiling.py 文件源码 项目:Price-Comparator 作者: Thejas-1 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def demo(text=None):
    from nltk.corpus import brown
    from matplotlib import pylab
    tt = TextTilingTokenizer(demo_mode=True)
    if text is None: text = brown.raw()[:10000]
    s, ss, d, b = tt.tokenize(text)
    pylab.xlabel("Sentence Gap index")
    pylab.ylabel("Gap Scores")
    pylab.plot(range(len(s)), s, label="Gap Scores")
    pylab.plot(range(len(ss)), ss, label="Smoothed Gap scores")
    pylab.plot(range(len(d)), d, label="Depth scores")
    pylab.stem(range(len(b)), b)
    pylab.legend()
    pylab.show()
test_msckf.py 文件源码 项目:prototype 作者: chutsu 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def plot_position(self, pos_true, pos_est, cam_states):
        N = pos_est.shape[1]
        pos_true = pos_true[:, :N]
        pos_est = pos_est[:, :N]

        # Figure
        plt.figure()
        plt.suptitle("Position")

        # Ground truth
        plt.plot(pos_true[0, :], pos_true[1, :],
                 color="red", label="Grouth truth")
                 # color="red", marker="x", label="Grouth truth")

        # Estimated
        plt.plot(pos_est[0, :], pos_est[1, :],
                 color="blue", label="Estimated")
                 # color="blue", marker="o", label="Estimated")

        # Sliding window
        cam_pos = []
        for cam_state in cam_states:
            cam_pos.append(cam_state.p_G)
        cam_pos = np.array(cam_pos).reshape((len(cam_pos), 3)).T
        plt.plot(cam_pos[0, :], cam_pos[1, :],
                 color="green", label="Camera Poses")
                 # color="green", marker="o", label="Camera Poses")

        # Plot labels and legends
        plt.xlabel("East (m)")
        plt.ylabel("North (m)")
        plt.axis("equal")
        plt.legend(loc=0)
test_msckf.py 文件源码 项目:prototype 作者: chutsu 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def plot_velocity(self, timestamps, vel_true, vel_est):
        N = vel_est.shape[1]
        t = timestamps[:N]
        vel_true = vel_true[:, :N]
        vel_est = vel_est[:, :N]

        # Figure
        plt.figure()
        plt.suptitle("Velocity")

        # X axis
        plt.subplot(311)
        plt.plot(t, vel_true[0, :], color="red", label="Ground_truth")
        plt.plot(t, vel_est[0, :], color="blue", label="Estimate")

        plt.title("x-axis")
        plt.xlabel("Date Time")
        plt.ylabel("ms^-1")
        plt.legend(loc=0)

        # Y axis
        plt.subplot(312)
        plt.plot(t, vel_true[1, :], color="red", label="Ground_truth")
        plt.plot(t, vel_est[1, :], color="blue", label="Estimate")

        plt.title("y-axis")
        plt.xlabel("Date Time")
        plt.ylabel("ms^-1")
        plt.legend(loc=0)

        # Z axis
        plt.subplot(313)
        plt.plot(t, vel_true[2, :], color="red", label="Ground_truth")
        plt.plot(t, vel_est[2, :], color="blue", label="Estimate")

        plt.title("z-axis")
        plt.xlabel("Date Time")
        plt.ylabel("ms^-1")
        plt.legend(loc=0)
test_msckf.py 文件源码 项目:prototype 作者: chutsu 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def plot_attitude(self, timestamps, att_true, att_est):
        # Setup
        N = att_est.shape[1]
        t = timestamps[:N]
        att_true = att_true[:, :N]
        att_est = att_est[:, :N]

        # Figure
        plt.figure()
        plt.suptitle("Attitude")

        # X axis
        plt.subplot(311)
        plt.plot(t, att_true[0, :], color="red", label="Ground_truth")
        plt.plot(t, att_est[0, :], color="blue", label="Estimate")

        plt.title("x-axis")
        plt.legend(loc=0)
        plt.xlabel("Date Time")
        plt.ylabel("rad s^-1")

        # Y axis
        plt.subplot(312)
        plt.plot(t, att_true[1, :], color="red", label="Ground_truth")
        plt.plot(t, att_est[1, :], color="blue", label="Estimate")

        plt.title("y-axis")
        plt.legend(loc=0)
        plt.xlabel("Date Time")
        plt.ylabel("rad s^-1")

        # Z axis
        plt.subplot(313)
        plt.plot(t, att_true[2, :], color="red", label="Ground_truth")
        plt.plot(t, att_est[2, :], color="blue", label="Estimate")

        plt.title("z-axis")
        plt.legend(loc=0)
        plt.xlabel("Date Time")
        plt.ylabel("rad s^-1")
test_imu_state.py 文件源码 项目:prototype 作者: chutsu 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def plot_velocity(self, timestamps, vel_true, vel_est):
        N = vel_est.shape[1]
        t = timestamps[:N]
        vel_true = vel_true[:, :N]
        vel_est = vel_est[:, :N]

        # Figure
        plt.figure()
        plt.suptitle("Velocity")

        # X axis
        plt.subplot(311)
        plt.plot(t, vel_true[0, :], color="red", label="Ground_truth")
        plt.plot(t, vel_est[0, :], color="blue", label="Estimate")

        plt.title("x-axis")
        plt.xlabel("Date Time")
        plt.ylabel("ms^-1")
        plt.legend(loc=0)

        # Y axis
        plt.subplot(312)
        plt.plot(t, vel_true[1, :], color="red", label="Ground_truth")
        plt.plot(t, vel_est[1, :], color="blue", label="Estimate")

        plt.title("y-axis")
        plt.xlabel("Date Time")
        plt.ylabel("ms^-1")
        plt.legend(loc=0)

        # Z axis
        plt.subplot(313)
        plt.plot(t, vel_true[2, :], color="red", label="Ground_truth")
        plt.plot(t, vel_est[2, :], color="blue", label="Estimate")

        plt.title("z-axis")
        plt.xlabel("Date Time")
        plt.ylabel("ms^-1")
        plt.legend(loc=0)
test_features.py 文件源码 项目:prototype 作者: chutsu 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def plot_storage(self, storage):
        plt.figure()
        plt.plot(range(len(storage)), storage)
        plt.title("Num of tracks over time")
        plt.xlabel("Frame No.")
        plt.ylabel("Num of Tracks")
test_features.py 文件源码 项目:prototype 作者: chutsu 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def plot_tracked(self, tracked):
        plt.figure()
        plt.plot(range(len(tracked)), tracked)
        plt.title("Matches per Frame")
        plt.xlabel("Frame No.")
        plt.ylabel("Num of Tracks")
earth_model.py 文件源码 项目:seis_tools 作者: romaguir 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def plot_1d_model(self):
      plt.subplot(131)
      plt.plot(self.rho_bg,self.radius)
      plt.xlabel('density (kg/m3)')
      plt.ylabel('radius (km)')
      plt.subplot(132)
      plt.plot(self.vp_bg,self.radius)
      plt.xlabel('Vp (km/s)')
      plt.ylabel('radius (km)')
      plt.subplot(133)
      plt.plot(self.vs_bg,self.radius)
      plt.xlabel('Vs (km/s)')
      plt.ylabel('radius (km)')
      plt.show()
Q_models.py 文件源码 项目:seis_tools 作者: romaguir 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def plot_q(model='cem', r_min=0.0, r_max=6371.0, dr=1.0):

    """
    Plot a radiallysymmetric Q model.

    plot_q(model='cem', r_min=0.0, r_max=6371.0, dr=1.0):

    r_min=minimum radius [km], r_max=maximum radius [km], dr=radius increment [km]

    Currently available models (model): cem, prem, ql6
    """

    r = np.arange(r_min, r_max+dr, dr)
    q = np.zeros(len(r))

    for k in range(len(r)):

        if model=='cem':
            q[k]=q_cem(r[k])
        elif model=='ql6':
            q[k]=q_ql6(r[k])
        elif model=='prem':
            q[k]=q_prem(r[k])


    plt.plot(r,q,'k')
    plt.xlim((0.0,r_max))
    plt.xlabel('radius [km]')
    plt.ylabel('Q')
    plt.show()


###################################################################################################
#- CEM, EUMOD
###################################################################################################
pymod_sup.py 文件源码 项目:pymod 作者: pymodproject 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def ylabel(s, *args, **kwargs):
        print "Warning! Failed to import matplotlib so no axes will be labeled"
demo_mi.py 文件源码 项目:Building-Machine-Learning-Systems-With-Python-Second-Edition 作者: PacktPublishing 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _plot_mi_func(x, y):

    mi = mutual_info(x, y)
    title = "NI($X_1$, $X_2$) = %.3f" % mi
    pylab.scatter(x, y)
    pylab.title(title)
    pylab.xlabel("$X_1$")
    pylab.ylabel("$X_2$")
demo_corr.py 文件源码 项目:Building-Machine-Learning-Systems-With-Python-Second-Edition 作者: PacktPublishing 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def _plot_correlation_func(x, y):

    r, p = pearsonr(x, y)
    title = "Cor($X_1$, $X_2$) = %.3f" % r
    pylab.scatter(x, y)
    pylab.title(title)
    pylab.xlabel("$X_1$")
    pylab.ylabel("$X_2$")

    f1 = scipy.poly1d(scipy.polyfit(x, y, 1))
    pylab.plot(x, f1(x), "r--", linewidth=2)
    # 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]])
utils.py 文件源码 项目:Building-Machine-Learning-Systems-With-Python-Second-Edition 作者: PacktPublishing 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def plot_pr(auc_score, name, phase, precision, recall, label=None):
    pylab.clf()
    pylab.figure(num=None, figsize=(5, 4))
    pylab.grid(True)
    pylab.fill_between(recall, precision, alpha=0.5)
    pylab.plot(recall, precision, lw=1)
    pylab.xlim([0.0, 1.0])
    pylab.ylim([0.0, 1.0])
    pylab.xlabel('Recall')
    pylab.ylabel('Precision')
    pylab.title('P/R curve (AUC=%0.2f) / %s' % (auc_score, label))
    filename = name.replace(" ", "_")
    pylab.savefig(os.path.join(CHART_DIR, "pr_%s_%s.png" %
                  (filename, phase)), bbox_inches="tight")
utils.py 文件源码 项目:Building-Machine-Learning-Systems-With-Python-Second-Edition 作者: PacktPublishing 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def plot_log():
    pylab.clf()
    pylab.figure(num=None, figsize=(6, 5))

    x = np.arange(0.001, 1, 0.001)
    y = np.log(x)

    pylab.title('Relationship between probabilities and their logarithm')
    pylab.plot(x, y)
    pylab.grid(True)
    pylab.xlabel('P')
    pylab.ylabel('log(P)')
    filename = 'log_probs.png'
    pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")
utils.py 文件源码 项目:Building-Machine-Learning-Systems-With-Python-Second-Edition 作者: PacktPublishing 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def plot_feat_hist(data_name_list, filename=None):
    pylab.clf()
    num_rows = 1 + (len(data_name_list) - 1) / 2
    num_cols = 1 if len(data_name_list) == 1 else 2
    pylab.figure(figsize=(5 * num_cols, 4 * num_rows))

    for i in range(num_rows):
        for j in range(num_cols):
            pylab.subplot(num_rows, num_cols, 1 + i * num_cols + j)
            x, name = data_name_list[i * num_cols + j]
            pylab.title(name)
            pylab.xlabel('Value')
            pylab.ylabel('Density')
            # the histogram of the data
            max_val = np.max(x)
            if max_val <= 1.0:
                bins = 50
            elif max_val > 50:
                bins = 50
            else:
                bins = max_val
            n, bins, patches = pylab.hist(
                x, bins=bins, normed=1, facecolor='green', alpha=0.75)

            pylab.grid(True)

    if not filename:
        filename = "feat_hist_%s.png" % name

    pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")


问题


面经


文章

微信
公众号

扫码关注公众号