Thuta Learning
IntermediateData & Databasesintermediate

Decision Trees

Relax. We'll talk through this in plain words — no textbook voice.

What you'll walk away with

  • Understand Decision Trees, without any of the intimidation
  • Be able to run scikit-learn code yourself
  • Be able to apply this concept immediately in a real project

Let's think about it this way for a second

A Decision Tree is a tree structure that splits data using a series of questions (e.g. 'age > 30?') until it reaches a leaf node and makes a decision — because it's human-readable (unlike, say, Linear Regression's coefficients), you can clearly explain 'why this prediction was made'. If you don't limit the tree's depth (the number of question layers), it can grow deep enough to 'memorize' the training data (overfitting risk) — you limit this with the `max_depth` parameter.

Let's connect it to a real scenario

Writing `from sklearn.tree import DecisionTreeClassifier; model = DecisionTreeClassifier(max_depth=5); model.fit(X_train, y_train)` limits the tree depth to 5 layers, keeping overfitting in check — running `from sklearn.tree import plot_tree; plot_tree(model)` lets you view the tree structure as a visual diagram, clearly showing which feature is split at which threshold.

Let's look at it together

python
from sklearn.tree import DecisionTreeClassifier, plot_tree
import matplotlib.pyplot as plt

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

print(f"Accuracy: {model.score(X_test, y_test):.2f}")

# Visualize the tree structure
plot_tree(model, feature_names=X.columns, filled=True)
plt.show()
You should see
Accuracy: 0.84

5-minute try-it

Train a Decision Tree Classifier on a sample dataset, setting `max_depth` to 2, 5, and None (unlimited) respectively, and compare the accuracy — observe what happens when the depth gets too large.

A quick word of caution

For use cases where interpretability (being able to clearly explain the decision) is a priority — like loan approval, medical decisions, or heavily regulated industries — a Decision Tree can be a better fit than a black-box algorithm like a Neural Network.

Easy traps

  • Training a tree with unlimited depth, without setting `max_depth` — you might get 100% training accuracy, but test accuracy can drop (overfitting)
  • Assuming a single Decision Tree's result is the final word — a single tree tends to be unstable (a small change in the data can noticeably change the tree structure); Random Forest (covered in the Advanced chapter) addresses this weakness

Now try it yourself

Train a Decision Tree Classifier on a sample dataset, setting `max_depth` to 2, 5, and None (unlimited) respectively, and compare the accuracy — observe what happens when the depth gets too large.

You'll know it worked when: Accuracy: 0.84

Decision Trees | Thuta Learning