xgboost预测代码
时间: 2024-06-19 09:01:11 浏览: 217
xgboost代码
XGBoost是一个强大的梯度提升库,常用于机器学习中的分类和回归任务。以下是一个使用Python的XGBoost库进行简单预测的基本示例,假设我们已经加载了数据集并进行了预处理:
```python
# 导入所需的库
import xgboost as xgb
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, mean_squared_error
# 假设你的数据已经存储在'data'中,特征列在'data_features',目标列在'data_target'
data = ... # 读取数据或加载数据
data_features, data_target = data['features'], data['target']
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(data_features, data_target, test_size=0.2, random_state=42)
# 初始化XGBoost模型
model = xgb.XGBClassifier() # 对于分类问题
# 或者
model = xgb.XGBRegressor() # 对于回归问题
# 训练模型
model.fit(X_train, y_train)
# 预测
y_pred = model.predict(X_test)
# 评估结果
if isinstance(model, xgb.XGBClassifier):
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")
else:
mse = mean_squared_error(y_test, y_pred)
print(f"MSE: {mse}")
# 如果你想保存模型,可以这样做
model.save_model('xgboost_model.xgb')
```
阅读全文