XGBoost调参demo(Python)

本文通过一个保险公司的数据集演示了XGBoost模型的调参过程,包括数据预处理、建立基础模型,以及逐步调整学习率、树的深度与节点权重、gamma、subsample和colsample_bytree等参数,通过交叉验证优化模型性能,最终降低平均绝对误差,提升预测效果。
摘要由CSDN通过智能技术生成

XGBoost

我们用的是保险公司的一份数据

# 各种库
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score as AUC
from sklearn.metrics import mean_absolute_error
from sklearn.decompositi on import PCA
from sklearn.preprocessing import LabelEncoder, LabelBinarizer
from sklearn.cross_validation import cross_val_score

from scipy import stats
import seaborn as sns
from copy import deepcopy

%matplotlib inline

# 早期版本的Jupyter可能引发异常
%config InlineBackend.figure_format = 'retina'

数据预处理

我们用的是保险公司的一份数据

train = pd.read_csv('train.csv')

做对数转换

train['log_loss'] = np.log(train['loss'])

数据分成连续和离散特征

features = [x for x in train.columns if x not in ['id','loss', 'log_loss']]

cat_features = [x for x in train.select_dtypes(
        include=['object']).columns if x not in ['id','loss', 'log_loss']]
num_features = [x for x in train.select_dtypes(
        exclude=['object']).columns if x not in ['id','loss', 'log_loss']]

print ("Categorical features:", len(cat_features))
print ("Numerical features:", len(num_features))

Categorical features: 116
Numerical features: 14

ntrain = train.shape[0]

train_x = train[features]
train_y = train['log_loss']

for c in range(len(cat_features)):
    train_x[cat_features[c]] = train_x[cat_features[c]].astype('category').cat.codes

print ("Xtrain:", train_x.shape)
print ("ytrain:", train_y.shape)

Xtrain: (188318, 130)
ytrain: (188318,)

Simple XGBoost Model

首先,我们训练一个基本的xgboost模型,然后进行参数调节通过交叉验证来观察结果的变换,使用平均绝对误差来衡量
mean_absolute_error(np.exp(y), np.exp(yhat))。
xgboost 自定义了一个数据矩阵类 DMatrix,会在训练开始时进行一遍预处理,从而提高之后每次迭代的效率

def xg_eval_mae(yhat, dtrain):
    y = dtrain.get_label()
    return 'mae', mean_absolute_error(np.exp(y), np.exp(yhat))

Model

dtrain = xgb.DMatrix(train_x, train['log_loss'])

Xgboost参数

  • ‘booster’:’gbtree’,
  • ‘objective’: ‘multi:softmax’, 多分类的问题
  • ‘num_class’:10, 类别数,与 multisoftmax 并用
  • ‘gamma’:0.1, 用于控制是否后剪枝的参数,越大越保守,一般0.1、0.2这样子。
  • ‘max_depth’:12, 构建树的深度,越大越容易过拟合
  • ‘lambda’:2, 控制模型复杂度的权重值的L2正则化项参数,参数越大,模型越不容易过拟合。
  • ‘subsample’:0.7, 随机采样训练样本
  • ‘colsample_bytree’:0.7, 生成树时进行的列采样
  • ‘min_child_weight’:3, 这个参数默认是 1,是每个叶子里面 h 的和至少是多少,对正负样本不均衡时的 0-1 分类而言,假设 h 在 0.01 附近,min_child_weight 为 1 意味着叶子节点中最少需要包含 100 个样本。这个参数非常影响结果,控制叶子节点中二阶导的和的最小值,该参数值越小,越容易 overfitting。
  • ‘silent’:0 ,设置成1则没有运行信息输出,最好是设置为0.
  • ‘eta’: 0.007, 如同学习率
  • ‘seed’:1000,
  • ‘nthread’:7, cpu 线程数
xgb_params = {
    'seed': 0,
    'eta': 0.1,
    'colsample_bytree': 0.5,
    'silent': 1,
    'subsample': 0.5,
    'o
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值