Decision trees
Cover security and operational gates
A decision tree predicts by testing one feature threshold at each node and following branches until a leaf returns a class.
Before you start
Why this matters
Before running anything, predict one observable result from the case: study hours and practice-test count predict readiness, and each prediction must have a traceable path. Write the prediction beside the command or code line that should cause it. This makes the session an experiment rather than a transcription exercise.
1Learn the idea
Read
Operate the chapter step
Operational quality includes safe inputs, predictable resources, and recoverable changes. Readable rules are not automatically fair. Audit proxy features, missing-value handling, and outcome rates across relevant groups. Version the feature schema because positional drift may not raise an error. Review what is written to disk or logs, which dependencies execute, and what another user can alter.
Read every command or statement before running it. The examples deliberately expose intermediate state so a surprising result has somewhere concrete to point.
Read
Run the working example
from sklearn.tree import DecisionTreeClassifier, export_text
X = [[1, 0], [2, 1], [4, 1], [5, 3], [6, 2], [7, 4]]
y = ["needs-practice", "needs-practice", "almost", "ready", "ready", "ready"]
tree = DecisionTreeClassifier(max_depth=2, min_samples_leaf=1, random_state=7)
tree.fit(X[:5], y[:5])
print(tree.predict([[7, 4]])[0])
print(export_text(tree, feature_names=["hours", "practice_tests"]))
Expected evidence:
ready
|--- hours <= 3.00
| |--- class: needs-practice
|--- hours > 3.00
| |--- hours <= 4.50
| | |--- class: almost
| |--- hours > 4.50
| | |--- class: ready
The output may include version-specific details such as hashes, paths, fitted thresholds, or final decimal places. Compare the structural facts described here rather than copying placeholders. If the structure differs, stop and inspect the earliest unexpected line.
Read
Read it line by line
- the classifier receives two features in a fixed positional order.
max_depth=2limits the number of learned questions along a path.fitsearches splits using only the first five rows.- the final row is held out;
export_textexposes the learned thresholds instead of relying on a diagram.
These lines form one chain: numeric rows [hours, practice_tests] with readiness labels becomes class predictions, a readable tree, and held-out accuracy. Change only one input first. When several values change together, you cannot tell which change caused the new behavior.
Read
Common errors and fixes
- First failure: reversing feature order at prediction time silently changes the question each column answers. Re-run the smallest command that proves the repair.
- Second failure: an unconstrained tree can create leaves containing one training row and memorize noise. Preserve the failing input as a test when it represents a realistic mistake.
- Misleading success: text categories in numeric columns require consistent encoding rather than arbitrary integer labels. A clean-looking final line cannot cancel contradictory intermediate evidence.
When debugging, copy the exact error text and inspect names, paths, shapes, types, and versions. Explain the cause in one sentence before changing code. That discipline prevents a guessed repair from creating a second defect.
Read
Evidence for this stage
The input contract is numeric rows [hours, practice_tests] with readiness labels. The visible result is class predictions, a readable tree, and held-out accuracy.
For the current operate step, save the smallest useful evidence: the relevant command, its output, and the input that produced it. Do not use a screenshot as the only record when text can be copied and searched. Keep generated artifacts separate from source inputs so rerunning the example does not destroy the evidence it is meant to evaluate.
Evaluate several held-out rows with a confusion matrix, compare training and test accuracy, and inspect leaf sample counts. A large training-test gap or tiny leaves indicates overfitting.
Read
Reflect on the result
Return to your opening prediction. Mark it correct or rewrite it with the condition you missed. Then explain the difference between a successful execution and a trustworthy result for this specific example.
Continue learning · glossary & guides
- Which line or command establishes the current step's most important fact?
- What output would reveal that reversing feature order at prediction time silently changes the question each column answers?
- Can a new user reproduce a depth-limited classification tree with held-out accuracy and printed decision rules from the stated setup?