XGBoost怎么用python实现代码
时间: 2024-06-11 09:02:42 浏览: 95
XGBoost是一种流行的机器学习库,它在许多比赛和实际应用中都表现出色。在Python中使用XGBoost非常方便,下面是一个简单的代码示例:
首先,安装XGBoost库:
```
pip install xgboost
```
然后导入库和数据集:
```python
import xgboost as xgb
from sklearn.datasets import load_boston
boston = load_boston()
X, y = boston.data, boston.target
```
接下来,将数据集划分为训练集和测试集,并定义模型参数:
```python
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
params = {
'objective': 'reg:squarederror',
'eval_metric': 'rmse'
}
```
定义模型并训练:
```python
dtrain = xgb.DMatrix(X_train, label=y_train)
dtest = xgb.DMatrix(X_test, label=y_test)
num_rounds = 100
model = xgb.train(params, dtrain, num_rounds)
```
在测试集上进行预测:
```python
y_pred = model.predict(dtest)
```
最后,计算模型的性能指标(例如RMSE):
```python
from sklearn.metrics import mean_squared_error
rmse = mean_squared_error(y_test, y_pred, squared=False)
print('RMSE:', rmse)
```
阅读全文