自适应网格搜索优化xgboost算法详细代码

自适应网格搜索(Adaptive Grid Search)通常是一种动态调整搜索范围以优化性能的方法。在 XGBoost 算法中,您可以通过逐步缩小或扩大超参数搜索范围来实现自适应网格搜索。

以下是一个基于 XGBoost 的自适应网格搜索的示例,演示如何使用逐步缩小超参数搜索范围的思想。请注意,此示例中的超参数和搜索范围仅供参考,并非绝对适用于所有问题。您可能需要根据具体情况调整超参数范围和步长。

import xgboost as xgb
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, GridSearchCV

# 加载数据集
data = load_breast_cancer()
X, y = data.data, data.target

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 定义初始参数范围
param_grid = {
    'learning_rate': [0.1, 0.01, 0.001],
    'max_depth': [3, 4, 5, 6, 7],
    'n_estimators': [100, 200, 300, 400]
}

# 初始化 GridSearchCV
grid_search = GridSearchCV(
    estimator=xgb.XGBClassifier(),
    param_grid=param_grid,
    cv=5,
    scoring='accuracy',
    n_jobs=-1
)

# 开始搜索
grid_result = grid_search.fit(X_train, y_train)

# 输出最佳参数和对应的性能指标
print("最佳参数:", grid_result.best_params_)
print("最佳得分:", grid_result.best_score_)

# 在测试集上评估最佳模型
best_model = grid_result.best_estimator_
test_accuracy = best_model.score(X_test, y_test)
print("测试集准确率:", test_accuracy)
 

import xgboost as xgb
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, GridSearchCV

# 加载数据集
data = load_breast_cancer()
X, y = data.data, data.target

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 定义初始参数范围
param_grid = {
    'learning_rate': [0.1, 0.01, 0.001],
    'max_depth': [3, 4, 5, 6, 7],
    'n_estimators': [100, 200, 300, 400]
}

# 初始化 GridSearchCV
grid_search = GridSearchCV(
    estimator=xgb.XGBClassifier(),
    param_grid=param_grid,
    cv=5,
    scoring='accuracy',
    n_jobs=-1
)

# 开始搜索
grid_result = grid_search.fit(X_train, y_train)

# 输出最佳参数和对应的性能指标
print("最佳参数:", grid_result.best_params_)
print("最佳得分:", grid_result.best_score_)

# 在测试集上评估最佳模型
best_model = grid_result.best_estimator_
test_accuracy = best_model.score(X_test, y_test)
print("测试集准确率:", test_accuracy)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值