修剪决策树

16 python scikit-learn

嗨,下面的人是决策树的片段,因为它非常庞大.

在此输入图像描述

当节点中的最低小于5 时,如何使树停止增长.以下是生成决策树的代码.在SciKit - Decission Tree上我们可以看到唯一的方法是通过min_impurity_decrease,但我不确定它是如何具体工作的.

import numpy as np
import pandas as pd
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier


X, y = make_classification(n_samples=1000,
                           n_features=6,
                           n_informative=3,
                           n_classes=2,
                           random_state=0,
                           shuffle=False)

# Creating a dataFrame
df = pd.DataFrame({'Feature 1':X[:,0],
                                  'Feature 2':X[:,1],
                                  'Feature 3':X[:,2],
                                  'Feature 4':X[:,3],
                                  'Feature 5':X[:,4],
                                  'Feature 6':X[:,5],
                                  'Class':y})


y_train = df['Class']
X_train = df.drop('Class',axis = 1)

dt = DecisionTreeClassifier( random_state=42)                
dt.fit(X_train, y_train)

from IPython.display import display, Image
import pydotplus
from sklearn import tree
from sklearn.tree import _tree
from sklearn import tree
import collections
import drawtree
import os  

os.environ["PATH"] += os.pathsep + 'C:\\Anaconda3\\Library\\bin\\graphviz'

dot_data = tree.export_graphviz(dt, out_file = 'thisIsTheImagetree.dot',
                                 feature_names=X_train.columns, filled   = True
                                    , rounded  = True
                                    , special_characters = True)

graph = pydotplus.graph_from_dot_file('thisIsTheImagetree.dot')  

thisIsTheImage = Image(graph.create_png())
display(thisIsTheImage)
#print(dt.tree_.feature)

from subprocess import check_call
check_call(['dot','-Tpng','thisIsTheImagetree.dot','-o','thisIsTheImagetree.png'])
Run Code Online (Sandbox Code Playgroud)

更新

我认为min_impurity_decrease可以在某种程度上帮助实现目标.因为调整min_impurity_decrease实际上修剪了树.任何人都可以解释min_impurity_decrease.

我试图理解scikit学习中的等式,但我不确定right_impurity和left_impurity的价值是多少.

N = 256
N_t = 256
impurity = ??
N_t_R = 242
N_t_L = 14
right_impurity = ??
left_impurity = ??

New_Value = N_t / N * (impurity - ((N_t_R / N_t) * right_impurity)
                    - ((N_t_L / N_t) * left_impurity))
New_Value
Run Code Online (Sandbox Code Playgroud)

更新2

我们在一定条件下修剪而不是修剪某个值.比如我们分成6/4和5/5而不是6000/4或5000/5.假设一个值与节点中的相邻值相比是否低于某个百分比,而不是某个值.

      11/9
   /       \
  6/4       5/5
 /   \     /   \
6/0  0/4  2/2  3/3
Run Code Online (Sandbox Code Playgroud)

Dav*_*ale 20

使用min_impurity_decrease或任何其他内置停止条件无法直接限制叶子的最低值(特定类的出现次数).

我认为你可以在不改变scikit-learn源代码的情况下实现这一目标的唯一方法就是对你的树进行后期修剪.要实现这一点,您可以遍历树并删除节点的所有子节点,最小类数少于5(或您可以想到的任何其他条件).我会继续你的榜样:

from sklearn.tree._tree import TREE_LEAF

def prune_index(inner_tree, index, threshold):
    if inner_tree.value[index].min() < threshold:
        # turn node into a leaf by "unlinking" its children
        inner_tree.children_left[index] = TREE_LEAF
        inner_tree.children_right[index] = TREE_LEAF
    # if there are shildren, visit them as well
    if inner_tree.children_left[index] != TREE_LEAF:
        prune_index(inner_tree, inner_tree.children_left[index], threshold)
        prune_index(inner_tree, inner_tree.children_right[index], threshold)

print(sum(dt.tree_.children_left < 0))
# start pruning from the root
prune_index(dt.tree_, 0, 5)
sum(dt.tree_.children_left < 0)
Run Code Online (Sandbox Code Playgroud)

此代码将首先打印74,然后打印91.这意味着代码创建了17个新的叶节点(通过实际删除其祖先的链接).树,看起来像之前

在此输入图像描述

现在看起来像

在此输入图像描述

所以你可以看到确实已经减少了很多.