Post pruning decision trees with cost complexity pruning
The DecisionTreeClassifier provides parameters such as
min_samples_leaf and max_depth to prevent a tree from overfitting. Cost
complexity pruning provides another option to control the size of a tree. In
DecisionTreeClassifier, this pruning technique is parameterized by the
cost complexity parameter, ccp_alpha. Greater values of ccp_alpha
increase the number of nodes pruned. Here we only show the effect of
on regularizing the trees and how to choose a
based on validation scores.
ccp_alpha
ccp_alpha
)
ax
.
set_ylabel
(
"total impurity of leaves"
)
ax
.
set_title
(
"Total Impurity vs effective alpha for training set"
)
)
print
(
"Number of nodes in the last tree is:
{}
with ccp_alpha:
{}
"
.
format
(
clfs
[
-
1
]
.
tree_
.
node_count
,
ccp_alphas
[
-
1
]
)
)
clfs
]
fig
,
ax
=
(
2
,
1
)
ax
[
0
]
.
plot
(
ccp_alphas
,
node_counts
,
marker
=
"o"
,
drawstyle
=
"steps-post"
)
ax
[
0
]
.
set_xlabel
(
"alpha"
)
ax
[
0
]
.
set_ylabel
(
"number of nodes"
)
ax
[
0
]
.
set_title
(
"Number of nodes vs alpha"
)
ax
[
1
]
.
plot
(
ccp_alphas
,
depth
,
marker
=
"o"
,
drawstyle
=
"steps-post"
)
ax
[
1
]
.
set_xlabel
(
"alpha"
)
ax
[
1
]
.
set_ylabel
(
"depth of tree"
)
ax
[
1
]
.
set_title
(
"Depth vs alpha"
)
fig
.
tight_layout
()
Download zipped: plot_cost_complexity_pruning.zip