scikit learn 随机森林

随机森林

在随机森林中,集合中的每棵树都是根据训练集中的替换样本(即引导样本)构建的。
此外,在树的构造过程中拆分每个节点时,可以从所有输入要素或size的随机子集中找到最佳拆分 max_features。
这两个随机性来源的目的是减少森林估计量的方差。实际上,单个决策树通常表现出较高的方差并且倾向于过度拟合。森林中注入的随机性产生决策树,其预测误差有些解耦。(一个树有误差不会对总体结果有太大影响。)通过取这些预测的平均值,可以消除一些误差。随机森林通过组合不同的树木来减少变化,有时会以略微增加偏差为代价。

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.ensemble import RandomForestClassifier,ExtraTreesClassifier
from sklearn import datasets
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

# 随机森立 :多颗决策树构建而成,每一颗决策树都是刚才讲到的决策树原理
# 多颗决策树一起运算------------>集成算法
# 随机森林,随机什么意思
#意味着通过在分类器构造中引入随机性来创建多样化的分类器集
#随机在抽样上 100棵树意味着100种子样本 每一棵树的裂分条件也会不同 最后的结果会结合10棵树进行决策 使用平均数提高准确率 防止过拟合
wine = datasets.load_wine()
wine
#...'target_names': array(['class_0', 'class_1', 'class_2'], dtype='<U7'),...三种

X = wine['data']
y = wine['target']
X.shape
#(178, 13)
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.2)

#n_estimators默认10个分类器 gini系数 深度
clf = RandomForestClassifier()
clf.fit(X_train,y_train)
y_ = clf.predict(X_test)
from sklearn.metrics import accuracy_score
accuracy_score(y_test,y_)
#1.0

dt_clf = DecisionTreeClassifier()
dt_clf.fit(X_train,y_train)
dt_clf.score(X_test,y_test)
#0.9444444444444444

score = 0 
for i in range(100):
    X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.2)
    dt_clf = DecisionTreeClassifier()
    dt_clf.fit(X_train,y_train)
    score+=dt_clf.score(X_test,y_test)/100    
print('决策树多次运行准确率:',score)
#决策树多次运行准确率: 0.909166666666666

score = 0 
for i in range(100):
    X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.2)    
    clf = RandomForestClassifier(n_estimators=100)
    clf.fit(X_train,y_train)
    score+=clf.score(X_test,y_test)/100   
print('随机森林多次运行准确率:',score)
#随机森林多次运行准确率: 0.9808333333333332
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值