Python Tutorial

Decision Tree

A flowchart-like model that splits data on feature thresholds to make transparent, rule-based predictions.

How a Decision Tree Works

A decision tree asks a sequence of yes/no questions about the features. Each internal node tests one feature against a threshold; each leaf holds a prediction. The algorithm greedily chooses the split that best separates the classes, measured by Gini impurity or entropy (information gain).

Trees handle numeric and categorical data, need no feature scaling, and are easy to interpret — you can read the exact rules that led to a prediction.

Building a Classifier

import pandas as pd
from sklearn.tree import DecisionTreeClassifier

data = {
    "Age":       [36, 42, 23, 52, 43, 44, 66, 35, 52, 35],
    "Experience":[10, 12,  4, 4,  21, 14, 3,  14, 13, 5],
    "Rank":      [9,  4,   6, 4,  8,  5,  7,  9,  7,  9],
    "Go":        [1,  0,   0, 0,  1,  0,  1,  1,  1,  1],
}
df = pd.DataFrame(data)

X = df[["Age", "Experience", "Rank"]]
y = df["Go"]

tree = DecisionTreeClassifier(criterion="gini", random_state=0)
tree.fit(X, y)

print(tree.predict([[40, 10, 7]]))   # 1 = go, 0 = don't go

Reading the Rules

Export the learned rules as text or a diagram to explain the model.

from sklearn.tree import export_text, plot_tree
import matplotlib.pyplot as plt

print(export_text(tree, feature_names=list(X.columns)))

plt.figure(figsize=(10, 6))
plot_tree(tree, feature_names=X.columns, class_names=["No", "Go"], filled=True)
plt.show()

Controlling Overfitting

An unrestricted tree grows until every leaf is pure, memorizing noise. Prune it with hyperparameters:

ParameterEffect
max_depthLimit how many questions deep the tree can go
min_samples_leafRequire a minimum number of samples in each leaf
min_samples_splitOnly split nodes with enough samples
ccp_alphaCost-complexity pruning strength
tree = DecisionTreeClassifier(max_depth=3, min_samples_leaf=2, random_state=0)
tree.fit(X, y)

Feature Importance

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

Higher values mean the feature contributed more to reducing impurity across the tree.

Advanced: From Trees to Forests

A single tree is high-variance — small data changes reshape it. Averaging many trees trained on bootstrapped samples (a Random Forest) dramatically improves accuracy and stability. Gradient boosting builds trees sequentially to correct prior errors.

from sklearn.ensemble import RandomForestClassifier

forest = RandomForestClassifier(n_estimators=200, random_state=0)
forest.fit(X, y)
print(forest.predict([[40, 10, 7]]))

Best Practices

  • Limit depth or leaf size to prevent overfitting on small datasets.
  • Use DecisionTreeRegressor for continuous targets.
  • Prefer ensembles (Random Forest, Gradient Boosting) when accuracy matters more than a single readable rule set.
  • Evaluate on a held-out test set, not the training data.

Try It Yourself

Exercise 1: Train a depth-2 decision tree on the iris dataset and print its test accuracy.

Show solution
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
X, y = load_iris(return_X_y=True)
Xtr, Xte, ytr, yte = train_test_split(X, y, random_state=0)
tree = DecisionTreeClassifier(max_depth=2).fit(Xtr, ytr)
print(round(tree.score(Xte, yte), 3))

Exercise 2: Which hyperparameter most directly limits overfitting in a tree?

Show solution

max_depth (also min_samples_leaf) — shallower trees can't memorize noise.

📘 Real-World Deep Dive

Knowing <strong>ML Decision Tree (scikit-learn)</strong> well is what turns scikit-learn from a curiosity into a daily tool — you'll reach for it in nearly every real project.

Real-Life Scenario

An end-to-end usage of ML Decision Tree that you'd actually see in a data pipeline or analytics notebook.

Real-Life Example

from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
X, y = load_iris(return_X_y=True)
clf = DecisionTreeClassifier(max_depth=3, random_state=0).fit(X, y)
print("train score:", round(clf.score(X, y), 3))

Expected Output

(see source)

Common mistakes

  • fit expects numeric arrays; OneHotEncoder / LabelEncoder are easy to forget for categorical features.
  • Calling predict on a model trained on unscaled data and then scaling inputs at inference time silently degrades accuracy.
  • train_test_split(X, y) requires both arrays; train_test_split(X) for unsupervised learning slips past static checkers.
  • Treating ML Decision Tree as a black box without reading the docs — the API has subtle defaults that bite when you scale.

🚀 Performance & Best Practices

  • Wrap preprocessing + estimator in a Pipeline so fit / predict stay reproducible.
  • Use joblib / pickle for serialising models, not the entire Python state.
  • For > 100 k rows, switch to HistGradientBoostingClassifier or cuML.
  • When working with scikit-learn, prefer vectorised / batched operations over Python loops.

🧪 Try It Yourself

  1. Reproduce the snippet on a representative slice of your own data.
  2. Profile the snippet with cProfile or timeit and find the single biggest improvement.
  3. Generalise the snippet into a small, reusable function you can drop into future projects.

FAQ: Decision Tree

Common questions about this page.

What is Decision Tree?

Decision Tree is a Machine Learning lesson that explains decision tree in Python. A flowchart-like model that splits data on feature thresholds to make transparent, rule-based predictions. Copy the samples and run them in the Python editor. It is written for beginners who want a clear definition and working examples.

Should I run decision tree examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn decision tree in this Machine Learning Python lesson (Decision Tree).

How do I use decision tree in Python?

To use decision tree in Python, follow the examples on this StudyGrid page. Copy a snippet, run it in the browser, then Download and run it locally for better learning. Change the values and compare the output.

What is the syntax of decision tree?

This Decision Tree tutorial shows decision tree syntax with short Python examples. Use the code blocks in this lesson for the exact statements, then try them in your editor.

Decision Tree example for beginners

Yes. This page includes a beginner decision tree example you can copy and run. It is designed for searches such as "decision tree for beginners", "decision tree example", and "how to use decision tree".

What are common mistakes with decision tree?

Common decision tree mistakes include wrong syntax, mixing types, and skipping practice. Work through this Machine Learning chapter in order, run every example, and check the output before moving on.

Why should I learn decision tree?

Decision Tree is used in real Python work. Learning decision tree helps you write clearer programs and continue the Machine Learning tutorial on StudyGrid.

Is Decision Tree free to learn online?

Yes. You can learn decision tree free on StudyGrid (studygrid.in). This chapter is part of the Machine Learning path and includes examples, syntax, and next-step links.