Decision Tree Classifier

A Decision Tree Classifier predicts outcomes by learning a series of if-else questions about the features, forming a flowchart-like structure that leads to a final class label.

How It Works

Is Income > 50000?
+-- Yes: Is Age > 30?
|         +-- Yes: Class = "Buys"
|         +-- No:  Class = "Doesn't Buy"
+-- No:  Class = "Doesn't Buy"

Implementing in Python

import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split

df = pd.DataFrame({
    "Income": [20000, 25000, 40000, 45000, 60000, 65000, 80000, 90000],
    "Age": [22, 45, 25, 50, 28, 55, 30, 35],
    "Buys": [0, 0, 0, 1, 1, 1, 1, 1]
})

X = df[["Income", "Age"]]
y = df["Buys"]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)

model = DecisionTreeClassifier(max_depth=3, random_state=42)
model.fit(X_train, y_train)

print(model.predict(X_test))

Splitting Criteria

At each step, the tree chooses the feature and threshold that best separates the classes, commonly measured using Gini impurity or entropy (information gain).

Decision Trees are easy to interpret and visualize, but they can overfit easily if allowed to grow too deep without constraints like max_depth.

Coming Up Next

Next, you'll take a closer look at the individual nodes that make up a Decision Tree.

How a Split Is Chosen, with Numbers

Gini impurity measures how mixed a group is. For a node, it is 1 minus the sum of the squared class proportions. A pure node, where every sample has the same label, has a Gini of 0.

Take 10 customers: 6 buy and 4 do not. The starting Gini is 1 - (0.6² + 0.4²) = 1 - (0.36 + 0.16) = 0.48.

Now test the split "Income > 50000":

  • Left group (income 50000 or less): 4 customers, 1 buys, 3 do not. Gini = 1 - (0.25² + 0.75²) = 0.375.
  • Right group (income above 50000): 6 customers, 5 buy, 1 does not. Gini = 1 - (0.833² + 0.167²), roughly 0.278.
  • Weighted Gini after the split = 0.4 x 0.375 + 0.6 x 0.278, roughly 0.317.

The impurity drops from 0.48 to about 0.32, so this split is useful. The algorithm tries many features and thresholds, keeps the one with the biggest drop, and repeats inside each child node until a stopping rule is reached.

Inspecting and Controlling the Tree

One big advantage of trees is that you can read the learned rules directly.

from sklearn.tree import export_text
from sklearn.metrics import accuracy_score

print(export_text(model, feature_names=["Income", "Age"]))
print("Test accuracy:", accuracy_score(y_test, model.predict(X_test)))
print("Feature importance:", dict(zip(X.columns, model.feature_importances_)))

To limit overfitting, scikit-learn offers several controls besides max_depth:

  • min_samples_split: a node needs at least this many samples before it can split.
  • min_samples_leaf: every leaf must keep at least this many samples.
  • max_leaf_nodes: caps the total number of leaves.
  • ccp_alpha: cost-complexity pruning, which trims branches that add little value.
  • class_weight="balanced": helps when one class is much rarer than the other.

Pick these values with cross-validation, for example using GridSearchCV, rather than by guessing.

When a Tree Is the Right Choice

Choose a single decision tree when you need a model that people can follow, such as explaining a loan or eligibility decision. Trees handle numeric and categorical-style features, need no feature scaling, and capture non-linear rules naturally.

If raw accuracy matters more than readability, ensembles usually win. Random Forest averages many trees to reduce variance, and gradient boosting builds trees one after another to correct earlier errors.

Common Mistakes

  • Leaving the tree unconstrained and celebrating near-perfect training accuracy.
  • Judging the model on a tiny test set, like the demo split above; use cross-validation on real data.
  • Reading feature importance as cause and effect.
  • Forgetting that small changes in data can produce a very different tree.

Ready to Master Data Science?

Join Uncodemy's Data Science Course and build real, job-ready skills with expert mentors.

Explore Course