Decision Tree in Python with scikit-learn
Train a tree of yes/no questions, print it with export_text, and limit its depth to stop it memorising.
- DecisionTreeClassifier and max_depth
- Reading the rules with export_text
- Spotting overfitting from train and test scores
petal width <= 0.75- class 0
petal length <= 4.75- class 1
- class 2
A tree of questions
The problem
Sometimes you need a model whose decisions you can explain to a person, step by step: why was this loan refused, why is this flower a versicolor?
Think of it like this
A decision tree works like the game of twenty questions. Each question splits the remaining possibilities in two, and the best questions come first. When the answer is clear, you stop and name the class.
fit(X_train, y_train)❓ Find the questions that split the classes bestmax_depth=2✋ Ask at most two questions in a rowexport_text(tree)📜 Print the questions as rulespredict(X_test)🌸 Follow the answers down to a classA decision tree splits the data again and again on the feature and threshold that best separate the classes, and predicts the majority class of the leaf a sample ends in.
Key points
- The first question is petal width (cm)
<=0.75: if yes, the flower is class 0. - Otherwise petal length (cm)
<=4.75 separates class 1 from class 2. - The depth-2 tree scores 0.956 on the test set.
- Without a limit the tree reaches depth 6 and 1.000 on the training data, a sign of memorising.
When should you use it?
- Models that must be explained to people.
- Data with a mix of numeric and category features.
- The building block of random forests and gradient boosting.
When not to use it
- When you need the best accuracy: a random forest is usually better.
- Small changes in the data can change a single tree a lot; average many trees for stability.
Example code
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, export_text
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.3, random_state=1, stratify=iris.target
)
# max_depth=2 keeps the tree small enough to read
tree = DecisionTreeClassifier(max_depth=2, random_state=0)
tree.fit(X_train, y_train)
print(f"Test accuracy (depth 2): {tree.score(X_test, y_test):.3f}")
print(export_text(tree, feature_names=list(iris.feature_names)))
deep = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
print(f"No depth limit: depth {deep.get_depth()}, train {deep.score(X_train, y_train):.3f}, test {deep.score(X_test, y_test):.3f}")
Result of running the code
Test accuracy (depth 2): 0.956
|--- petal width (cm) <= 0.75
| |--- class: 0
|--- petal width (cm) > 0.75
| |--- petal length (cm) <= 4.75
| | |--- class: 1
| |--- petal length (cm) > 4.75
| | |--- class: 2
No depth limit: depth 6, train 1.000, test 0.978
Code explanation
DecisionTreeClassifier(max_depth=2) may ask at most two questions in a row. export_text prints them: a petal width of 0.75 cm or less means class 0 (setosa), otherwise a petal length of 4.75 cm separates class 1 from class 2. Even this small tree scores 0.956 on the test set. Without a depth limit the tree grows to depth 6 and gets every training flower right (1.000), a sign it is memorising the training data; on this easy dataset the test score still holds at 0.978, but on noisier data an unlimited tree usually does worse.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change random_state and see how much the score moves.
- Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
- Try a different model or hyperparameter and compare the scores.
Common mistakes
Growing the tree without any limit
A full-depth tree fits the training data perfectly and often does worse on new data.
DecisionTreeClassifier().fit(X_train, y_train)
DecisionTreeClassifier(max_depth=3, random_state=0).fit(X_train, y_train)
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Gini Impurity Measure how mixed the labels in a group are, the score decision trees use to choose splits. Easy
- Information Gain Compute how much splitting on a feature reduces entropy, the criterion behind ID3 decision trees. Medium
Tools for this lesson
- Classification Basics: Softmax and k-Nearest Neighbors in PythonTurn scores into class probabilities with softmax, score them with cross-entropy and classify points with k-nearest neighbors.
- Jupyter Notebook Online: Run Python Cells in Your BrowserFree online Jupyter notebook: run Python cells with pandas, NumPy and Matplotlib, add Markdown text, open and download .ipynb files. No install, no account.
- pandas Online Compiler: Run pandas and NumPy in Your BrowserRun pandas and NumPy code online with nothing to install. NumPy, pandas, SciPy, Matplotlib and scikit-learn are ready in the free Python editor.