Intermediate Data Science

Decision Trees

Author

Joanna Bieri
DATA201

Intermediate Data Science

Important Information

Today’s Reading

Introduction to Machine Learning with Python, Chapter 2.3.5 - Decision Trees.

Career Reading

Build a Career in Data Science, 5.1 and 5.2 Finding the Right Job. Read it and take notes. We discuss portfolios, resumes and cover letters together on Tuesday 11/17.

Final Project

Your Project Proposal and Exploratory Data Analysis is due Tuesday 11/10 at 11:59pm. It is individual work, on Canvas and in your sandbox. See the Final Project Information page.

Video

Video - Introduction to Decision Trees

NOTE: The video is from last year, so a few things are different in these notes. In the video I pick the depth and alpha by looking at the test set. In the notes we use a validation set instead, which is the better way to do it! The regression example in the video used random data with no seed, so your numbers will not match the video. Also the video calls Iris “day 12”, it is Day 11 this year, and around 21 minutes I scroll up to a cost complexity printout that is no longer in the notes (we get to pruning later).


Continue with Supervised Learning

So far we have KNN, linear and logistic regression (with scaling and regularization), and Naive Bayes. Today we add one more supervised model that you will see EVERYWHERE: the decision tree. A tree asks a series of yes or no questions about the features, and you can draw it and read it. Trees can do classification and regression, and we will see the same over and underfitting story that we saw with KNN and polynomial regression.

# NOTE - This list of package imports is getting long
# In a professional setting you would only want to 
#      import what you need!
# I had chatGPT break the packages into groups here

# ============================================================
# Basic packages
# ============================================================
import os                             # For file and directory operations
import numpy as np                    # For numerical computing and arrays
import pandas as pd                   # For data manipulation and analysis

# ============================================================
# Visualization packages
# ============================================================
import matplotlib.pyplot as plt        # Static 2D plotting
from matplotlib.colors import ListedColormap
import seaborn as sns                  # Statistical data visualization built on matplotlib

# Interactive visualization with Plotly
import plotly.express as px
from plotly.subplots import make_subplots
import plotly.io as pio
pio.renderers.default = 'notebook_connected'   # Set renderer for interactive output in notebooks

# ============================================================
# Scikit-learn: Core utilities for model building and evaluation
# ============================================================
from sklearn.model_selection import train_test_split    # Train/test data splitting
from sklearn.preprocessing import PolynomialFeatures, MinMaxScaler, StandardScaler  # Feature transformations and scaling
from sklearn.metrics import (                            # Model evaluation metrics
    mean_squared_error, r2_score, accuracy_score, 
    precision_score, recall_score, confusion_matrix, 
    classification_report
)

# ============================================================
# Scikit-learn: Linear and polynomial models
# ============================================================
from sklearn.linear_model import LinearRegression, LogisticRegression, Ridge, Lasso
from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor       # For KNN

# ============================================================
# Scikit-learn: Synthetic dataset generators
# ============================================================
from sklearn.datasets import make_classification, make_regression

# ============================================================
# Scikit-learn: Naive Bayes models
# ============================================================
from sklearn.naive_bayes import GaussianNB, BernoulliNB, MultinomialNB

# ============================================================
# Scikit-learn: Decision Trees
# ============================================================
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor, plot_tree

Decision Trees

Today we are going to talk about Decision Trees (for classification and regression). Decision Trees use a series of splits to recursively split feature space into regions that divide up target variables. They are interpretable, meaning we can see how they are making their decisions, and they do a good job of capturing nonlinear relationships.

Decision Trees work by recursively splitting the data using a feature and threshold that best separate the target variable.
At each step, the algorithm chooses the split that reduces variance (for regression) or minimizes impurity (for classification), where impurity is commonly measured as one of:

Gini Impurity

Gini impurity measures how often a randomly chosen sample from a node would be incorrectly labeled if it were labeled according to the distribution of classes in that node.

Formula:

\[ G = 1 - \sum p_k^2 \]

where p_k is the proportion of class k in the node.

Example:
If a node has
- 80% of samples from class A → p_A = 0.8
- 20% of samples from class B → p_B = 0.2

Then

\[ G = 1 - (0.8^2 + 0.2^2) = 1 - (0.64 + 0.04) = 0.32 \]

That means the node is somewhat impure, since it contains a mix of both classes.
If all samples were from class A (100%), then

\[ G = 1 - (1^2) = 0 \]

A Gini impurity of 0 means perfect purity (only one class present).

Entropy

Entropy comes from information theory.
It measures uncertainty or how unpredictable the class labels are in a node.

Formula:

\[ H = -\sum_k p_k \log_2(p_k) \]

If all samples belong to one class → H = 0 (no uncertainty).
If classes are evenly mixed (50/50) → H = 1 (maximum uncertainty).

Example:
For 80% A and 20% B:

\[ H = -(0.8 \log_2 0.8 + 0.2 \log_2 0.2) \approx 0.72 \]

For a perfectly even mix (50% A, 50% B):

\[ H = -(0.5 \log_2 0.5 + 0.5 \log_2 0.5) = 1 \]


Comparing Gini and Entropy

Situation Gini Entropy Purity
100% one class 0.0 0.0 Pure
80/20 mix 0.32 0.72 Somewhat impure
50/50 mix 0.50 1.00 Very impure

Both measures behave similarly. They are just two different ways to quantify impurity.

  • Gini is slightly faster to compute.
  • Entropy has a stronger theoretical connection to information theory.

In practice, they usually lead to very similar trees.

What the Tree Does

At each node, the Decision Tree tries every possible split and picks the one that results in the biggest drop in impurity.
This process repeats recursively until the stopping rules (like max_depth) are met.

NOTE - Trees do not need scaling! On Day 13 we said ALWAYS SCALE YOUR FEATURE DATA, because KNN uses distances and regularization uses the size of the coefficients. A tree only ever asks one question about one feature at a time, like “is feature 1 <= 0.47?”. If you rescale that feature, the tree just moves the cutoff to the rescaled number and makes the exact same split. So scaling does not hurt a tree, but it does not help either.

Decision Tree for Classification

Decision tree boundaries are piecewise-rectangular, showing how trees partition the space with axis-aligned splits.

X, y = make_classification(
    n_samples=200, n_features=2, n_informative=2, n_redundant=0,
    n_clusters_per_class=1,n_classes=3, random_state=42
)

# Create the plot
plt.figure(figsize=(8, 6))
plt.scatter(X[y == 0, 0], X[y == 0, 1], color='steelblue', label='Class 0', alpha=0.7)
plt.scatter(X[y == 1, 0], X[y == 1, 1], color='darkorange', label='Class 1', alpha=0.7)
plt.scatter(X[y == 2, 0], X[y == 2, 1], color='darkred', label='Class 2', alpha=0.7)

# Add labels and legend
plt.title("Synthetic  Classification Data")
plt.xlabel("Feature 1")
plt.ylabel("Feature 2")
plt.legend()
plt.grid(True, linestyle='--', alpha=0.6)
plt.show()

Remember Day 13: when we are going to tune a hyperparameter (here the depth of the tree), we split our data into a Training Set, a Validation Set, and a Testing Set. We choose the depth using the validation set, and we only get to use the test set once, at the very end.

random_seed = 42
# First split: hold out test data
X_train, X_test_full, y_train, y_test_full = train_test_split(
    X, y, test_size=0.2, random_state=random_seed
)

# Second split: create a validation set from the testing data
X_test, X_val, y_test, y_val = train_test_split(
    X_test_full, y_test_full, test_size=0.5, random_state=random_seed
)
# (Hold out data so that final proportions are 80% train / 10% val / 10% test)

print(f"Train: {len(X_train)}, Validation: {len(X_val)}, Test: {len(X_test)}")
Train: 160, Validation: 20, Test: 20
clf = DecisionTreeClassifier(max_depth=1, 
                             criterion='gini', 
                             random_state=42)
clf.fit(X_train, y_train)
DecisionTreeClassifier(max_depth=1, random_state=42)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
# Define grid
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02),
                     np.arange(y_min, y_max, 0.02))

Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)

# Plot
cmap=ListedColormap(['steelblue', 'darkorange', 'darkred'])
labels = ['Class 0 ','Class 1','Class 2']
plt.figure(figsize=(8,6))
plt.contourf(xx, yy, Z, alpha=0.2, 
             cmap=cmap)
plt.scatter(X_train[:, 0], X_train[:, 1], 
            c=y_train, cmap=cmap,alpha=0.7)
plt.title("Decision Tree Classifier Decision Boundaries")
plt.xlabel("Feature 1")
plt.ylabel("Feature 2")
plt.grid(True, linestyle='--', alpha=0.6)
plt.show()

y_pred = clf.predict(X_val)
print(f"Accuracy: {accuracy_score(y_val, y_pred):.3f}")
Accuracy: 0.600
plt.figure(figsize=(12, 6))
plot_tree(clf,
          filled=True,
          feature_names=["Feature 1", "Feature 2"],
          class_names=["Class 0", "Class 1", "Class 2"],
          rounded=True,
          fontsize=10)
plt.title("Decision Tree Structure")
plt.show()

You Try

Change max_depth in the classifier above to 2, then 3, then 5, and rerun the three cells. How does the picture of the decision boundary change? How does the tree drawing change? What happens to the accuracy on the validation data?

Let’s let a for loop try the depths for us.

# What depth should I use
accuracies=[]
depths = [1,2,3,4,5]
for d in depths:
    clf = DecisionTreeClassifier(max_depth=d, 
                             criterion='gini', 
                             random_state=42)
    clf.fit(X_train, y_train)
    y_pred = clf.predict(X_val)
    acc=accuracy_score(y_val, y_pred)
    accuracies.append(acc)
    print(f"Accuracy: {acc:.3f}")

plt.plot(depths,accuracies,'r')
plt.xlabel("Max Depth")
plt.ylabel("Accuracy on Validation Data")
plt.grid()
plt.show()
Accuracy: 0.600
Accuracy: 0.850
Accuracy: 0.850
Accuracy: 0.800
Accuracy: 0.750

A depth of 2 or 3 gets 0.85 on the validation data. A depth of 5 does worse (0.75), even though a deeper tree always does better on the training data. That should look familiar… it is overfitting!

You Try

Change criterion='gini' to criterion='entropy' in the loop above. Do you get different trees? Different accuracies? (Remember: in practice the two usually lead to very similar trees.)

The one test at the end

We pick the simplest tree with the best validation accuracy, a depth of 2. NOW we get to use the test set, once.

# Our final choice: depth 2. Train it and use the test set ONE time.
clf = DecisionTreeClassifier(max_depth=2,
                             criterion='gini',
                             random_state=42)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print(f"Accuracy on the test set: {accuracy_score(y_test, y_pred):.3f}")
Accuracy on the test set: 0.950

Decision Tree for Regression

X, y = make_regression(n_samples=200, n_features=1, noise=10, random_state=42)

X_train, X_test, y_train, y_test = train_test_split(X, y, 
                                                    test_size=0.2, 
                                                    random_state=42)
tree_reg = DecisionTreeRegressor(max_depth=3, random_state=0)
tree_reg.fit(X_train, y_train)
y_pred = tree_reg.predict(X_test)

r2 = r2_score(y_test, y_pred)
mse = mean_squared_error(y_test, y_pred)
print(f"R² score: {r2:.3f}")
print(f"Mean Squared Error: {mse:.3f}")
R² score: 0.930
Mean Squared Error: 529.467
# Sort for smooth plotting
X_sorted = np.sort(X_test, axis=0)
y_smooth = tree_reg.predict(X_sorted)

plt.figure(figsize=(8,6))
plt.scatter(X_test, y_test, color="gray", alpha=0.6, label="Test Data")
plt.plot(X_sorted, y_smooth, color="red", linewidth=2, label="Tree Prediction")
plt.title("Decision Tree Regression Fit")
plt.xlabel("Feature")
plt.ylabel("Target")
plt.grid(True, linestyle='--', alpha=0.6)
plt.legend()
plt.show()

plt.figure(figsize=(12, 6))
plot_tree(tree_reg,
          filled=True,
          feature_names=["Feature 1"],
          rounded=True,
          fontsize=10)
plt.title("Decision Tree Structure")
plt.show()

Controlling Tree Complexity

Increasing tree depth reduces training error but can lead to overfitting. We can use pruning (ccp_alpha) to select an appropriate complexity level. When building a Decision Tree, sklearn can prune it after growing, meaning it removes branches that provide little improvement in predictive power.

By default there is no pruning and typically values are very small between 0 and 0.1.

np.random.seed(42)   # so we all get the same random data
X = np.sort(5 * np.random.rand(200, 1), axis=0)
# Nonlinear target with noise
y = np.sin(X).ravel() + np.random.normal(scale=0.4, size=200)

random_seed = 42
# First split: hold out test data
X_train, X_test_full, y_train, y_test_full = train_test_split(
    X, y, test_size=0.2, random_state=random_seed
)

# Second split: create a validation set from the testing data
X_test, X_val, y_test, y_val = train_test_split(
    X_test_full, y_test_full, test_size=0.5, random_state=random_seed
)
# (Hold out data so that final proportions are 80% train / 10% val / 10% test)

print(f"Train: {len(X_train)}, Validation: {len(X_val)}, Test: {len(X_test)}")


plt.figure(figsize=(8,6))
plt.scatter(X, y, color="gray", alpha=0.6, label="Data")
plt.title("Regression Data")
plt.xlabel("Feature")
plt.ylabel("Target")
plt.grid(True, linestyle='--', alpha=0.6)
plt.legend()
plt.show()
Train: 160, Validation: 20, Test: 20

Decisions with no pruning and no max-depth

alpha = 0
tree_reg = DecisionTreeRegressor(random_state=42)
tree_reg.fit(X_train, y_train)

plt.figure(figsize=(12, 6))
plot_tree(tree_reg,
          filled=True,
          feature_names=["Feature 1"],
          rounded=True,
          fontsize=10)
plt.title("Decision Tree Structure")
plt.show()

mse_train = mean_squared_error(y_train, tree_reg.predict(X_train))
mse_val = mean_squared_error(y_val, tree_reg.predict(X_val))

print(f'MSE on Training: {mse_train}')
print(f'MSE on Validation: {mse_val}')

R_train = r2_score(y_train, tree_reg.predict(X_train))
R_val = r2_score(y_val, tree_reg.predict(X_val))

print(f'R2 on Training: {R_train}')
print(f'R2 on Validation: {R_val}')
MSE on Training: 0.0
MSE on Validation: 0.2557411824510989
R2 on Training: 1.0
R2 on Validation: 0.555320540253107

We had ZERO error on our training data and an R2 of 1!!! What does this mean?

X_sorted = np.sort(X_val, axis=0)
y_smooth = tree_reg.predict(X_sorted)

plt.figure(figsize=(8,6))
plt.scatter(X_val, y_val, color="gray", alpha=0.6, label="Validation Data")
plt.plot(X_sorted, y_smooth, color="red", linewidth=2, label="Tree Prediction")
plt.title("Decision Tree Regression Fit")
plt.xlabel("Feature")
plt.ylabel("Target")
plt.grid(True, linestyle='--', alpha=0.6)
plt.legend()
plt.show()

Clearly we are overfitting. We are memorizing the training data! This is clear from the difference in results between our training and validation data and also from the jaggedness of the prediction line.

IMPORTANT Remember that in general you will not be able to plot the decision lines or boundaries because typically your data is much higher dimensional than the examples that I am showing you here. This is why you MUST GET GOOD at interpreting the numerical measures of goodness of fit!!

Let’s visualize the decision boundaries. Every dashed line is a split point in the tree.

x_plot = np.linspace(0, 5, 500).reshape(-1, 1)
y_pred = tree_reg.predict(x_plot)

plt.figure(figsize=(10, 5))
plt.scatter(X_train, y_train, s=15, label="data")
plt.plot(x_plot, y_pred, lw=.5, label="tree prediction")

tree_struct = tree_reg.tree_
split_thresholds = tree_struct.threshold[tree_struct.feature >= 0]
# vertical lines at the split thresholds
for thr in split_thresholds:
    plt.axvline(thr, color="black", linestyle="dashed",lw=0.5, alpha=0.7)

plt.title("Regression Tree Decision Boundaries (Split Points)")
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.show()

path = tree_reg.cost_complexity_pruning_path(X_train, y_train)
for c in path.ccp_alphas:
    print(c)
0.0
5.079262239970905e-10
1.0158153378458934e-07
1.4809282561575876e-07
6.74972025099807e-07
1.0936103126784475e-06
1.0956965998953905e-06
4.044153180763894e-06
1.5168081677578715e-05
1.6388621833017362e-05
1.7096529612179585e-05
1.8009452240277253e-05
2.177096814712509e-05
2.1886054887054056e-05
2.217085720708639e-05
2.707544765862546e-05
2.8452006858079376e-05
2.893179887408642e-05
3.137272717401162e-05
3.3805858300063176e-05
3.91884744391148e-05
3.9912512253616885e-05
4.021521773659664e-05
5.0801805231256995e-05
6.479217325359304e-05
6.972439312817602e-05
7.020644097071923e-05
7.287084717391701e-05
8.347114225366049e-05
9.940232653043792e-05
9.959121595208894e-05
0.00010130588409533806
0.00010676334770434787
0.00011094252251339365
0.00012472429214782678
0.00012918720142103822
0.0001308230057888507
0.00015636670903183115
0.00017060881262057068
0.00017171200217971222
0.00017292373987931215
0.0001733175506676506
0.00018551508657949493
0.00019929152009092108
0.00020275667545674225
0.00021911002381321752
0.00022340835201850733
0.0002238190692329556
0.0002396920090306242
0.00024770380967909086
0.0002652160043141587
0.00031132921676165653
0.00031745001241101914
0.0003212913989180482
0.0003236172197655249
0.00033914230614051356
0.0003413624847557743
0.00034356726956170057
0.0003468443809596669
0.0003517446916628215
0.0003596669721554764
0.00040853532057293367
0.00044246525434388093
0.0004430415403353527
0.00044522720532398847
0.00045137742359974386
0.00045803334301945523
0.00046325478375693887
0.0004935273465073457
0.0005228228374845819
0.0005497703222312758
0.000616204575886714
0.0006501687488658703
0.0006657557084951617
0.0006852459403472131
0.0007403038550859477
0.0007542659954584322
0.0007826721022929185
0.0008778463812268161
0.0008847688723978954
0.0009290783444176938
0.0009495757729983383
0.0009647103362850602
0.0009722975181837082
0.0010351491631275115
0.001121980266676642
0.001135044900328974
0.001276280131569879
0.0013733672154105656
0.0014820540156104207
0.0015264764716166924
0.0015479351313603283
0.001701396985083337
0.001702660321281383
0.0017495399597978502
0.0018390069061650163
0.0018789546878149456
0.0019079316701135923
0.001911978259535545
0.0020527808510712887
0.002053442757824691
0.002122758000352185
0.0023067732613401577
0.002947365669942215
0.00336681464868163
0.003937191798790039
0.005203724214295845
0.008797865943492078
0.03373099207491103
0.0349378096738463
0.44089001766294844

Change \(\alpha\) to add pruning - regularization

Above we printed the values of the complexity cutoffs. This helps give a range for possible \(\alpha\) values.

alpha = .01

tree_reg = DecisionTreeRegressor(ccp_alpha=alpha,
                                 random_state=42)
tree_reg.fit(X_train, y_train)

plt.figure(figsize=(12, 6))
plot_tree(tree_reg,
          filled=True,
          feature_names=["Feature 1"],
          rounded=True,
          fontsize=10)
plt.title("Decision Tree Structure")
plt.show()

mse_train = mean_squared_error(y_train, tree_reg.predict(X_train))
mse_val = mean_squared_error(y_val, tree_reg.predict(X_val))

print(f'MSE on Training: {mse_train}')
print(f'MSE on Validation: {mse_val}')

R_train = r2_score(y_train, tree_reg.predict(X_train))
R_val = r2_score(y_val, tree_reg.predict(X_val))

print(f'R2 on Training: {R_train}')
print(f'R2 on Validation: {R_val}')
MSE on Training: 0.1310954942281057
MSE on Validation: 0.17553227270082639
R2 on Training: 0.8059546733832451
R2 on Validation: 0.6947867549346572
X_sorted = np.sort(X_val, axis=0)
y_smooth = tree_reg.predict(X_sorted)

plt.figure(figsize=(8,6))
plt.scatter(X_val, y_val, color="gray", alpha=0.6, label="Validation Data")
plt.plot(X_sorted, y_smooth, color="red", linewidth=2, label="Tree Prediction")
plt.title("Decision Tree Regression Fit")
plt.xlabel("Feature")
plt.ylabel("Target")
plt.grid(True, linestyle='--', alpha=0.6)
plt.legend()
plt.show()

Exploring depths

depths = range(1, 15)
mse_train = []
mse_val = []
diff = []
ccp_alpha=0
for d in depths:
    tree_reg = DecisionTreeRegressor(max_depth=d,
                                 random_state=42)
    tree_reg.fit(X_train, y_train)
    mtr = mean_squared_error(y_train, tree_reg.predict(X_train))
    mte = mean_squared_error(y_val, tree_reg.predict(X_val))
    mse_train.append(mtr)
    mse_val.append(mte)
    diff.append(mte-mtr)

plt.plot(depths, mse_train, 'o-',label='MSE train')
plt.plot(depths, mse_val, 'o-r',label='MSE validation')
plt.plot(depths, diff, 'o-k', label='MSE difference')
plt.xlabel("Max Depth")
plt.ylabel("MSE")
plt.title("Effect of Tree Depth on MSE")
plt.grid(True, linestyle='--', alpha=0.6)
plt.legend()
plt.show()

Here a tree depth of one has the smallest difference between the training and validation MSE (the validation MSE is even a little lower), but that tree is too simple, it is underfitting. A depth of 5 gives the lowest MSE on the validation data. But we also need to select alpha!

alphas = np.arange(0,.5,.01)
mse_train = []
mse_val = []
diff = []
ccp_alpha=0
for a in alphas:
    tree_reg = DecisionTreeRegressor(ccp_alpha=a,
                                 random_state=42)
    tree_reg.fit(X_train, y_train)
    mtr = mean_squared_error(y_train, tree_reg.predict(X_train))
    mte = mean_squared_error(y_val, tree_reg.predict(X_val))
    mse_train.append(mtr)
    mse_val.append(mte)
    diff.append(mte-mtr)

plt.plot(alphas, mse_train, '.-',label='MSE train')
plt.plot(alphas, mse_val, '.-r',label='MSE validation')
plt.plot(alphas, diff, '.-k', label='MSE difference')
plt.xlabel("alpha")
plt.ylabel("MSE")
plt.title("Effect of Alpha on MSE")
plt.grid(True, linestyle='--', alpha=0.6)
plt.legend()
plt.show()

It looks like an \(\alpha\) of .01 is best. But how do we really pick both \(\alpha\) and depth to be the best possible values?

The one test at the end

For now, let’s just pick the model with the lowest validation MSE that we found: the tree with a max depth of 5. NOW we use the test set, once.

# Our final choice: max_depth = 5. Train it and use the test set ONE time.
tree_reg = DecisionTreeRegressor(max_depth=5,
                                 random_state=42)
tree_reg.fit(X_train, y_train)

mse_test = mean_squared_error(y_test, tree_reg.predict(X_test))
R_test = r2_score(y_test, tree_reg.predict(X_test))
print(f'MSE on Testing: {mse_test}')
print(f'R2 on Testing: {R_test}')
MSE on Testing: 0.2721358388068471
R2 on Testing: 0.5832207563970588

The test MSE (about 0.27) is higher than the validation MSE was (about 0.15). With only 20 points in the validation set and 20 in the test set, these numbers bounce around a lot depending on which points land in which set. That is one of the reasons for cross-validation…

Cross-validation (coming soon, Days 20 and 21!)

So far we have been using simple for loops and one validation set to check which hyperparameters are best. There are much better ways to do this!

Cross-validation is a resampling technique used to estimate how well a model will generalize to unseen data. Instead of training the model once and evaluating it once, cross-validation repeatedly splits the data into training and validation sets in a systematic way.

It is one of the most important concepts in machine learning, especially for preventing overfitting.

Using Decision Trees for Feature Importance and Feature Engineering

Decision Trees don’t just make predictions, they also tell us which features are most important for those predictions.

This information is useful for: - Understanding what drives the model’s decisions
- Reducing dimensionality (removing unimportant features)
- Creating new features (interactions or transformations of important ones)

How Feature Importance Works

Each split in a decision tree is chosen to reduce impurity (for example, Gini impurity or entropy for classification, variance for regression).

The importance of a feature is calculated by looking at how much each split using that feature reduces impurity, averaged over all nodes where that feature is used.

For feature \(j\):

\[ \text{Importance}(j) = \frac{1}{T} \sum_{t \in T_j} \left( N_t \cdot \Delta I_t \right) \]

where:

  • \(T_j\) = set of nodes where feature \(j\) is used
  • \(N_t\) = number of samples reaching node \(t\)
  • \(\Delta I_t\) = impurity decrease (before split - after split)
  • \(T\) = all nodes in the tree

Finally, the importances are normalized to sum to 1.


Interpreting Feature Importance

  • Higher values mean the feature contributed more to reducing impurity.
  • Features with importance close to 0 likely didn’t help much in prediction.

This helps us identify which features matter most for our model.


Example: Using a Decision Tree for Feature Importance

We will reload the familiar Iris data set from earlier in the class. (Day 11 - Intro to ML)

from sklearn.datasets import load_iris

# Load a simple dataset
iris = load_iris()
X = pd.DataFrame(iris.data, columns=iris.feature_names)
y = iris.target

# Train a Decision Tree
tree = DecisionTreeClassifier(random_state=42, max_depth=3)
tree.fit(X, y)

# Get feature importances
importances = pd.Series(tree.feature_importances_, index=X.columns).sort_values(ascending=False)

# Display and plot
print(importances)

importances.plot(kind='bar', color='steelblue', title='Feature Importances (Decision Tree)')
plt.ylabel("Importance")
plt.show()
petal length (cm)    0.585616
petal width (cm)     0.414384
sepal width (cm)     0.000000
sepal length (cm)    0.000000
dtype: float64

Here we can see that petal length and width are the most important features. We could leave out sepal length and width and still get a really good prediction!

This can also be used for dimensionality reduction. In our Iris data, we started with four dimensions, but really we only need TWO! I can plot in two dimensions!

X.keys()
Index(['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)',
       'petal width (cm)'],
      dtype='str')
X.plot.scatter(x= 'petal length (cm)',
               y = 'petal width (cm)',
               c = y,
               colormap = 'viridis')
plt.grid()
plt.show()


Homework 15

The full assignment is in HW_day15.ipynb in your sandbox. You will build a classification tree on the Iris data and a regression tree on the California Housing data, explore depth and pruning, and look at feature importance.

Work the problems in your sandbox and push it, your sandbox is your backup. Your write-up notebook goes in Week09 of your team’s repo, along with Homework 16. Both are due Sunday 11/15 at 11:59pm.