XGBoost案例代码(一)——sklearn之交叉验证

#!/usr/bin/python
'''
Created on 1 Apr 2015

@author: Jamie Hall
'''
import pickle
import xgboost as xgb

import numpy as np
from sklearn.model_selection import KFold, train_test_split, GridSearchCV
from sklearn.metrics import confusion_matrix, mean_squared_error
from sklearn.datasets import load_iris, load_digits, load_boston

rng = np.random.RandomState(31337)

print("Zeros and Ones from the Digits dataset: binary classification")
digits = load_digits(2)
y = digits['target']
X = digits['data']
kf = KFold(n_splits=2, shuffle=True, random_state=rng)
for train_index, test_index in kf.split(X):
    xgb_model = xgb.XGBClassifier().fit(X[train_index], y[train_index])
    predictions = xgb_model.predict(X[test_index])
    actuals = y[test_index]
    print(confusion_matrix(actuals, predictions))

print("Iris: multiclass classification")
iris = load_iris()
y = iris['target']
X = iris['data']
kf = KFold(n_splits=2, shuffle=True, random_state=rng)
for train_index, test_index in kf.split(X):
    xgb_model = xgb.XGBClassifier().fit(X[train_index], y[train_index])
    predictions = xgb_model.predict(X[test_index])
    actuals = y[test_index]
    print(confusion_matrix(actuals, predictions))

print("Boston Housing: regression")
boston = load_boston()
y = boston['target']
X = boston['data']
kf = KFold(n_splits=2, shuffle=True, random_state=rng)
for train_index, test_index in kf.split(X):
    xgb_model = xgb.XGBRegressor().fit(X[train_index], y[train_index])
    predictions = xgb_model.predict(X[test_index])
    actuals = y[test_index]
    print(mean_squared_error(actuals, predictions))

print("Parameter optimization")
y = boston['target']
X = boston['data']
xgb_model = xgb.XGBRegressor()
clf = GridSearchCV(xgb_model,
                   {'max_depth': [2,4,6],
                    'n_estimators': [50,100,200]}, verbose=1)
clf.fit(X,y)
print(clf.best_score_)
print(clf.best_params_)

# The sklearn API models are picklable
print("Pickling sklearn API models")
# must open in binary format to pickle
pickle.dump(clf, open("best_boston.pkl", "wb"))
clf2 = pickle.load(open("best_boston.pkl", "rb"))
print(np.allclose(clf.predict(X), clf2.predict(X)))

# Early-stopping

X = digits['data']
y = digits['target']
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
clf = xgb.XGBClassifier()
clf.fit(X_train, y_train, early_stopping_rounds=10, eval_metric="auc",
        eval_set=[(X_test, y_test)])

03-08
### XGBoost机器学习算法介绍 XGBoost(eXtreme Gradient Boosting)是种高效的梯度提升框架,广泛应用于数据科学竞赛和工业界项目中。该算法基于梯度提升树,在传统GBDT基础上做了多项改进,提升了训练速度与模型精度[^2]。 #### 主要特点 - **高效并行化处理**:支持多线程CPU并行加速; - **正则项控制过拟合**:加入L1/L2正则化参数防止过拟合现象发生; - **灵活的目标函数定义**:允许自定义损失函数适应不同场景需求; - **内置交叉验证功能**:方便调参操作减少外部依赖工具; - **缺失值自动处理机制**:无需额外预处理即可有效应对含有空缺的数据集。 ### 使用方法概述 为了更好地理解和运用XGBoost,下面将以Python为例展示基本的安装配置流程及简单案例: #### 安装环境准备 对于大多数开发者而言,推荐采用pip命令快速完成软件包安装: ```bash pip install xgboost ``` 如果希望在C++环境中部署,则需按照特定指南编译源码文件,并链接必要的头文件路径[^3]: ```cpp #include <iostream> #include <vector> #include <xgboost/c_api.h> int main() { std::cout << "Hello, XGBoost!" << std::endl; } ``` #### 构建分类器实例 创建个简单的二元分类任务作为入门练习: ```python import numpy as np from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split import xgboost as xgb # 准备模拟数据集 X, y = make_classification(n_samples=1000, n_features=20, n_informative=2, n_redundant=10, random_state=7) dtrain = xgb.DMatrix(X[:800], label=y[:800]) dtest = xgb.DMatrix(X[800:], label=y[800:]) param = {'max_depth': 6, 'eta': 0.3, 'objective': 'binary:logistic'} num_round = 100 bst = xgb.train(param, dtrain, num_round) preds = bst.predict(dtest) print('Prediction:', preds) ``` 此段代码展示了如何利用`sklearn`生成合成数据集,并将其划分为训练集与测试集用于后续评估过程。接着设置超参数字典`param`指定最大深度、学习率等重要属性,最后通过调用`xgb.train()`启动迭代优化直至收敛得到最终模型对象`bst`。 ### 特征工程技巧 针对大规模稀疏矩阵或高维特征空间问题,XGBoost提供了独特的解决方案——近似分割策略。具体来说就是通过对连续型变量执行离散化映射至有限区间内,从而降低内存占用量的同时加快求解进度[^4]。 例如某列数值范围位于\[0,9\]之间时可划分成若干子区间形成新的编码形式便于计算机识别存储;而全局/局部两种模式下的分桶规则决定了每次更新节点内部是否沿用先前设定好的边界条件还是重新计算最优切分点位置。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值