xgboost预测的模型代码
时间: 2024-06-18 07:04:17 浏览: 120
Xgboost案例源代码.zip
XGBoost是一种非常流行的机器学习算法,它在许多比赛和实际项目中都有着优秀的表现。XGBoost是一个集成学习算法,它通过对多个决策树的结果进行加权平均来进行预测。
下面是一个使用XGBoost进行二分类预测的示例代码:
```python
import xgboost as xgb
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 加载数据集
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=42)
# 将数据转换为DMatrix格式
dtrain = xgb.DMatrix(X_train, label=y_train)
dtest = xgb.DMatrix(X_test, label=y_test)
# 设置模型参数
params = {'max_depth': 3, 'eta': 0.1, 'objective': 'binary:logistic', 'eval_metric': 'error'}
# 训练模型
num_rounds = 100
model = xgb.train(params, dtrain, num_rounds)
# 预测测试集
y_pred = model.predict(dtest)
y_pred = [int(round(p)) for p in y_pred]
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```
阅读全文