smartyfy.mrindigi.com

Python Master Course V2 — 135. Decision Trees and Ensemble Models

Purpose and learning outcomes

Trees divide the input space into regions and predict within each region. Ensembles combine many trees to improve stability or correct remaining errors. We will compare a shallow tree, a random forest, and histogram gradient boosting on the same generated classification problem. The emphasis is a fair bounded comparison, not an assumption that a more complicated method must win.

  • Explain tree partitions and overfitting
  • Compare bagging and gradient-boosting approaches
  • Evaluate feature importance cautiously on held-out data

Prerequisites: 133–134: regression and classification.

Environment and run order

Use a dedicated Python 3.11 or 3.12 virtual environment. These exercises use local synthetic or bundled data; no account, API key, or dataset download is needed. The shell commands install free packages. Run the Python blocks in order in one lesson file; worked solutions continue from that file unless stated otherwise.

Shell

python -m venv .venv
# macOS/Linux: source .venv/bin/activate
# Windows PowerShell: .venv\Scripts\Activate.ps1
python -m pip install numpy pandas scikit-learn matplotlib joblib
python -m pip freeze > requirements-observed.txt

Understand the model and the evidence

A tree is a sequence of local questions

A decision tree might ask whether feature 2 exceeds a value, then ask another question in each resulting branch. A leaf predicts from the training observations that reach it. Deep trees can isolate tiny groups and memorize noise. max_depth and min_samples_leaf limit how fine those partitions become. Because partitions depend on thresholds, ordinary monotonic rescaling usually matters less than for distance-based or penalized linear models.

Bagging reduces instability through variation

A random forest trains trees on bootstrap samples and considers randomized feature subsets when choosing splits. Averaging their probability estimates can reduce the instability of an individual tree when errors are not perfectly correlated. More trees do not automatically remove systematic bias, bad labels, or leakage. A fixed n_jobs=1 prevents this small exercise from unexpectedly consuming every CPU core.

Boosting builds an additive correction

Gradient boosting builds models sequentially, each helping reduce the current loss. Histogram gradient boosting first bins continuous values, making split search efficient. Learning rate and iteration count interact: many small updates differ from a few aggressive updates. We explicitly disable its internal early stopping here so that the demonstration’s stated validation partition remains the visible comparison boundary.

Importance measures dependence, not causation

Permutation importance measures the drop in a selected score when one feature is shuffled on held-out rows. It asks how this fitted model relies on that information under the shuffling intervention, not what causes the outcome. Correlated columns can substitute for each other and appear individually unimportant. Shuffling can also create unrealistic feature combinations. Impurity-based importances have additional biases, so they should not be treated as unquestionable explanations.

Incremental worked example

1. Generate one comparison dataset

The synthetic data contain informative and redundant features with modest label noise. All models see the same training and validation arrays, ensuring their differences are not merely different evaluation samples. A protected test partition is created but left unused while we inspect validation behavior.

Python

from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, HistGradientBoostingClassifier
from sklearn.metrics import balanced_accuracy_score
from sklearn.inspection import permutation_importance

X, y = make_classification(n_samples=700, n_features=8, n_informative=4,
                           n_redundant=2, flip_y=0.04, random_state=35)
Xd, Xt, yd, yt = train_test_split(X, y, test_size=0.2, stratify=y, random_state=35)
Xr, Xv, yr, yv = train_test_split(Xd, yd, test_size=0.25, stratify=yd, random_state=36)
models = {
    "tree": DecisionTreeClassifier(max_depth=4, min_samples_leaf=8, random_state=35),
    "forest": RandomForestClassifier(n_estimators=60, max_depth=6,
                    min_samples_leaf=4, random_state=35, n_jobs=1),
    "boosting": HistGradientBoostingClassifier(max_iter=60, max_leaf_nodes=12,
                    learning_rate=0.08, early_stopping=False, random_state=35)}

2. Inspect fit gaps and held-out importance

Training minus validation score is a diagnostic, not an exact overfitting measurement. Select by validation balanced accuracy and inspect importance on that same validation set as a development analysis. If this inspection changes the features, repeat selection without using the test set.

Python

validation = {}
for name, model in models.items():
    model.fit(Xr, yr)
    train_score = balanced_accuracy_score(yr, model.predict(Xr))
    validation[name] = balanced_accuracy_score(yv, model.predict(Xv))
    print(name, "train", train_score, "validation", validation[name])
chosen_name = max(validation, key=validation.get)
chosen = models[chosen_name]
importance = permutation_importance(chosen, Xv, yv, n_repeats=5,
    random_state=35, scoring="balanced_accuracy", n_jobs=1)
print("chosen", chosen_name)
print("importance mean", importance.importances_mean)
print("importance std", importance.importances_std)
# No feature changes are made after this inspection.
print("final test", balanced_accuracy_score(yt, chosen.predict(Xt)))

Expected output / interpretation

The script prints three train/validation comparisons and eight importance summaries.
Importance can be small or negative because of sampling variation or redundant features.
No model ordering or score is guaranteed; the final metric applies to the selected fitted model.

Guided lab and acceptance criteria

  1. Sketch a two-level tree for an invented pair of measurements. Identify which regions cannot be separated with only those questions and how an additional split changes the partition.
  2. Run the three fixed candidates and record training time with perf_counter if you want a compute comparison. Use the same machine and report the measurement conditions; a single short timing includes overhead and is not a general benchmark.
  3. For the shallow tree, compare depth 2 and depth 10 using validation only. Inspect changes in both training and validation scores. Add a min_samples_leaf constraint and explain its effect on small regions.
  4. Write a model-selection note that includes score, complexity, compute budget, and permutation-importance limitations. Finish with one locked test evaluation. A passing report does not label feature importance as a causal effect or present the largest training score as the winner.

Common mistakes and repairs

  • Growing a tree until training accuracy reaches one: that can memorize label noise while harming new-case performance.
  • Comparing forest impurity importances directly with permutation scores as though their scales match: they measure different quantities.
  • Enabling all available CPU workers in nested searches: control parallelism at one level and keep this local exercise bounded.

Questions that test understanding

Why can averaging trees help?

Individual trees can respond strongly to small data changes. When several varied trees make imperfectly correlated errors, aggregation can smooth some of that variability. If every tree makes the same systematic mistake, averaging will preserve it, so data quality and useful features remain essential.

How is boosting different from a random forest?

A forest largely builds trees independently and aggregates them. Boosting builds a sequence in which later components depend on the current model’s errors or loss gradient. This creates different interactions among depth, learning rate, iteration budget, and overfitting risk.

Does a large training-validation gap prove overfitting?

It is a warning, but not a complete diagnosis. Sampling variability, train-validation distribution differences, and leakage can also affect the gap. Examine split design and repeated development measurements before making a definitive claim, especially when validation contains few observations.

Why can permutation importance be negative?

Shuffling a feature may accidentally improve the score on a finite validation sample, or the fitted model may rely on harmful noise. Repeat shuffles and inspect uncertainty. A slightly negative mean is not evidence that the feature is inherently harmful in every model or population.

Why may correlated features look unimportant individually?

The model may recover similar information from a correlated partner after one column is shuffled. Individual permutation tests then underestimate the information carried jointly. Grouped permutation can address a different question, but the grouping must be justified and reported.

Why disable internal early stopping in this example?

It keeps each candidate’s training budget explicit and avoids an additional hidden split within the learner. Internal early stopping is useful in larger workflows, but its partition and stopping criterion should be documented and kept separate from the final test set.

Exercises with worked solutions

Exercise 1: Count leaves and inspect complexity

Reveal the worked solution and reasoning

The tree object exposes its realized depth and leaf count. Those are properties of the fitted partition, which can be smaller than the allowed limits. Compare them with validation scores rather than assuming a larger tree is more informative.

Python

tree = models["tree"]
print("depth", tree.get_depth(), "leaves", tree.get_n_leaves())
assert tree.get_depth() <= 4

Exercise 2: Explain an all-zero importance vector

Reveal the worked solution and reasoning

Possible explanations include a model that barely beats a baseline, highly redundant inputs, a score insensitive to small changes, or too little validation data. First compare baseline performance and inspect predictions; then repeat the permutation analysis with a justified metric and more evidence. Do not invent a list of important features merely because a chart is expected.

Recap and next step

Trees create partitions; forests aggregate varied trees; boosting builds sequential corrections. Their evidence should still come from shared honest splits and deployment-relevant metrics. The next lesson replaces ad hoc parameter choices with a small reproducible search whose entire preprocessing pipeline is fitted inside each fold.

Official references

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.