<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Joann on Medium]]></title>
        <description><![CDATA[Stories by Joann on Medium]]></description>
        <link>https://medium.com/@vzhang1999?source=rss-877ea298a683------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*imTpyW3HxHRju8xYXhVryA.jpeg</url>
            <title>Stories by Joann on Medium</title>
            <link>https://medium.com/@vzhang1999?source=rss-877ea298a683------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 06:23:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vzhang1999/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Classification Tree Growing and Pruning with Python Code (Grid Search & Cost-Complexity Function)]]></title>
            <link>https://vzhang1999.medium.com/classification-tree-growing-and-pruning-with-python-code-grid-search-cost-complexity-function-b2e45e33a1a4?source=rss-877ea298a683------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2e45e33a1a4</guid>
            <category><![CDATA[k-fold-cross-validation]]></category>
            <category><![CDATA[data-mining]]></category>
            <category><![CDATA[grid-search]]></category>
            <category><![CDATA[classification-tree]]></category>
            <category><![CDATA[decision-tree]]></category>
            <dc:creator><![CDATA[Joann]]></dc:creator>
            <pubDate>Thu, 25 Mar 2021 15:11:22 GMT</pubDate>
            <atom:updated>2021-03-26T20:42:56.561Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hEWL0yo6FNUG2qRpkeEhXw.jpeg" /><figcaption><em>Cesare da Sesto (1480–1521), Study for a Tree</em></figcaption></figure><h3><strong>Topics in this article:</strong></h3><ol><li><strong><em>Recursive Partitioning</em></strong></li><li><em>Impurity Measurements: </em><strong><em>Gini Index</em></strong><em> and </em><strong><em>Entropy</em></strong></li><li><em>Tree evaluation using </em><strong><em>Grid Search</em></strong><em> and </em><strong><em>Cost-Complexity</em></strong><em> with Cross Validation (CV)</em></li><li><strong><em>Pros and Cons</em></strong><em> about Decision Tree</em></li></ol><h3><strong>Why Decision Tree?</strong></h3><p>Among the numerous data mining methods, decision tree is a flexible algorithm that could fit both regression and classification problems. Moreover, as a prediction-oriented algorithm, decision tree is also easy to interpret under transparent rules based on the tree splits, making the predictive results readily understandable.</p><h3>Basic Concepts &amp; Property in Tree</h3><ol><li>Decision nodes: nodes that have following branches and nodes downward the tree.</li><li>Terminal nodes/leaves: nodes that have no successors.</li><li>For binary trees: the number of terminal nodes is exactly one more than the number of decision nodes.</li></ol><h3>How to grow a tree: <em>Recursive Partitioning</em></h3><p>Predictors/Input Variables: X1, X2, X3, X4….which are numeric, binary or ordinal.</p><p>Response Variable: binary (0/1 or No/Yes), meaning a classification problem.</p><p>First, a variable is selected, say X1, then a value of it, s1, is chosen to split the input variables (a 4-dimensional space) into two non-overlapping parts, points with X1 &lt; s1, and points with X1 =&gt; s1. One of these two parts is then selected and a variable and a value is used to split it in a similar manner. This process repeats again and again until there are many small partitions. Each partition is operated on the result of its previous partition, therefore it’s called recursive partitioning. Importantly, the goal of the partitions is to <strong>have each partition as pure as possible</strong>. By pure, it means that the partition contains records that belong to only one class (YES/NO). The measurements of impurity are <strong>Gini Index and Entropy</strong>.</p><p><strong>How s1 (the splitting point) is selected? </strong>For each variable, we sort the values and take the midpoints of each pair of consecutive values. Among the possible splitting points, we rank them according to how much impurity they have reduced.</p><p><strong>How to define Reduction of impurity? </strong>It’s the difference between the overall impurity before the split and the sum of impurities of the two partition after the split.</p><pre># load the data<br>bank_df = pd.read_csv(&#39;UniversalBank.csv&#39;)</pre><pre># data preprocess<br>bank_df.columns = [c.replace(&#39; &#39;, &#39;_&#39;) for c in bank_df.columns]</pre><pre># Treat education as categorical, convert to dummy variables<br>bank_df[&#39;Education&#39;] = bank_df[&#39;Education&#39;].astype(&#39;category&#39;)<br>new_categories = {1: &#39;Undergrad&#39;, 2: &#39;Graduate&#39;, 3: &#39;Advanced/Professional&#39;}<br>bank_df.Education.cat.rename_categories(new_categories, inplace=True)<br>bank_df = pd.get_dummies(bank_df, prefix_sep=&#39;_&#39;, drop_first=True)</pre><pre># split the train and validation data<br>x = bank_df.drop([&#39;Personal_Loan&#39;, &#39;ZIP_Code&#39;, &#39;ID&#39;], axis=&#39;columns&#39;)<br>y = bank_df[&#39;Personal_Loan&#39;]<br>train_x, val_x, train_y, val_y = train_test_split(x, y, test_size = .4, random_state = 1)</pre><pre># fit the tree<br>fulltree = DecisionTreeClassifier(random_state=2)<br>fulltree.fit(train_x, train_y)</pre><pre># plot the tree<br>plotDecisionTree(fulltree, feature_names=train_x.columns)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3kH665UJbL9-G8RW2DpelQ.png" /><figcaption>The fully grown tree</figcaption></figure><h3>Tree Evaluation: Grid Search and Cost Complexity Function with out-of-sample data</h3><p><strong>Why evaluate a tree? </strong>The first reason is that <strong>tree structure is unstable</strong>, this is further discussed in the pro and cons later. Moreover, <strong>a tree can be easily OVERFITTING</strong>, which means a tree (probably a very large tree or even a fully grown tree) focus too much on the data and capture relationships and noise that are invalid when predict new data, leading to poor predictive power we won’t desire.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*EQcQ3xXKdIWNZJTi7W1wbA.png" /><figcaption>Sample: A smaller tree</figcaption></figure><p>There are two major ways to achieve a smaller gap in performance between training set and testing set (new dataset). Firstly, we can stop the tree growth before it’s overfitting, ending up with a tree with less terminal nodes and splits. The other way is to prune the fully grown tree back to a smaller one with a cost-complexity function in the algorithm. Details and Python code are as follows.</p><h4>Grid Search: fine-tuning tree parameters</h4><p>It’s not easy to determine to what depth or number of splits we can develop the tree so that the predictive power can boost. One way to solve this is to try multiple different combinations of them, which is called <strong>grid search</strong>. There are a list of parameters in the DecisionTreeClassifier() from sklearn. The frequently used ones are <strong>max_depth, min_samples_split, and min_impurity_decrease</strong> (click <a href="https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html">here</a> to check out more explanations).</p><pre># using GridSearchCV to fine tune method parameters<br># Start with an initial guess for parameters<br>param_grid = {<br> ‘max_depth’:[5,10,20,],<br> ‘min_samples_split’:[20,40,60,80],<br> ‘min_impurity_decrease’: [0.0001, 0.0005, 0.001, 0.005, 0.01]<br>}</pre><pre>gridSearch = GridSearchCV(DecisionTreeClassifier(random_state=1), param_grid, cv=5, n_jobs=1)<br>gridSearch.fit(train_x, train_y)</pre><pre>print(‘Initial score: ‘, gridSearch.best_score_)<br>print(‘Initial parameters: ‘, gridSearch.best_params_)</pre><pre>#---------------------------------------------------------------</pre><pre># Adapt grid based on result from initial grid search<br>param_grid = {<br> &#39;max_depth&#39;: list(range(3,12)), <br> &#39;min_samples_split&#39;: list(range(15, 35)), <br> &#39;min_impurity_decrease&#39;: [x/10000 for x in range(1, 900, 5)], <br>}<br>gridSearch = GridSearchCV(DecisionTreeClassifier(random_state=1), param_grid, cv=5, n_jobs=-1)<br>gridSearch.fit(train_x, train_y)</pre><pre>print(&#39;Improved score: &#39;, gridSearch.best_score_)<br>print(&#39;Improved parameters: &#39;, gridSearch.best_params_)<br>bestClassTree = gridSearch.best_estimator_</pre><pre># fit the final model with best parameters: {&#39;max_depth&#39;: 7, &#39;min_impurity_decrease&#39;: 0.0001, &#39;min_samples_split&#39;: 15}</pre><pre>prunedtree = DecisionTreeClassifier(random_state = 1, max_depth=7, min_impurity_decrease=0.0001, min_samples_split=15)<br>prunedtree.fit(train_x, train_y)</pre><pre>plotDecisionTree(prunedtree, feature_names=train_x.columns)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kUsf5Z2d1TEaY-s_kyDcVQ.png" /><figcaption>The smaller tree after parameter-tuning with grid search</figcaption></figure><p><strong>Is there a way to determine the range of parameters so that the optimal choice could be covered with the best probability? (</strong>Answered by Professor Noah Giansiracusa<strong>)</strong></p><blockquote>Practically, decision tree is one of the algorithms that can be trained quickly, therefore it’s fine to start with a broad parameter range and a fairly large step size and conduct grid search. Then we can zoom in to a sub-range where we think the better values are located and perform another grid search with a smaller step size.</blockquote><blockquote>Having said that, there are a few technical methods commonly used in the context of deep learning, such as random walk type approaches and some Bayesian ones, for better search of hyperparameter values (a useful article <a href="https://towardsdatascience.com/intuitive-hyperparameter-optimization-grid-search-random-search-and-bayesian-search-2102dbfaf5b">here</a>).</blockquote><h4>Cost-Complexity Function with Cross Validation</h4><p>Tree pruning is a popular method in CART. The idea is simply to let the tree gown fully and then prune it back to a smaller but efficient tree.</p><blockquote>More specifically, the CART algorithm uses a cost-complexity function that balances tree size (complexity) and misclassification error (cost) in order to choose tree size.</blockquote><p><strong>CC(T) = err(T) + αL(T)</strong></p><p>α is the cost-complexity parameter in the penalty term (tree size). When α = 0, the tree grows fully and overfit the data, when α =1, the tree is just a single node and hence underfit the data. The process is that starting from α = 0, we slowly increase it to 1 to fit trees at each stage. For each tree and its corresponding α, we use cross-validation to evaluate the tree, then compute the average errors across all different splits. We choose the α complexity parameter for which the CV error is minimal. And use the α and all the data we have grow a new tree.</p><p>There is no such a shortcut function currently in Python to implement the above process. So I applied a loop function to incorporate the necessary steps.</p><pre># prune the tree with cost complexity pruning — Alpha<br>path = fulltree.cost_complexity_pruning_path(train_x, train_y)<br>alphas, impurities = path.ccp_alphas, path.impurities</pre><pre>mean, std = [], []<br>for i in alphas:<br> tree = DecisionTreeClassifier(ccp_alpha=i, random_state=0)<br># 5 fold cross validation for each alpha value<br> scores = cross_val_score(tree, x, y, cv=5)<br> mean.append(scores.mean())<br> std.append(scores.std())<br># keep a record of the values of alpha, mean accuracy rate, standard deviation of accuracies<br>eva_df = pd.DataFrame({‘alpha’: alphas, ‘mean’: mean, ‘std’: std})<br>eva_df = eva_df.sort_values([‘mean’], ascending = False)<br>eva_df.head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*UT1n4Zo5fsWqe-aKvEkN2w.png" /><figcaption>Partial evaluation scores after CV</figcaption></figure><p>It looks like the model with the best accuracy performance has α = 0.000444. It also has a lower standard deviation, meaning the accuracy scores are less variant, or more stable than that from models under other α values.</p><pre># fit the pruned tree - cv<br>prunedtree_cv = DecisionTreeClassifier(ccp_alpha=eva_df.iloc[4, 0], random_state=0)<br>prunedtree_cv.fit(train_x, train_y)</pre><pre>classificationSummary(train_y, prunedtree_cv.predict(train_x))<br>classificationSummary(val_y, prunedtree_cv.predict(val_x))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xtajP6s3nQz3a8yBsF_8cg.png" /><figcaption>The final tree after pruning with cost-complexity function</figcaption></figure><h3>Pros and Cons about Decision Tree</h3><h4>Pros:</h4><blockquote>No need for transformation of variables, i.e. no need for normalization or standardization.</blockquote><blockquote>Variable subset selection is automatic since it is part of the split selection.</blockquote><blockquote>Trees are also intrinsically robust to outliers, since the choice of a split depends on the ordering of values and not on the absolute magnitudes of these values.</blockquote><blockquote>Without having to impute values or delete records with missing values.</blockquote><blockquote>Transparent rules that they generate.</blockquote><h4>Cons:</h4><blockquote>Sensitive to changes in the data, and even a slight change can cause very different splits!</blockquote><blockquote>Computational expensive, since it requires a large dataset;</blockquote><blockquote>In “favor” predictors with many potential split points. This includes categorical predictors with many categories and numerical predictors with many different values. Such predictors have a higher chance of appearing in a tree.</blockquote><blockquote>Nonlinear and nonparametric, not assume any relationship between predictors and the outcome. Classification trees are useful classifiers in cases where horizontal and vertical splitting of the predictor space adequately divides the classes. But consider, for instance, a dataset with two predictors and two classes, where separation between the two classes is most obviously achieved by using a diagonal line.</blockquote><h4>To find everything about the code in this article, refer to my Github <a href="https://github.com/joannzhang00/3-methods-to-prune-a-classification-tree">here</a>.</h4><h3>Reference</h3><p><a href="https://scikit-learn.org/stable/auto_examples/tree/plot_cost_complexity_pruning.html">https://scikit-learn.org/stable/auto_examples/tree/plot_cost_complexity_pruning.html</a><br><a href="https://www.analyticsvidhya.com/blog/2020/10/cost-complexity-pruning-decision-trees/">https://www.analyticsvidhya.com/blog/2020/10/cost-complexity-pruning-decision-trees/</a><br><a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html">https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html</a><br><a href="https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html">https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html</a><br><a href="https://scikit-learn.org/stable/modules/cross_validation.html">https://scikit-learn.org/stable/modules/cross_validation.html</a><br><a href="https://www.dataminingbook.com/book/python-edition">https://www.dataminingbook.com/book/python-edition</a></p><p>My LinkedIn: <a href="https://www.linkedin.com/in/joannzhang1818/">https://www.linkedin.com/in/joannzhang1818/</a></p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2e45e33a1a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>