用python写一个xgboost回归的代码
时间: 2023-04-06 08:02:48 浏览: 173
好的,我可以回答这个问题。以下是一个简单的 Python 代码示例,用于训练和测试 XGBoost 回归模型:
```python
import xgboost as xgb
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
# 加载数据集
boston = load_boston()
X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, test_size=0.2, random_state=123)
# 定义模型参数
params = {
'objective': 'reg:squarederror',
'eval_metric': 'rmse',
'max_depth': 3,
'learning_rate': 0.1,
'subsample': 0.8,
'colsample_bytree': 0.8,
'seed': 123
}
# 转换数据为 DMatrix 格式
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)
# 预测并计算误差
y_pred = model.predict(dtest)
mse = mean_squared_error(y_test, y_pred)
print('MSE:', mse)
```
希望这个代码示例能够帮助到你。
阅读全文