• Python数据分析与机器学习39-Xgboost算法实例


    一. xgboost.XGBClassifier 分类算法 参数详解

    语法:

    class xgboost.XGBClassifier(max_depth=3, learning_rate=0.1, n_estimators=100, silent=True, objective='binary:logistic', booster='gbtree', n_jobs=1, nthread=None, gamma=0, min_child_weight=1, max_delta_step=0, subsample=1, colsample_bytree=1, colsample_bylevel=1, reg_alpha=0, reg_lambda=1, scale_pos_weight=1, base_score=0.5, random_state=0, seed=None, missing=None, **kwargs)
    
    • 1
    • booster
    1. gbtree 树模型做为基分类器(默认)
    2. gbliner 线性模型做为基分类器
    • n_jobs 并行线程数
    1. silent
      silent=0时,不输出中间过程(默认)
      silent=1时,输出中间过程
    2. nthread
      nthread=-1时,使用全部CPU进行并行运算(默认)
      nthread=1时,使用1个CPU进行运算。
    • scale_pos_weight
      正样本的权重,在二分类任务中,当正负样本比例失衡时,设置正样本的权重,模型效果更好。例如,当正负样本比例为1:10时,scale_pos_weight=10。

    • n_estimatores
      含义:总共迭代的次数,即决策树的个数
      调参:

    • max_depth
      含义:树的深度,默认值为6,典型值3-10。
      调参:值越大,越容易过拟合;值越小,越容易欠拟合。

    • min_child_weight
      含义:默认值为1,。
      调参:值越大,越容易欠拟合;值越小,越容易过拟合(值较大时,避免模型学习到局部的特殊样本)。

    • subsample
      含义:训练每棵树时,使用的数据占全部训练集的比例。默认值为1,典型值为0.5-1。
      调参:防止overfitting。

    • colsample_bytree
      含义:训练每棵树时,使用的特征占全部特征的比例。默认值为1,典型值为0.5-1。
      调参:防止overfitting。

    • learning_rate
      含义:学习率,控制每次迭代更新权重时的步长,默认0.3。
      调参:值越小,训练越慢。
      典型值为0.01-0.2。

    • gamma
      惩罚项系数,指定节点分裂所需的最小损失函数下降值。
      调参:

    • alpha
      L1正则化系数,默认为1

    • lambda
      L2正则化系数,默认为1

    二. 数据集介绍

    pima-indians-diabetes.csv
    印度的一个数据集,前面是各个类别的值,最后一列是标签值,1代表糖尿病,0代表正常。
    image.png

    三. 实战代码

    3.1 一个简单的Xgboost实例

    代码:

    from numpy import loadtxt
    from xgboost import XGBClassifier
    from sklearn.model_selection import train_test_split
    from sklearn.metrics import accuracy_score
    
    # 加载数据集
    dataset = loadtxt('E:/file/pima-indians-diabetes.csv', delimiter=",")
    # 将数据分为 数据和标签
    X = dataset[:,0:8]
    Y = dataset[:,8]
    # 划分测试集和训练集
    seed = 7 # 随机因子,能保证多次的随机数据一致
    test_size = 0.33
    X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=test_size, random_state=seed)
    
    # 训练模型
    model = XGBClassifier()
    model.fit(X_train, y_train)
    # 对模型做预测
    y_pred = model.predict(X_test)
    predictions = [round(value) for value in y_pred]
    # 评估预测
    accuracy = accuracy_score(y_test, predictions)
    print("Accuracy: %.2f%%" % (accuracy * 100.0))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    测试记录:
    Accuracy: 74.02%

    3.2 查看特征的重要性

    代码:

    from numpy import loadtxt
    from xgboost import XGBClassifier
    from xgboost import plot_importance
    from matplotlib import pyplot as plt
    
    # 加载数据集
    dataset = loadtxt('E:/file/pima-indians-diabetes.csv', delimiter=",")
    # 将数据分为 数据和标签
    X = dataset[:,0:8]
    Y = dataset[:,8]
    
    # 训练模型
    model = XGBClassifier()
    model.fit(X, Y)
    
    # 画图,画出特征的重要性
    plot_importance(model)
    plt.show()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    测试记录:
    image.png

    3.3 对模型进行调参

    代码:

    from numpy import loadtxt
    from xgboost import XGBClassifier
    from sklearn.model_selection import train_test_split
    from sklearn.metrics import accuracy_score
    
    # 加载数据集
    dataset = loadtxt('E:/file/pima-indians-diabetes.csv', delimiter=",")
    # 将数据分为 数据和标签
    X = dataset[:,0:8]
    Y = dataset[:,8]
    # 划分测试集和训练集
    seed = 7 # 随机因子,能保证多次的随机数据一致
    test_size = 0.33
    X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=test_size, random_state=seed)
    
    # 训练模型
    model = XGBClassifier()
    eval_set = [(X_test, y_test)]
    model.fit(X_train, y_train, early_stopping_rounds=10, eval_metric="logloss", eval_set=eval_set, verbose=True)
    # 对模型做预测
    y_pred = model.predict(X_test)
    predictions = [round(value) for value in y_pred]
    # 评估预测
    accuracy = accuracy_score(y_test, predictions)
    print("Accuracy: %.2f%%" % (accuracy * 100.0))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    测试记录:

    [0]	validation_0-logloss:0.60491
    [1]	validation_0-logloss:0.55934
    [2]	validation_0-logloss:0.53068
    [3]	validation_0-logloss:0.51795
    [4]	validation_0-logloss:0.51153
    [5]	validation_0-logloss:0.50934
    [6]	validation_0-logloss:0.50818
    [7]	validation_0-logloss:0.51097
    [8]	validation_0-logloss:0.51760
    [9]	validation_0-logloss:0.51912
    [10]	validation_0-logloss:0.52503
    [11]	validation_0-logloss:0.52697
    [12]	validation_0-logloss:0.53335
    [13]	validation_0-logloss:0.53905
    [14]	validation_0-logloss:0.54545
    [15]	validation_0-logloss:0.54613
    Accuracy: 74.41%
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    3.4 交叉验证

    代码:

    from numpy import loadtxt
    from xgboost import XGBClassifier
    from sklearn.model_selection import GridSearchCV
    from sklearn.model_selection import StratifiedKFold
    
    # 加载数据集
    dataset = loadtxt('E:/file/pima-indians-diabetes.csv', delimiter=",")
    # 将数据分为 数据和标签
    X = dataset[:,0:8]
    Y = dataset[:,8]
    
    # grid search 做交叉验证
    model = XGBClassifier()
    learning_rate = [0.0001, 0.001, 0.01, 0.1, 0.2, 0.3]
    param_grid = dict(learning_rate=learning_rate)
    kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=7)
    grid_search = GridSearchCV(model, param_grid, scoring="neg_log_loss", n_jobs=-1, cv=kfold)
    grid_result = grid_search.fit(X, Y)
    
    # 汇总结果
    print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
    means = grid_result.cv_results_['mean_test_score']
    params = grid_result.cv_results_['params']
    for mean, param in zip(means, params):
        print("%f  with: %r" % (mean, param))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    测试记录:

    Best: -0.530152 using {'learning_rate': 0.01}
    -0.689563  with: {'learning_rate': 0.0001}
    -0.660868  with: {'learning_rate': 0.001}
    -0.530152  with: {'learning_rate': 0.01}
    -0.552723  with: {'learning_rate': 0.1}
    -0.653341  with: {'learning_rate': 0.2}
    -0.718789  with: {'learning_rate': 0.3}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    参考:

    1. https://study.163.com/course/introduction.htm?courseId=1003590004#/courseDetail?tab=1
    2. https://blog.csdn.net/qq_36603091/article/details/80592157
  • 相关阅读:
    PostgreSQL使用(一)
    数据结构与算法【Java】03---栈
    从零开始学习 Java:简单易懂的入门指南之不可变集合、方法引用(二十六)
    团队人才流失怎么办
    LPRNet, 车牌识别网络
    AlexNet论文解读
    Java实战:Spring Boot集成Elasticsearch全文搜索引擎
    EPICS记录参考--sub-Array记录(subArray)
    ARM-V9 RME(Realm Management Extension)系统架构之系统安全能力的MPAM
    二叉搜索树的最近公共祖先likou235、二叉搜索树的插入元素likou701
  • 原文地址:https://blog.csdn.net/u010520724/article/details/126096620