xgboost能否用于分类场景中,如果能是怎么应用的呢,请给出代码示例
时间: 2023-02-08 14:14:47 浏览: 134
XGBoost可以用于分类场景。在使用XGBoost进行分类时,需要将目标变量的类型设置为"category",然后使用"softmax"作为损失函数。
以下是一个使用XGBoost进行分类的Python代码示例:
```
import xgboost as xgb
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
# 加载数据集
iris = load_iris()
X, y = iris.data, iris.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 设置模型参数
params = {
'objective': 'multi:softmax',
'num_class': 3,
'tree_method': 'gpu_hist'
}
# 构建模型
xgb_model = xgb.XGBClassifier(**params)
# 训练模型
xgb_model.fit(X_train, y_train)
# 预测并评估模型
y_pred = xgb_model.predict(X_test)
acc = (y_pred == y_test).mean()
print("Accuracy: {:.2f}%".format(acc*100))
```
阅读全文
相关推荐


















