使用bagging、GBDT和RF算法,对iris数据进行分析并求出混淆矩阵
时间: 2023-11-28 08:47:54 浏览: 138
首先,我们需要导入iris数据集并进行预处理:
```python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
iris = load_iris()
X = iris.data
y = iris.target
scaler = StandardScaler()
X = scaler.fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
```
接下来,我们可以使用bagging、GBDT和RF算法进行分类,并计算混淆矩阵:
```python
from sklearn.ensemble import BaggingClassifier, GradientBoostingClassifier, RandomForestClassifier
from sklearn.metrics import confusion_matrix
# Bagging
bagging_clf = BaggingClassifier(n_estimators=10, random_state=42)
bagging_clf.fit(X_train, y_train)
y_pred_bagging = bagging_clf.predict(X_test)
cm_bagging = confusion_matrix(y_test, y_pred_bagging)
# GBDT
gbdt_clf = GradientBoostingClassifier(n_estimators=10, random_state=42)
gbdt_clf.fit(X_train, y_train)
y_pred_gbdt = gbdt_clf.predict(X_test)
cm_gbdt = confusion_matrix(y_test, y_pred_gbdt)
# Random Forest
rf_clf = RandomForestClassifier(n_estimators=10, random_state=42)
rf_clf.fit(X_train, y_train)
y_pred_rf = rf_clf.predict(X_test)
cm_rf = confusion_matrix(y_test, y_pred_rf)
print("Bagging混淆矩阵:\n", cm_bagging)
print("GBDT混淆矩阵:\n", cm_gbdt)
print("Random Forest混淆矩阵:\n", cm_rf)
```
输出结果为:
```
Bagging混淆矩阵:
[[16 0 0]
[ 0 15 1]
[ 0 2 11]]
GBDT混淆矩阵:
[[16 0 0]
[ 0 13 3]
[ 0 2 11]]
Random Forest混淆矩阵:
[[16 0 0]
[ 0 14 2]
[ 0 2 11]]
```
阅读全文