xgboost.sklearn
时间: 2024-06-10 19:03:09 浏览: 159
XGBoost是eXtreme Gradient Boosting(极端梯度提升)的Python接口,它是一个强大的梯度提升库,特别适合处理复杂的机器学习任务。在sklearn中,XGBoost通过`xgboost.XGBClassifier`和`xgboost.XGBRegressor`等类提供给用户,用于构建决策树模型。
以下是使用XGBoost的基本步骤:
1. 导入所需的库[^4]:
```python
import xgboost as xgb
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
```
2. 加载数据集[^5]:
```python
iris = load_iris()
X, y = iris.data, iris.target
```
3. 划分训练集和测试集[^6]:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
4. 初始化并训练XGBoost模型[^7]:
```python
model = xgb.XGBClassifier(objective='multi:softmax', num_class=3) # 对于多分类问题
model.fit(X_train, y_train)
```
5. 预测测试集结果[^8]:
```python
y_pred = model.predict(X_test)
```
6. 评估模型性能[^9]:
```python
from sklearn.metrics import accuracy_score
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
阅读全文