sklearn机器学习之随机森林分类(红酒数据集)

本次使用随机森林通过十折交叉验证得到最大平均精度为99%

1.导入相应包

from sklearn.tree import DecisionTreeClassifier
from matplotlib import pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score

2.准备数据集

wine = load_wine()
wine.data
wine.target

3.划分训练测试集

#划分训练测试集
Xtrain, Xtest, Ytrain, Ytest = train_test_split(wine.data, wine.target, test_size=0.3)

4.对比单个决策树和随机森林

clf = DecisionTreeClassifier(random_state=0)
rfc = RandomForestClassifier(random_state=0)
clf.fit(Xtrain, Ytrain)
rfc.fit(Xtrain, Ytrain)
score_c = clf.score(Xtest, Ytest)
score_r = rfc.score(Xtest, Ytest)
print("single Tree is {}".format(score_c), "Random forest is {}".format(score_r))

5.对比单个决策树和随机森林十折交叉验证精度

rfc = RandomForestClassifier(n_estimators=25)
rfc_s = cross_val_score(rfc, wine.data, wine.target, cv=10)

clf = DecisionTreeClassifier()
clf_s = cross_val_score(clf, wine.data, wine.target, cv=10)

plt.plot(range(1, 11), rfc_s, label='Random forest')
plt.plot(range(1, 11), clf_s, label='Decision Tree')
plt.xticks(range(1, 11))
plt.legend()
plt.show()

此段代码一种高级写法为:

#高级写法:将模型写入列表通过for遍历对比精度
label = 'Random Forest'
for model in [RandomForestClassifier(n_estimators=25), DecisionTreeClassifier()]:
    score = cross_val_score(model, wine.data, wine.target, cv=10)
    print("{}:".format(label)), print(score.mean())
    plt.plot(range(1,11), score, label=label)
    plt.legend()
    label = "Decision Tree"

得到图像为:
在这里插入图片描述

6.对比十次单个决策树和随机森林的精度

rfc_l = []
clf_l = []
for i in range(10):
    rfc = RandomForestClassifier(n_estimators=25)
    rfc_s = cross_val_score(rfc, wine.data, wine.target, cv=10).mean()
    rfc_l.append(rfc_s)
    clf = DecisionTreeClassifier()
    clf_s = cross_val_score(clf, wine.data, wine.target, cv=10).mean()
    clf_l.append(clf_s)
    
plt.plot(range(1,11),rfc_l,label = "Random Forest")
plt.plot(range(1,11),clf_l,label = "Decision Tree")
plt.legend()
plt.show()

对比结果图为:
在这里插入图片描述
从结果中我们可以看出随机森林对比单个决策树分类精度整体高很多,这也说明随机森林的强大。

7.不同n_estimators随机森林学习曲线

#n_estimators学习曲线
superna = []
for i in range(50):
    rfc = RandomForestClassifier(n_estimators=i+1)
    rfc_s = cross_val_score(rfc, wine.data, wine.target, cv=10).mean()
    superna.append(rfc_s)
print("max is {}".format(max(superna)), "index is {}".format(superna.index(max(superna))))
plt.figure(figsize=[20, 5])
plt.plot(range(1, 51), superna)
plt.show()

学习曲线图为:
在这里插入图片描述
得到的最大精度以及n_estimators参数值为15,这说明随着n_estimators的不短增加,精度也会逐渐增大,但是到了一定阈值,精度就会在最大值附近波动。

max is 0.9888888888888889 index is 15

8.自主法划分训练集

#设置
rfc = RandomForestClassifier(n_estimators=25, oob_score=True)
rfc.fit(wine.data, wine.target)
rfc.oob_score_

得到的精度为:

0.9831460674157303

9.其他参数

rfc = RandomForestClassifier(n_estimators=25)
rfc.fit(Xtrain, Ytrain)
rfc.score(Xtest, Ytest)
#属性重要性
rfc.feature_importances_
#输入特征集输出叶子结点索引
rfc.apply(Xtest)
#输入特征集输出类别
rfc.predict(Xtest)
#输入特征集输出分类可能性
rfc.predict_proba(Xtest)

9.集成算法的一个重要要求

之前我们说过,在使用袋装法时要求基评估器要尽量独立。其实,袋装法还有另一个必要条件:基分类器的判断准确率至少要超过随机分类器,即时说,基分类器的判断准确率至少要超过50%,不然袋装法的精确率要比单棵决策树效果更差。

import numpy as np
import math
x = np.linspace(0, 1, 20)
y = []
for epsilon in x:
    E = np.array([math.comb(25,i)*(epsilon**i)*((1-epsilon)**(25-i))
                  for i in range(13,26)]).sum()
    y.append(E)
plt.plot(x,y,"o-",label="when estimators are different")
plt.plot(x,x,"--",color="red",label="if all estimators are same")
plt.xlabel("individual estimator's error")
plt.ylabel("RandomForest's error")
plt.legend()
plt.show()

得到的对比图如下:
在这里插入图片描述
所以我们需要保证每个决策树的准确率大于50%,才可以使用袋装法随机森林进行预测。

  • 11
    点赞
  • 110
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
随机森林是一种集成学习方法,它通过构建多个决策树来提高预测准确性。下面是sklearn随机森林的一些基本步骤、参数、属性和接口: 1. 基本步骤: 1.1 参数n_estimators:指定森林中树的数量。 1.2 建立森林:使用RandomForestClassifier()函数建立随机森林。 1.3 n_estimators的学习曲线:使用validation_curve()函数绘制n_estimators的学习曲线。 2. 重要的参数、属性、接口: 2.1 random_state:在划分训练集和测试集的类train_test_split、构建决策树的函数、构建随机森林时都可以使用该参数,它可以保证每次运行时得到的结果都是一样的。 2.2 estimators_:查看森林中每棵树的状况。 2.3 bootstrap & oob_score:bootstrap参数控制是否进行有放回的随机抽样,oob_score参数控制是否使用袋外样本来评估模型的准确性。 2.4 fit & score:fit()函数用于拟合模型,score()函数用于评估模型的准确性。 2.5 feature_importances_:查看每个特征的重要性。 2.6 apply:返回每个样本所在的叶子节点的索引。 2.7 predict:对新数据进行预测。 2.8 predict_proba:返回每个类别的概率。 3. 随机森林回归器: 3.1 重要的参数、属性、接口:与分类器类似,但是需要使用RandomForestRegressor()函数来建立随机森林回归器。 4. 机器学习中调参的基本思想: 泛化误差:模型在新数据上的误差。 标签和特征:标签是我们要预测的变量,特征是我们用来预测标签的变量。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值