stacking集成xgboost,rf代码
时间: 2023-05-26 21:02:55 浏览: 34
以下是将XGBoost和随机森林进行堆叠集成的Python示例代码:
```python
# 导入所需的库和模型
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from xgboost import XGBClassifier
from sklearn.metrics import accuracy_score
# 加载数据
data = pd.load_csv('data.csv')
X = data.drop('target', axis=1)
y = data['target']
# 将训练集和测试集拆分为50-50,以便进行堆叠集成
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=42)
# 创建第一层模型
rf = RandomForestClassifier(n_estimators=100, random_state=42)
xgb = XGBClassifier(n_estimators=100, random_state=42)
# 训练第一层模型并进行预测
rf.fit(X_train, y_train)
rf_predictions = rf.predict_proba(X_test)[:, 1]
xgb.fit(X_train, y_train)
xgb_predictions = xgb.predict_proba(X_test)[:, 1]
# 将第一层模型的预测结果作为第二层模型的输入
X_stacked = np.column_stack((rf_predictions, xgb_predictions))
y_stacked = y_test
# 创建第二层模型,并训练和预测
stacked_model = XGBClassifier(n_estimators=100, random_state=42)
stacked_model.fit(X_stacked, y_stacked)
stacked_predictions = stacked_model.predict(X_stacked)
# 计算精度
accuracy = accuracy_score(y_stacked, stacked_predictions)
print("Stacked model accuracy: %.2f%%" % (accuracy * 100.0))
```
以上代码中,我们:
1. 加载数据集并将其拆分为训练集和测试集。
2. 创建两个第一层模型 - 随机森林和XGBoost,并分别训练它们。
3. 对测试集进行预测,并将两个第一层模型的预测结果堆叠在一起。
4. 创建第二层模型 - XGBoost,并使用以上步骤中的堆叠结果进行训练和预测。
5. 计算第二层模型的精度。