Iris鸢尾花数据集与集成学习

实验内容:

1. 将数据集按7:3 的比例随机划分为训练集和验证集,随机数生成器种子为学号后三位数,并输出训练集和验证集前10行数据;

2. 在训练集上训练决策树模型,生成如下的决策树边界

3. 在训练集上训练Bagging(基学习器自选)和随机森林模型,基学习器个数为100,输出决策边界图,并分析结果差异;

4. 分别计算决策树、Bagging(基学习器自选)和随机森林模型在Iris数据集上三分类的混淆矩阵,并对三种算法的输出结果进行比较。

数据集的准备

#加载数据并分离数据集与测试集
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
iris = load_iris()
X = iris.data
y = iris.target

x_train,x_test,y_train,y_test = train_test_split(X,y,test_size=0.3,random_state=(208))
print("训练集前十行数据:")
print(x_train[:10])
print()
print(y_train[:10])
print()
print("验证集前十行数据:")
print(x_test[:10])
print()
print(y_test[:10])

 模型训练

在训练集上训练决策树模型
from sklearn.tree import DecisionTreeClassifier
tree_clf = DecisionTreeClassifier(random_state=208)
tree_clf.fit(x_train[:,2:], y_train)

#绘制决策树边界
plt.figure(1)
plot_decision_boundary(tree_clf,x_train[:,2:],y_train)
plt.xlabel("petal length/cm", fontsize=14)
plt.ylabel("petal width/cm", rotation='vertical', fontsize=14)
plt.title("decision tree decision boundaries plot", fontsize=16)
plt.text(1.40, 1.0, "Depth=0", fontsize=15)
plt.text(3.2, 1.80, "Depth=1", fontsize=13)
plt.text(4.05, 0.5, "Depth=2", fontsize=11)
save_fig("决策树边界")

#训练Bagging(基学习器自选)模型
from sklearn.ensemble import BaggingClassifier
bag_clf = BaggingClassifier(
    DecisionTreeClassifier(random_state=208), n_estimators=100,
    max_samples=50, bootstrap=True, random_state=208)
bag_clf.fit(x_train[:,2:], y_train)

plt.figure(2)
plot_decision_boundary(bag_clf,X[:,2:],y)
plt.title("Decision Trees with Bagging", fontsize=14)
plt.xlabel("petal length/cm", fontsize=14)
plt.ylabel("petal width/cm", rotation='vertical', fontsize=14)
plt.text(1.00, 1.0, "Depth=0", fontsize=13)
plt.text(3.2, 0.5, "Depth=1", fontsize=13)
plt.text(6.0, 1.5, "Depth=2", fontsize=11)
save_fig("Bagging 模型")

#训练随机森林模型
from sklearn.ensemble import RandomForestClassifier
rnd_clf = RandomForestClassifier(n_estimators=100, random_state=208)
rnd_clf.fit(x_train[:,2:], y_train)
plt.figure(3)
plot_decision_boundary(rnd_clf,X[:,2:],y)
plt.xlabel("petal length/cm", fontsize=14)
plt.ylabel("petal width/cm", rotation='vertical', fontsize=14)
plt.title("RandomForest boundary n_estimators=100", fontsize=14)
plt.text(3.50, 0.5, "Depth=0", fontsize=13)
plt.text(1.75, 1.25, "Depth=1", fontsize=13)
plt.text(5.75, 1.25, "Depth=2", fontsize=13)
save_fig("随机森林模型")

精度比较

#精度验证
from sklearn.metrics import accuracy_score
y_pred = tree_clf.predict(x_test[:,2:])
print("决策树精度:",accuracy_score(y_test, y_pred))

y_pred = bag_clf.predict(x_test[:,2:])
print("Bagging精度:",accuracy_score(y_test, y_pred))

y_pred_rf = rnd_clf.predict(x_test[:,2:])
print("随机森林精度:",np.sum(y_pred == y_pred_rf) / len(y_pred))

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值