xgboost 2分类(sex predict)

1. xgboost 参数介绍

sklearn 中的xgboost 的 XGBClassifer 参数一样。

1.1 常规参数

1.1.1 booster

1.  gbtree  使用树模型作为基分类器(default)
2.  gbliner  使用线性模型作为基分类器

1.1.2 silent

1.  0  安静模式,不输出中间过程(default)
2.  1  输出中间过程

1.1.3 nthread

  1. -1 使用全部cpu进行并行运算(default)
  2. 1 使用1个cpu运算

1.1.4 scale_pos_weight

正样本的权重,默认取1。在二分类任务中,当正负样本比例失衡时,设置正样本的权重,模型效果更好(如正样本:负样本=1:10,则scale_pos_weight=10)。

1.2 模型参数

1.2.1 n_estimatores

总迭代次数,也就是拟合几次残差(即决策树个数)。

1.2.2 early_stopping_rounds

在验证集上连续n次迭代,分类没有提高后,提前终止训练,防止过拟合(一般取10)。

1.2.3 max_depth

树的最大深度,默认为6,典型值3-10。值越大,越容易过拟合;值越小,越容易欠拟合。

1.2.4 min_child_weight

表示子树观测权重之和的最小值,如果树的生长时的某一步所生成的叶子结点,其观测权重之和小于min_child_weight,那么可以放弃该步生长,在线性回归模式中,这仅仅与每个结点所需的最小观测数相对应。该值越大,算法越保守。
默认取1,值越大,越容易欠拟合;值越小,越容易过拟合。值较大时,可避免模型学习到局部的特殊样本。

1.2.5 subsample

训练每棵树时,使用的数据占全部训练集的比例,默认取1,一般取0.8,可防止过拟合。

1.2.6 colsample_bytree

训练每棵树时,使用的feature占全部特征的比例,默认取1,一般取0.8,可防止过拟合。

1.3 学习任务参数

1.3.1 learning_rate

学习率,控制每次迭代更新权重时的步长,默认取0.3,一般0.01-0.2,值越小,训练越慢。

1.3.2 objective

目标函数

  1. 回归任务
    reg:linear (default)
    reg:logistic
  2. 二分类
    binary:logistic 概率
    binary:logitraw 类别
  3. 多分类
    multi:softmax num_calss=n 返回类别
    multi:softprob num_calss=n 返回概率
  4. rank:pairwise

1.3.3 eval_metric

  1. 回归任务
    rmse 均方根误差(default)
    mae 平方绝对误差
  2. 分类任务
    auc roc曲线下面积
    error 错误率(二分类,default)
    merror 错误率(多分类)
    logloss 负对数似然函数(二分类)
    mlogloss 负对数似然函数(多分类)

1.3.4 gamma

惩罚项系数,一般取0.1-0.2,指定结点分裂所需的最小损失函数下降值。

1.3.5 alpha

L1 正则化系数,默认取1 。

1.3.6 lambda

L2 正则化系数,默认取1 。

1.4 主要函数

  1. 载入数据:load_digits()
  2. 数据分割:train_test_split()
  3. 建立模型:XGBClassifier()
  4. 模型训练:fit()
  5. 模型预测:predict()
  6. 性能度量:accuracy_score()
  7. 特征重要度:plot_importance()

2. 二分类模型训练

# -*- coding: utf-8 -*-
import numpy as np
import xgboost as xgb
from xgboost import plot_importance
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn import preprocessing
# from matplotlib import pyplot as plt

# 1.load data
// data = np.loadtxt('out.txt', delimiter=',')
data = pd.read_csv('out.txt', sep='\t')
data.drop(["uid","random","7d_retention","life_cycle"], axis=1, inplace=True)
data.fillna(0, inplace=True)
data.round(decimals=2)

data_num, feature_num = data.shape
print("data_num:   ", data_num)
print("feature_num:   ", feature_num)
# 2.shuffle data
rng = np.random.RandomState(830041)
index = list(range(data_num))
rng.shuffle(index)
data = data[index]
# 3.split data
X, Y = data[:, 0:feature_num-1], data[:, feature_num-1]
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, random_state=0)

xg_train = xgb.DMatrix(X_train, label=y_train)
xg_test = xgb.DMatrix(X_test, label=y_test)

params = {
    'booster': 'gbtree',
    'objective': 'binary:logistic',
    'eval_metric': 'auc',
    'max_depth': 10,
    'lambda': 10,
    'subsample': 0.85,
    'colsample_bytree': 0.85,
    'min_child_weight': 2,
    # 'eta': 0.025,
    'eta': 0.1,
    'seed': 0,
    'nthread': 8,
    'silent': 1
}

watchlist = [(xg_train, 'train'), (xg_test, 'test')]
num_round = 50
bst = xgb.train(params, xg_train, num_round, watchlist)
# xgb = xgb.XGBClassifier(n_estimators=20, max_depth=4,
#    learning_rate=0.1, subsample=0.7, colsample_bytree=0.7)
# xgb.fit(train_X, train_y, early_stopping_rounds=10, eval_metric="auc",
#        eval_set=[(test_X, test_y)])
bst.save_model('test.model')
pred = bst.predict(xg_test)
print('predicting, classification error=%f'
       % (sum(int(pred[i]) != y_test[i] for i in range(len(y_test))) / float(len(y_test))))
# print('错误类为%f' %((pred!=y_test).sum()/float(y_test.shape[0])))

y_pred = (pred >= 0.5) * 1
print('AUC: %.4f' % metrics.roc_auc_score(y_test, pred))
print('ACC: %.4f' % metrics.accuracy_score(y_test, y_pred))
print('Recall: %.4f' % metrics.recall_score(y_test, y_pred))
print('F1-score: %.4f' % metrics.f1_score(y_test, y_pred))
print('Precesion: %.4f' % metrics.precision_score(y_test, y_pred))
print(metrics.confusion_matrix(y_test, y_pred))

# plot_importance(bst)
# plt.show()

# 打印特征重要度
importance = bst.get_score(importance_type='gain')
sorted_importance = sorted(importance.items(), key=lambda x: x[1], reverse=True)
print('feature importances[gain]: ', sorted_importance)
# 或
# temp = pd.DataFrame()
# temp['feature_importances'] = xgb_model.feature_importances_
# temp = temp.sort_values('feature_importances', ascending=False)
# temp.set_index('feature_names').plot.bar(figsize=(16,8),rot=0)

3. 统计oe与auc

sample_rate = 0.6
pos = 100  # 正样本数
count = 200 # 总样本数
dtest = xgb.DMatrix('test_data.txt')
bst = xgb.Booster(model_file="test.model")
test_preds = bst.predict(dtest)
preds = 0.0
predList = []
for pred in test_preds:
    pred = pred*sample_rate/(1-pred*(1-sample_rate))
    preds += pred
    predList.append(pred)
oe = pos/preds
auc = roc_auc_score(labelList, predList)
with open("out.txt",'w') as f:
    f.write("count=%d,\tauc=%f,\toe=%f\n"%(count,auc,oe))
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值