Decision Trees and Ensemble Methods

Learn how decision trees make predictions and how to grow them by choosing splits with Gini impurity, entropy and squared error. Control overfitting with stopping rules and cost-complexity pruning, then combine many trees: bagging and random forests to reduce variance, gradient boosting and XGBoost to reduce bias. Read feature importance with care, using impurity-based and permutation importance, and tune and compare tree ensembles with out-of-bag scores, cross-validation and early stopping. Worked examples with real numbers and scikit-learn and XGBoost settings show each step.

IntermediateLesson 6 of 9 in Machine Learning Course

What you will learn

  1. Explain how a decision tree turns a sequence of yes/no questions into predictions, and choose the splits of classification and regression trees with impurity and squared-error measures.
    • Read a decision tree and trace its predictions
      Name the parts of a tree, follow an example from the root to a leaf, and explain how leaves give class labels, probabilities or numbers, and where single trees are strong or weak.
    • Choose classification splits with Gini impurity and entropy
      Measure how mixed a node is, compute the weighted impurity of a candidate split, and pick the split with the largest impurity decrease or information gain.
    • Split numeric and categorical features and grow regression trees
      Find candidate thresholds for numeric features, prepare categorical and missing values for a tree, and choose regression splits by the reduction in squared error.
  2. Recognize when a decision tree overfits, limit its growth with hyperparameters chosen by validation, and prune it back with cost-complexity pruning.
    • Diagnose overfitting and limit tree growth
      Spot the training–validation gap of an overgrown tree and use depth and leaf-size limits, tuned by cross-validation, to stop growth earlier.
    • Prune a tree with cost-complexity pruning
      Grow a large tree, compute effective alphas along the pruning path, and choose the pruning strength by cross-validation.
  3. Explain how averaging trees trained on bootstrap samples reduces variance, how random feature selection decorrelates the trees of a random forest, and how out-of-bag examples estimate test performance.
    • Bootstrap and aggregate many trees (bagging)
      Draw bootstrap samples, combine the trees' predictions by averaging or voting, and explain why averaging lowers variance but not correlation.
    • Decorrelate trees with random forests
      Explain how restricting each split to a random subset of features decorrelates the trees, choose the subset size, and know a forest's main settings and limits.
    • Estimate performance with out-of-bag error
      Use the examples each tree did not see to estimate test error without a separate validation split, and know when this estimate is unreliable.
  4. Explain how boosting adds shallow trees one after another to correct the current errors, derive the pseudo-residuals for common losses, and train and regularize XGBoost models.
    • Boost shallow trees by fitting residuals
      Run the boosting loop for squared error by hand, explain the role of the learning rate, and contrast boosting with bagging.
    • Explain gradient boosting with loss functions and pseudo-residuals
      Derive the pseudo-residuals for squared error and log loss, compute starting values and leaf values for classification, and use the scikit-learn implementations.
    • Train and regularize XGBoost models
      Use XGBoost's regularized objective, gradient and Hessian sums, split gain and main hyperparameters, with early stopping on a validation set.
  5. Compute and read impurity-based feature importance, recognize its biases, and use permutation importance and explanation plots to describe what a tree ensemble has learned.
    • Compute and read impurity-based importance
      Calculate mean decrease in impurity from a tree's splits, read normalized importances correctly, and recognize when they mislead.
    • Use permutation importance and explain model behavior
      Measure importance on held-out data by shuffling features, handle correlated features, and use partial dependence and SHAP values to show the direction of effects.
  6. Tune random forests and gradient-boosted trees with validation, out-of-bag scores and early stopping, and choose between trees, ensembles and other models for a given problem.
    • Tune random forests
      Decide which random forest settings matter, tune them with out-of-bag or cross-validated scores, and handle imbalanced classes.
    • Tune gradient-boosted trees with early stopping and search
      Tune learning rate, number of trees, tree size, subsampling and regularization in a sensible order, with early stopping and randomized search that leave the test set untouched.
    • Choose between trees, forests, boosting and other models
      Match single trees, random forests, gradient boosting, linear models and neural networks to the data type, accuracy, interpretability and deployment needs of a problem.

Decision Trees and Ensemble Methods study guide

6 chapters

1

How trees turn features into predictions

A decision tree makes a prediction through a short path of feature tests. Reading that path is straightforward; choosing useful tests takes a measure of how much each split improves the fit. Start with class proportions and numeric targets, then work through the calculations that grow a tree. The same calculations explain why a tree can fit training data closely yet struggle on new records.

1.1 Paths, leaves, and prediction rules

A decision tree is a supervised model built from questions about the input features. It can predict a category, such as whether a customer leaves a service, or a number, such as daily demand. A small tree makes its reasoning visible as a path from a starting question to a prediction.

Follow one path

The first node is the root. An internal node tests a condition, a branch represents an answer, and a leaf holds the result. The tree's depth is the number of splits on its longest root-to-leaf path. CART, the algorithm used by scikit-learn, makes binary splits: each record goes to exactly one of two children.

Consider a tree whose root asks, "Is contract length at most 1 month?" A yes leads to "Were there at least 3 support calls last quarter?" The two leaves give churn probabilities of 0.80 for yes and 0.35 for no. A no at the root leads directly to probability 0.10.

A customer with a 1-month contract and 4 calls follows yes, yes, reaching 0.80. A customer with a 24-month contract reaches 0.10 after one test. The second customer's call count has no effect on that path. A tree does not consult every feature for every prediction.

Read the leaf correctly

An unweighted classification leaf uses its training class proportions as probability estimates and predicts the majority class. If 18 customers in a leaf churned and 6 stayed, its estimated churn probability is 18/24=0.75. This is a proportion among records grouped by the tree, not certainty about one customer.

A squared-error regression leaf predicts the mean of its training targets. Each leaf therefore gives one constant prediction throughout its region. Tests such as xj≤t cut along one feature axis at a time, making non-overlapping rectangular regions, or boxes in more dimensions. Some other tree algorithms allow several branches for a categorical feature; CART has two children per split.

How the rules are learned

Recursive binary splitting starts at the root. It tries feature tests, keeps the split with the largest immediate reduction in impurity or squared error, and repeats in each child. This search is greedy: the best next split need not lead to the best complete tree. Searching every possible tree is too costly on realistic data.

Trees need no feature scaling. Converting meters to centimeters changes threshold values but preserves the order and membership of the groups. A strictly increasing transformation preserves those groups as well. Standardizing the columns is unnecessary for this splitting rule.

Match the shape to the problem

A split within another feature's branch captures an interaction: the effect of one feature depends on the other. Trees naturally handle these patterns and nonlinear effects. A sloped straight-line trend or diagonal boundary takes many axis-aligned steps to approximate, so linear or logistic regression can fit such relationships more efficiently.

A deep tree also has high variance: a small training-data change can alter its early splits and much of the structure below them. Ensembles average or add trees to improve prediction, while giving up the single readable diagram. Compare models with cross-validation to judge which structure suits the data.

Key Takeaways

  • A prediction follows one root-to-leaf path.
  • Classification leaves estimate class proportions; squared-error regression leaves predict means.
  • Greedy splitting optimizes the next split, not the whole tree.
  • Trees need no feature scaling and can capture interactions.
  • Small trees are readable; deep trees are unstable.

1.2 Measuring the value of a classification split

A classification node is useful when it groups examples of the same class. Impurity measures how mixed its classes are. A pure node has impurity zero; a balanced mixture has the greatest impurity for a fixed number of classes.

Gini, entropy, and error

For class proportions p1,…,pK, the main measures are:

  • Gini impurity: G=1−∑kpk2.
  • Entropy: H=−∑kpklog⁡2pk, in bits, taking 0log⁡20=0.
  • Misclassification error: E=1−max⁡kpk.

In a two-class node, Gini is 2p(1−p). It peaks at 0.5 when both classes have proportion 0.5. Entropy peaks at 1 bit there. With K equally common classes, the maxima are 1−1/K and log⁡2K. Gini can also be read as the chance that two draws with replacement from the node have different classes.

Weight both children

A split's impurity is the size-weighted average of its children:

Isplit=nLnI(L)+nRnI(R).

The decrease is parent impurity minus this average. With entropy, it is called information gain. Comparing splits at the same parent, minimizing weighted child impurity and maximizing the decrease give the same choice.

Take 10 customers: 5 churned and 5 stayed. Parent Gini is 0.5. Split A makes a pure child of 4 churners and a child with 1 churner and 5 stayers. The second child's Gini is 1−(1/6)2−(5/6)2=10/36. Weighted child impurity is 0.4(0)+0.6(10/36)≈0.167, so the decrease is about 0.333.

Split B produces children with counts (3, 2) and (2, 3). Both have Gini 0.48. Their weighted impurity is 0.48, so the decrease is only 0.02. Split A wins.

Using entropy, the same parent has 1 bit. Split A gives weighted entropy about 0.390 and gain 0.610; split B gives about 0.971 and gain 0.029. Gini and entropy often agree on useful splits, although they need not always choose the same one. scikit-learn's classifier defaults to criterion="gini"; "entropy" and "log_loss" use Shannon information gain.

Why the weights matter

Isolating one churner leaves 9 customers with counts (4, 5). Their Gini is 40/81≈0.494. Averaging the two child impurities equally gives about 0.247, but the correct weighted value is 0.9(40/81)≈0.444. A tiny pure child helps only a small share of the records.

Misclassification error is useful for reporting label mistakes but is less sensitive during growth. From a parent with 200 examples of each class, children (150, 50) and (50, 150) have the same weighted error, 0.25, as children (100, 200) and (100, 0). Weighted Gini is 0.375 for the first split and about 0.333 for the second; it distinguishes the purer structure.

Gini and entropy cannot increase after size-weighted splitting on the training data. An unrestricted tree can keep refining until leaves are pure or no valid split remains. Identical features with conflicting labels cannot be separated. Training purity alone gives no evidence that the tree will generalize well.

Key Takeaways

  • Compute impurity from class proportions within each node.
  • Weight each child by its share of the parent records.
  • Information gain is the reduction in entropy.
  • Choose the largest decrease, or equivalently the smallest weighted child impurity.
  • Misclassification error can miss improvements that Gini detects.
  • Pure training leaves can still overfit.

1.3 Thresholds, numeric predictions, and prepared features

For a numeric feature, a tree needs to decide where one group ends and the next begins. For a numeric target, it also needs a measure of prediction error. These choices turn a table of measurements into a set of constant predictions.

Test the gaps between values

Sort the distinct feature values in a node. Candidate thresholds are the midpoints of adjacent values: n distinct values give n−1 candidates. Moving a threshold within one such gap leaves the same training groups. Repeated feature values do not create extra gaps.

For squared-error regression, each child predicts its own target mean. Compare splits using the total sum of squared errors:

SSE=∑i∈L(yi−yˉL)2+∑i∈R(yi−yˉR)2.

This is equivalent to maximizing the size-weighted decrease in MSE. The default scikit-learn criterion is "squared_error". With "absolute_error", a leaf predicts its median; "poisson" is available for count targets.

Work through a regression split

At temperatures 5, 10, 15, 20, 25, and 30 °C, daily bike rentals are 120, 150, 260, 300, 310, and 330. The root mean is 245 and its SSE is 39,350.

Threshold (°C)Total child SSE
7.520,600
12.53,050
17.5About 11,333
22.522,475
27.530,680

At the winning threshold, 12.5 °C, the left mean is 135 and the right mean is 300. Left SSE is 152+152=450. Right SSE is 402+02+102+302=2600, giving 3,050 overall. An 18 °C day reaches the right leaf and gets 300 rentals. So does a 40 °C day: a tree repeats its outer leaf value instead of extending a rising trend.

Encode categories without leaking targets

scikit-learn's ordinary trees and forests take numeric inputs. One-hot encoding turns basic, standard, and premium plans into three binary columns; premium becomes (0, 0, 1). Each split tests one category against the rest. Ordinal encoding gives categories integer codes, allowing threshold groups in code order. A natural order such as small, medium, large makes these groups easier to interpret.

Thousands of categories create many sparse one-hot columns and opportunities to fit rare cases. Group rare categories into "other", or use target encoding with training-row cross-fitting. A training row's own target must not enter its encoded value. Encode validation and test rows from training mappings. scikit-learn's TargetEncoder.fit_transform creates these out-of-fold training encodings. A pipeline also keeps the encoder inside each outer validation fold.

XGBoost with enable_categorical=True, LightGBM, CatBoost, and histogram gradient boosting offer native categorical support. Use the input format each estimator expects.

Missing values and growth limits

Recent scikit-learn trees and forests, histogram gradient boosting, XGBoost, and LightGBM can learn a direction for missing values at splits. For an estimator that requires imputation, fit the imputer within the training pipeline.

An ordinary scikit-learn tree starts with max_depth=None, min_samples_split=2, and min_samples_leaf=1. It keeps growing until a stopping condition or lack of a valid split prevents growth. Distinct feature combinations can end in single-record leaves with zero regression training error. Conflicting targets at identical feature values leave error because no feature test separates them.

Key Takeaways

  • Numeric thresholds lie between consecutive distinct feature values.
  • Squared-error leaves predict means and splits minimize total child SSE.
  • Regression predictions are constant inside each leaf.
  • Categorical encoding and imputation must respect validation boundaries.
  • Target encoding needs out-of-fold values for training rows.
  • Missing-value support depends on the estimator.
  • An unrestricted tree can memorize separable training records.
2

Keep a tree small enough to generalize

A tree can keep improving its training fit by carving the data into smaller groups. Validation shows when those extra rules stop helping new examples. You can limit growth while the tree is built, or grow a large tree and remove weak branches afterward. Depth curves and a worked pruning calculation show how these two approaches trade a closer fit for a simpler, more stable set of rules.

2.1 Growth limits and the training–validation gap

A deep tree can fit unusual training records as if they were reliable patterns. Its bias is low, but its predictions can change greatly with a different training sample. This is high variance, and it often appears as a large gap between training and validation performance.

Read the curve

Imagine a churn tree with 100% training accuracy and 81% validation accuracy. Limiting it to depth 4 gives 90% training accuracy and 87% validation accuracy. The lower training score buys better predictions on unseen customers. Training accuracy by itself would choose the worse model.

A validation curve plots training and validation scores against a complexity setting. At very small depth, both scores may be low: the tree misses useful structure and underfits. As depth increases, both can improve. When training keeps improving while validation levels off or worsens, added complexity is fitting noise.

A binary tree of depth d has at most 2d leaves. Depth 3 permits 8 leaves; depth 10 permits 1,024. With 1,000 examples, a depth-10 tree has enough possible leaves to isolate almost every record, although the actual structure depends on the available splits.

Choose what to limit

Pre-pruning stops some growth before the complete tree is built.

SettingWhat it restricts
max_depthSplits on the longest path
min_samples_splitRecords a node needs before splitting
min_samples_leafRecords required in each resulting child
max_leaf_nodesTotal number of leaves
min_impurity_decreaseMinimum size-weighted impurity improvement

min_samples_split=10 allows a 10-record parent to be considered for splitting; it does not promise 10 records in each child. min_samples_leaf=10 does require that minimum in both children. Larger leaves also base probability estimates on more records, making the estimates less extreme.

Select limits with held-out scores

Try candidate depths, such as 1 through 15, using cross-validation within the training data. Keep the same folds and metric for all candidates. Select the best mean score, or choose the simplest candidate within one standard error of the best. Refit that setting on the available training data before the final test evaluation.

Do not choose the setting from its training score: deeper trees can almost always improve that score. Repeated choices based on the test set make its reported result optimistic. The test set has one job, estimating the performance of the completed selection procedure.

Why early growth limits can miss a pattern

Suppose two binary features have all four combinations equally often. The label is yes exactly when one feature equals 1 and the other equals 0: an exclusive-or pattern. Splitting on either feature leaves two balanced children, so the immediate impurity decrease is zero.

A rule requiring a decrease of at least 0.01 stops at the root. Yet splitting each child on the second feature would produce pure leaves. The first step is useful only because it enables the next ones. Growing a larger tree and pruning afterward gives this interaction a chance to appear. Depth and leaf-size choices still need validation; a setting that works on one dataset need not work on another.

Key Takeaways

  • A widening training–validation gap signals overfitting.
  • Depth limits model capacity through the maximum number of leaves.
  • Minimum parent size and minimum child size are different controls.
  • Choose complexity with validation, then evaluate once on the test set.
  • A weak first split can enable a useful interaction.

2.2 Paying for leaves with cost-complexity pruning

Post-pruning begins with a large tree and removes subtrees that offer too little improvement for their size. Cost-complexity pruning makes this trade-off explicit by assigning a price to each leaf.

Compare fit plus complexity

The penalized training objective is

Rα(T)=R(T)+α∣T∣.

Here R(T) is the total training leaf error or impurity, ∣T∣ is the number of leaves, and α is the nonnegative price per leaf. At zero, there is no complexity penalty. Increasing alpha favors smaller trees; a sufficiently large value leaves only the root.

For scikit-learn's classification trees, use impurity weighted by the fraction of training examples reaching each leaf. A node holding 40 of 200 records with Gini impurity 0.3 has weighted risk R(t)=(40/200)(0.3)=0.06. Using 0.3 directly would put its contribution on the wrong scale.

Find the weakest link

Let the subtree below that node have 3 leaves whose weighted impurities total 0.02. Collapsing the subtree increases training risk from 0.02 to 0.06 but saves two leaves. Its effective alpha is the risk increase per leaf removed:

αeff(t)=R(t)−R(Tt)∣Tt∣−1=0.06−0.023−1=0.02.

The denominator is two because three leaves become one. It is not the original leaf count.

Check the comparison at two penalty values:

AlphaKeep 3 leavesCollapse to 1 leafLower cost
0.010.02 + 0.03 = 0.050.06 + 0.01 = 0.07Keep
0.030.02 + 0.09 = 0.110.06 + 0.03 = 0.09Collapse

At alpha 0.02, both costs equal 0.08. This equality explains the effective alpha: it is the point where the saved complexity pays for the lost training fit.

Weakest-link pruning removes the subtree with the smallest effective alpha first. Then it recalculates effective alphas in the remaining tree. Repeating this process gives a pruning path of nested subtrees. Each candidate comes from the preceding one by removing branches, so there is no need to enumerate every possible subtree.

Choose the amount of pruning

In scikit-learn, cost_complexity_pruning_path(X_train, y_train) returns candidate effective alphas and total leaf impurities. Fit trees with candidate values of ccp_alpha and compare cross-validated scores on the training data. The largest path value leaves only the root; ccp_alpha=0.0 applies no cost-complexity pruning.

Select the alpha with the best validation score, or the largest alpha within one standard error of the best score if you want a simpler tree. Then refit and use the untouched test set. Selecting by training accuracy would favor the unpruned model, defeating the purpose of the penalty.

A pruned tree is easier to inspect and often predicts new records better than the full tree. It remains a single unstable learner, however. Random forests address this instability by averaging deep trees; boosting controls the size of each correction and the number of corrections added.

Key Takeaways

  • Cost-complexity pruning minimizes training risk plus a price per leaf.
  • Effective alpha divides added risk by the number of leaves removed.
  • Weakest-link pruning produces a nested sequence of trees.
  • Cross-validation selects the pruning strength.
3

Make averaging work with bagging and forests

Deep trees change when the training sample changes. Bagging turns that weakness into useful diversity by fitting many trees to resampled data and combining their predictions. Random forests add feature randomness so those trees do not all make the same choices. The examples each tree leaves out supply out-of-bag predictions, linking the training procedure to a convenient performance estimate.

3.1 Bootstrap samples and the limits of averaging

Bagging, short for bootstrap aggregating, fits many versions of an unstable learner and combines their predictions. Deep trees are a good match: they capture detailed patterns, while their sensitivity to the sample gives the ensemble varied predictions to average.

Draw with replacement

A bootstrap sample contains n draws from n training records, with replacement after each draw. Some records appear more than once and some are absent. The sample still has n positions; it does not contain n distinct records.

A particular record is missed on one draw with probability 1−1/n, and on all draws with probability (1−1/n)n. Its chance of appearing at least once is therefore 1−(1−1/n)n. This is about 0.651 for 10 records and approaches 0.632 for large samples. About 36.8% of records are left out of each large bootstrap sample.

Fit one tree per bootstrap sample. The fits are independent computational tasks and can run in parallel. They still use overlapping data, so their prediction errors are statistically correlated.

Combine predictions on the right scale

For regression, average the numeric predictions. For classification, hard voting counts class labels, while soft voting averages class probabilities and chooses the class with the highest mean. scikit-learn's random forest classifier uses soft voting.

Five trees with churn probabilities 0.9, 0.4, 0.6, 0.55, and 0.2 have mean 0.53. Both their hard vote and their soft vote predict churn at a 0.5 threshold. But probabilities 0.55, 0.55, 0.55, 0, and 0 give three churn labels while their mean is only 0.33. Hard voting predicts churn; soft voting predicts stay. Counting labels discards the strength of each probability.

Understand what averaging removes

Suppose each tree prediction has variance σ2 and every pair has correlation ρ. The variance of the average of B predictions is

ρσ2+1−ρBσ2.

The second term shrinks with more trees. The first remains because all trees share some of their variation. With variance 4 and correlation 0.5, 10 trees give variance 2.2 and 100 give 2.02. With correlation 0.1 and 100 trees, it is about 0.436. Lower correlation can matter much more than adding trees after the average is stable.

Independent voting errors would also help: 25 independent classifiers that are each 60% accurate would have majority accuracy about 0.846. Bagged trees do not meet that independence condition, so this number is an illustration of the benefit of independent errors, not a forest accuracy promise.

Decide when bagging helps

Bagging mainly reduces variance while leaving bias about the same. Stable learners such as linear regression change little across bootstrap samples, so they offer less diversity and usually gain little. Deep trees have much more variance to remove.

Adding trees stabilizes the bagged average; it does not create the sequential noise-fitting process found in boosting. Stop adding them when the validation or out-of-bag curve has flattened enough for your time and memory budget. The trade-off is interpretability: hundreds of trees no longer fit into one readable rule diagram, so model inspection needs importance measures and explanation tools.

Key Takeaways

  • A bootstrap sample draws with replacement and can repeat records.
  • Large bootstrap samples contain about 63.2% distinct training records.
  • Regression averages numbers; soft voting averages class probabilities.
  • Correlation creates a variance floor that more trees cannot remove.
  • Bagging is most useful for unstable, high-variance learners.
  • Adding bagged trees stabilizes their average.

3.2 Feature randomness in a random forest

Bootstrap samples can produce trees that look too similar. If one feature is especially predictive, almost every tree may use it near the root. A random forest limits the features available at each split, giving other predictors a chance to shape the trees.

Choose fresh candidates at each node

At every split, select m candidate features randomly from the p available features, then search for the best split among those candidates. Make a fresh selection at the next split. The forest also uses bootstrap samples by default. Setting m=p removes feature restriction and gives ordinary bagging.

With 36 features and 6 candidates, one particular strong feature is absent with probability 30/36≈0.83 at a split. Trees must often use alternative predictors. This lowers their correlation, reducing the variance floor of their average.

The trade-off is individual-tree strength. If only 3 of 100 features are informative, a random group of 10 candidates contains none of them with probability about 0.73. Restricting the candidates too much makes many local choices rely on noise. A useful forest needs both reasonably strong trees and enough diversity between them.

Interpret max_features

A common classification starting point is m=p. A traditional regression rule is m=p/3. For 36 features, these give 6 and 12 candidates. They are starting choices for tuning, not universal optima.

scikit-learn's RandomForestClassifier defaults to max_features="sqrt". It rounds down: 10 input features give 3 candidates. RandomForestRegressor defaults to max_features=1.0, using all features, so set a smaller value to introduce feature restriction. A fractional value such as 0.5 uses approximately half the input columns per split.

Know the other controls

The main defaults are n_estimators=100, bootstrap=True, max_depth=None, and min_samples_leaf=1. max_samples=None draws a bootstrap sample with as many positions as the training set. Smaller bootstrap samples add another source of variation.

Use n_jobs to parallelize tree fits and random_state for repeatable random choices. class_weight changes how classes contribute during training when their frequencies or costs differ. Tree size still matters for memory and prediction speed even when averaging controls much of the variance.

Compare extra randomization

Extremely randomized trees, available as ExtraTreesClassifier and ExtraTreesRegressor, randomly propose thresholds for candidate features and choose the best of those proposals. Ordinary forests search thresholds more thoroughly. ExtraTrees adds diversity and often trains faster, with a possible increase in bias. Its default fits each tree on the full training set, without bootstrapping.

Forests are useful baselines for tabular records. They capture nonlinear effects and interactions, need no scaling, and tolerate outlying feature values without a distance calculation. Hundreds of deep trees can occupy substantial memory and make prediction slower. A squared-error forest regressor averages leaf means, so it stays within the training target range and cannot extend a trend beyond the data. A small tree remains the easier option when every prediction must be explained as a short path.

Key Takeaways

  • Random forests choose fresh feature candidates at every split.
  • Restricting features lowers correlation but can weaken individual trees.
  • The classifier and regressor have different max_features defaults.
  • ExtraTrees randomizes thresholds and does not bootstrap by default.
  • Large forests cost memory and do not extrapolate regression trends.

3.3 Use the records each tree leaves out

A bootstrap sample leaves some training records unused. These out-of-bag, or OOB, records can evaluate that tree because their targets did not help fit it. Across a forest, each record receives predictions from a different subset of trees.

Build one OOB prediction per record

For each training record, identify the trees whose bootstrap samples omitted it. Combine only those trees' predictions. For classification, average their class probabilities; for regression, average their numeric predictions. Compare this result with the record's actual target. Then calculate the performance metric across the records.

A customer might be out of bag for 180 trees. If their mean churn probability is 0.67, the OOB class prediction is churn at a 0.5 threshold. If the customer stayed, that is an OOB classification error. Trees that trained on this customer must not join this prediction, even if the forest contains many more trees.

About 36.8% of trees omit a given record in a large dataset. A forest of 500 trees therefore gives roughly 184 OOB contributors per record. The counts vary randomly; OOB predictions do not all average exactly the same number of trees.

Read scikit-learn's output

Set oob_score=True while keeping bootstrap=True. After fitting:

  • For a classifier, oob_score_ is accuracy by default and oob_decision_function_ contains class probabilities.
  • For a regressor, oob_score_ is the default R² score and oob_prediction_ contains numeric predictions.

The name does not mean every score is an error rate. For default classification accuracy, error is one minus accuracy. For R², subtracting from one does not produce a classification error rate.

OOB evaluation uses the forest already fitted, so it needs no extra model per fold. It resembles leave-one-out validation because each record is scored by trees that did not fit it, although the contributing trees were fitted to bootstrap samples, not the complete set of all other records.

Use enough trees

With only a few trees, a record may appear in every bootstrap sample. It then has no tree available for its OOB prediction. With 10 trees and the large-sample inclusion probability, this happens with probability about 0.63210≈0.010, around 1% of records. The resulting estimate is noisy, and scikit-learn can warn about missing OOB coverage.

Increase the tree count until the score is stable before using OOB comparisons to select max_features or leaf size. Each candidate setting needs one forest fit, making this cheaper than a separate fit for every fold.

Keep the evaluation question honest

Choosing the best of many settings using OOB scores makes the winning OOB result optimistic. Reserve a test set for evaluating the chosen procedure once. Data-dependent preprocessing also needs attention: an OOB tree's omission of a row does not undo information already used by a shared encoder or imputer.

Ordinary bootstrapping mixes times and groups. Records from the same person can appear on both sides of an OOB prediction, and future observations can help predict earlier ones. For repeated people or time series, use validation splits that respect those groups or time order. OOB is convenient for independent records, not a replacement for the right split design.

Key Takeaways

  • An OOB prediction uses only trees that omitted that record.
  • OOB scoring needs bootstrap sampling and enough trees.
  • Default OOB scores are accuracy for classification and R² for regression.
  • OOB tuning still needs a final untouched test set.
  • Group structure, time order, and shared preprocessing can invalidate an OOB comparison.
4

Build better predictions one correction at a time

Boosting adds a new tree to correct the current model, so each training round depends on the rounds before it. For squared error, the correction follows residuals. Other losses lead to pseudo-residuals, and XGBoost uses both gradients and curvature to choose regularized updates. Work through the update scale, leaf values, and split gains before using validation to decide how long learning should continue.

4.1 Residual fitting and the learning rate

A single shallow tree may miss much of the structure in a dataset. Boosting builds an additive model: fit a small tree to what the current model gets wrong, add part of its prediction, and repeat. The next tree learns from the updated errors.

Run the squared-error loop

Start with a constant F0 equal to the training target mean. At round m:

  1. Compute residuals ri=yi−Fm−1(xi).
  2. Fit a small regression tree hm to those residuals.
  3. Update Fm(x)=Fm−1(x)+ηhm(x).
  4. Recompute residuals for the next round.

The learning rate η shrinks each correction. After M rounds,

FM(x)=F0(x)+η∑m=1Mhm(x).

The trees are added, not averaged as separate complete predictions.

Follow the numbers

For feature values 1, 2, 3, 4 and targets 10, 12, 20, 22, the mean is 16. Initial residuals are −6, −4, 4, 6; their mean squared value is 26.

A stump, a tree with one split, separates at 2.5. Its left leaf predicts mean residual −5 and its right leaf predicts +5. With learning rate 0.1, the correction is only −0.5 or +0.5. Updated predictions are 15.5, 15.5, 16.5, 16.5. The new residuals are −5.5, −3.5, 3.5, 5.5, giving MSE 21.25.

The next tree fits these new residuals. Reusing the original residuals would repeatedly apply a correction for errors that the model has already partly fixed.

With learning rate 1, the first predictions would instead be 11, 11, 21, 21 and MSE would fall to 1. A rapid training improvement can also make it easier for later rounds to chase noise. Smaller learning rates, often 0.01 to 0.3, spread learning across more rounds. Halving the rate often requires roughly twice as many rounds for a similar training fit; validation decides the useful combination.

Compare the ensemble mechanisms
FeatureBaggingBoosting
TrainingSeparate fits, often parallelSequential corrections
Typical treesDeepShallow
CombinationAverage or voteAdd scaled corrections
Main benefitLower varianceLower bias
Too many treesAverage stabilizesCan fit validation noise

Boosting does not require bootstrap samples. It may use all training records or randomly subsample them per round.

Tree depth controls the interactions a correction can express. Stumps contribute one-feature effects, producing an additive model; depth-2 trees can express pairwise interactions. scikit-learn's classic gradient boosting defaults to depth 3, while XGBoost's default maximum depth is 6.

The tree count is a complexity choice in boosting. Watch validation performance as training error falls, and stop when extra rounds cease to help. AdaBoost is a related method that increases the training weight of misclassified examples and combines learners with a weighted vote. Gradient boosting takes a broader route: each tree follows the negative gradient of the chosen loss.

Key Takeaways

  • Squared-error boosting fits each new tree to current residuals.
  • Add the learning-rate-scaled correction to the current prediction.
  • A smaller learning rate usually needs more rounds.
  • Tree depth controls the interactions each correction can express.
  • Boosting can overfit as trees are added.
  • Bagging fits independent models; boosting fits sequential corrections.

4.2 Loss functions set the correction scale

Residual fitting is one case of gradient boosting. For a general differentiable loss, ask how a small change in the current prediction would change the loss. The negative derivative gives the direction that locally reduces it.

From gradients to pseudo-residuals

In round m, the pseudo-residual for record i is

rim=−∂L(yi,F)∂F∣F=Fm−1(xi).

Fit a regression tree to these values. Its regions collect records needing similar corrections; the final value in each leaf is chosen to reduce the actual loss for that region. Add the tree with the learning rate.

For half squared error, L=12(y−F)2, the negative gradient is y−F and the best leaf correction is the mean residual. For absolute error, the direction is the sign of the residual, +1 or −1 away from zero. This reduces the influence of very large residuals. Huber loss combines squared behavior for small errors with absolute-error behavior for large errors.

Binary classification uses log-odds

For labels 0 and 1, the additive score F is on the log-odds scale. Convert it into probability using

p=11+e−F.

The binary log loss is −[yln⁡p+(1−y)ln⁡(1−p)]. Its negative gradient with respect to F is y−p. The starting score is the log-odds of the training positive share:

F0=ln⁡pˉ1−pˉ.

If 30% of customers churn, F0≈−0.847 and their initial probabilities are 0.3. Churners have pseudo-residual 0.7; non-churners have −0.3.

For a leaf containing two churners and one non-churner, the Newton correction is

w=∑i(yi−pi)∑ipi(1−pi)=0.7+0.7−0.33(0.21)≈1.746.

With learning rate 0.1, the log-odds become about −0.673 and the probability rises to about 0.338. Add 0.175 to the log-odds, not to 0.3. A tree's leaf value can exceed 1 because it is a score correction, not a probability.

Add randomness and choose an implementation

Stochastic gradient boosting draws a fraction of the training rows without replacement for each tree. subsample=0.7 uses 70% per round, adding regularization and reducing work. In scikit-learn's classic gradient boosting, using less than 1.0 also provides oob_improvement_, the loss improvement on records omitted from that round. These round-specific improvements are not the same construction as a forest's OOB prediction.

scikit-learn implementationSplit search and useful behavior
GradientBoostingClassifier / RegressorSearches thresholds directly; defaults to learning rate 0.1, 100 trees, depth 3, and all rows
HistGradientBoostingClassifier / RegressorBins features into at most 255 non-missing bins; faster on large tables and handles missing values

Classic gradient boosting uses early stopping when n_iter_no_change is set. Histogram gradient boosting with early_stopping="auto" enables it for training sets larger than 10,000 records.

Key Takeaways

  • Pseudo-residuals are negative loss gradients at current predictions.
  • Squared-error pseudo-residuals are ordinary residuals.
  • Binary log-loss pseudo-residuals are label minus probability.
  • Classification updates add to log-odds before conversion to probability.
  • Stochastic boosting subsamples rows without replacement.
  • Histogram splitting speeds up training by binning numeric features.

4.3 XGBoost leaf weights, split gains, and controls

XGBoost builds gradient-boosted trees with an explicit penalty on tree complexity. It uses gradients and second derivatives, called Hessians, to estimate how useful a correction will be before adding it.

Penalize extra leaves and large corrections

Its objective combines the loss over records with a penalty for every tree. A common penalty is

Ω(f)=γT+12λ∑j=1Twj2,

where T counts leaves and wj is a leaf correction. An optional L1 term, α∑j∣wj∣, can set small corrections to zero. The penalty favors smaller trees and less extreme updates.

For half squared error, each record has gradient gi=y^i−yi and Hessian hi=1. For binary log loss, gi=pi−yi and hi=pi(1−pi). In a leaf, sum them to obtain G and H. With L2 regularization and no L1 term or additional weight constraint, the optimal correction is

w∗=−GH+λ.

Larger lambda shrinks the correction, especially when the leaf has a small Hessian sum. For log loss, a small sum can reflect confident probabilities, not simply a small record count.

Score a split

The textbook regularized improvement is

12[GL2HL+λ+GR2HR+λ−(GL+GR)2HL+HR+λ]−γ.

It compares the two children's achievable fit with the parent's and charges for the additional leaf. Keep the implementation scale separate: XGBoost computes the bracketed split score without the factor one-half and compares that score with its gamma setting (min_split_loss).

For four records with current prediction 16 and targets 10, 12, 20, 22, gradients are 6, 4, −4, −6 and all Hessians are 1. At the middle split, GL=10, HL=2, GR=−10, and HR=2. With lambda 1 and no split penalty, textbook improvement is 12(100/3+100/3)≈33.3. The other two split positions each give 13.5.

The winning leaf weights are −10/3 and +10/3. Learning rate 0.3 changes predictions from 16 to 15 or 17. XGBoost's implementation split score is about 66.7; gamma=40 permits it and gamma=80 blocks it. Comparing 40 directly with 33.3 would mix scales.

Match each setting to its job
SettingRole; documented default
reg_lambdaL2 shrinkage of leaf weights; 1
reg_alphaL1 shrinkage, possibly to zero; 0
gammaMinimum implementation split score; 0
min_child_weightMinimum child Hessian sum; 1
learning_rate (eta)Scale of each correction; 0.3
max_depthMaximum tree depth; 6
subsampleFraction of training rows per tree; 1
colsample_bytreeFraction of features per tree; 1

For unweighted half squared error, the Hessian sum equals the number of records. For log loss, it does not. objective="reg:squarederror" selects regression; "binary:logistic" selects binary probabilities; "multi:softprob" selects multiclass probabilities. Histogram tree construction is the default chosen by "auto" since version 2.0. For imbalanced binary classes, a starting scale_pos_weight is negatives divided by positives: 900 negatives and 100 positives give 9.

Stop using validation performance

An example for already prepared training and validation features is:

from xgboost import XGBClassifier

model = XGBClassifier(
    n_estimators=2000,
    learning_rate=0.05,
    early_stopping_rounds=50,
    eval_metric="logloss",
    random_state=7,
)
model.fit(X_train, y_train, eval_set=[(X_val, y_val)])
best_round_count = model.best_iteration + 1

Early stopping waits for 50 rounds without improvement. best_iteration is zero-based, so add one for the chosen round count. The scikit-learn wrapper uses the best iteration for prediction; the fitted object can still retain later trees. Use the validation set for stopping and keep the test set untouched.

XGBoost learns a default direction for missing feature values at each split. Related libraries share the boosted-tree idea: LightGBM uses histograms and leaf-wise growth, while CatBoost specializes in categorical features with ordered target statistics. scikit-learn's histogram implementation is inspired by LightGBM.

Key Takeaways

  • XGBoost penalizes leaf count and leaf weights.
  • With L2 only, a leaf correction is negative gradient sum divided by Hessian sum plus lambda.
  • Use the library split-score scale when choosing gamma.
  • Minimum child weight is a Hessian constraint, not generally a record count.
  • Early stopping uses validation data; the best iteration index starts at zero.
  • XGBoost learns missing-value directions at splits.
  • LightGBM and CatBoost offer related boosted-tree implementations.
5

Find what the fitted model relies on

Feature importance gives a compact view of a model with many trees, but the meaning depends on how importance is measured. Training impurity reduction shows which features built the fit; shuffling held-out features shows which inputs help a chosen score. Work through both calculations, then examine correlated inputs, leakage, and plots that show how predictions change. Each method answers a specific question about the model.

5.1 Training impurity reduction as importance

A tree records which features supplied its splits. Mean decrease in impurity, or MDI, totals the impurity improvement credited to each feature. This is a quick view of how the model fitted its training data.

Weight each split by how many records it serves

For a split at node t, its contribution is

ntn[I(t)−nLntI(L)−nRntI(R)].

The inner expression is the local impurity decrease. The outer factor weights it by the share of all training records reaching that node. A root split serves every record; a deep split may serve very few.

Add the contributions of all splits using the same feature, then normalize the feature totals to sum to one when there is positive reduction. In a forest, combine the per-tree normalized importances. scikit-learn exposes the result as feature_importances_. A feature never selected for splitting receives zero.

Compute a two-feature example

A churn tree has 100 customers, 50 of whom churned. Parent Gini is 0.5. A tenure split makes 60-record and 40-record children, with 45 and 5 churners. Their Gini impurities are 0.375 and 0.21875. The root decrease is

0.5−[0.6(0.375)+0.4(0.21875)]=0.1875.

The 60-record child splits on plan into equal groups with 28 and 17 churners. Their mean Gini is about 0.308. The local decrease is about 0.067, but this split serves only 60% of the dataset. Its total-data contribution is about 0.6(0.067)=0.040.

The combined contribution is about 0.2278. Normalization gives tenure roughly 0.82 and plan 0.18. Omitting the 0.6 factor would overstate the plan split's importance.

Read the number within its limits

An importance of 0.82 means a large share of this model's normalized training impurity reduction came from tenure. It has no target units and gives no direction. It does not say that adding a month of tenure lowers churn by 82%, or even that longer tenure lowers it at all.

MDI favors high-cardinality features: continuous measurements and identifiers offer many candidate thresholds. More chances to search can produce a large training improvement by luck. A random customer ID can therefore rank well in deep trees without helping on new customers.

Correlated features can divide the credit. Floor area in square meters and room count may substitute for each other across splits. Each can appear modest even when their shared information is useful. Removing one can raise the other's importance without changing the underlying relationship.

Label XGBoost charts precisely
Importance typeWhat it measures
weightNumber of splits using the feature
gainAverage gain of those splits
coverAverage Hessian sum at those splits
total_gainSum of gains
total_coverSum of Hessian coverage

The tree-based scikit-learn wrapper defaults to gain importance. Split count and average gain can rank features differently: a frequent feature need not make the largest improvements. Cover is approximately a record count for unit-Hessian squared error, but for classification it also reflects probability-dependent curvature. State the importance type and dataset when presenting a chart.

Key Takeaways

  • MDI weights local split improvement by the share of training records at the node.
  • Normalized importance describes training fit and has no effect direction.
  • Many candidate thresholds can inflate importance for high-cardinality features.
  • Correlated features can share credit.
  • XGBoost gain, split count, and cover measure different quantities.

5.2 Shuffling features and explaining effects

A feature can help a model memorize training records without helping it predict new ones. Permutation importance checks reliance through a score: how much does performance change when a feature's values are shuffled?

Run the shuffle experiment

First score the fitted model on held-out data. Shuffle one input column across records, leaving the model, targets, and other columns fixed. Score again. With a higher-is-better score, importance is baseline score minus shuffled score. Repeat several times and average the drops.

A model has validation accuracy 0.85. Shuffling tenure gives accuracies 0.78, 0.80, 0.79, 0.77, and 0.81. Their mean is 0.79, so importance is 0.06: a six-percentage-point accuracy drop. The standard deviation across these shuffles is about 0.014.

Shuffling customer ID instead gives 0.85, 0.84, 0.86, 0.85, and 0.85. The mean is unchanged. This experiment measures no average accuracy benefit from ID. It does not establish that every prediction stays unchanged; an accuracy score can miss probability changes.

For prepared validation features, a probability-based score can be used directly:

from sklearn.inspection import permutation_importance

result = permutation_importance(
    model, X_val, y_val,
    n_repeats=10,
    scoring="roc_auc",
    random_state=7,
)

The procedure works with many model types and avoids MDI's preference for many possible split thresholds. Small negative results near the shuffle variation provide little evidence of a benefit; a shuffle can improve the measured score by chance. A high training importance with low validation importance suggests overfitting.

Check what a shuffle changes

Two correlated features can cover for each other. Shuffling floor area may have little effect if room count still carries similar information. Shuffling room count alone may also have little effect. Both low scores can coexist with useful shared information.

One approach is to cluster correlated features and retain a representative from each group. Another is to shuffle the group together and report group importance. The question becomes how much that collection of information helps the model.

Importance describes predictive reliance, not causation. A feature such as "date of refund" may be highly predictive of churn because it becomes available after a customer leaves. Audit suspiciously strong features against what is known at prediction time. Held-out evaluation cannot repair a feature that leaks the outcome in every split.

Show direction with a different tool

A partial dependence plot varies one feature across a grid, predicts with each grid value while retaining other observed features, and averages the predictions. It can show predicted churn falling as tenure rises from 1 to 24 months. Strong feature correlations can make some tested combinations unrealistic, so interpret the curve with the input relationships in mind.

SHAP values allocate an individual model output among feature contributions relative to a baseline. The baseline plus the contributions equals the explained output. Keep the output scale explicit: an XGBoost classifier explained on its raw scale uses log-odds, not probability points. TreeSHAP computes these contributions efficiently for tree models.

Use MDI for a quick training overview, held-out permutation importance to check generalization, and partial dependence or SHAP for effect shape or individual contributions. Report the method, dataset, and metric or output scale so readers can interpret the result correctly.

Key Takeaways

  • Permutation importance measures a score drop after shuffling one feature.
  • Repeated shuffles reveal variation in the measured drop.
  • Correlated features can hide individual importance.
  • Predictive importance is not a causal effect; inspect strong features for leakage.
  • Partial dependence shows average model response; SHAP attributes individual outputs.
  • SHAP values and their baseline must use the same output scale.
6

Tune fairly and choose a usable model

A good model choice combines validation performance with the cost of training, serving, and explaining predictions. Forests usually need a few targeted checks; boosting needs coordinated choices about correction size, tree size, and stopping. Keep preprocessing and selection within the training process, compare candidates on the same evaluation design, and save the test data for the final estimate of the chosen model.

6.1 A focused random forest tuning workflow

Random forests are useful early candidates because they often perform well with little tuning. Most gains come from changing how diverse and how detailed the trees are. The tree count mainly determines how stable the final average has become.

Stabilize the average first

Check out-of-bag or cross-validated performance at tree counts such as 50, 100, 200, 500, and 1,000. Once the curve has leveled off, additional trees mainly cost time and memory. They do not play the same complexity role as extra sequential boosting rounds.

A score curve can wiggle because of random sampling. Look for stable performance across a sensible range, instead of treating a tiny difference between two large forests as a meaningful accuracy optimum.

Tune diversity and leaf size

max_features is often the most influential forest setting. Try "sqrt", 0.33, 0.5, and 1.0 as appropriate for the number of inputs. Smaller candidate sets reduce correlation between trees. Larger sets can help when useful predictors are rare among many noise features.

Then inspect min_samples_leaf, with candidates such as 1, 3, 5, and 10. Larger leaves smooth responses and base classification probabilities on more examples. A depth limit can reduce tree size and memory. max_samples changes the size of each bootstrap draw and offers another control over diversity.

OOB tuning needs only one fit per setting. Three feature-subset choices and three leaf-size choices give nine settings: nine OOB fits versus 45 fits for five-fold cross-validation. Use enough trees for OOB coverage, and keep a separate test set because selecting the best OOB score introduces selection optimism.

Handle class imbalance with the objective in mind

For class_weight="balanced", each record of class k receives weight

wk=nKnk,

where n is the record count, K the number of classes, and nk the class count. With 1,000 records and 100 positives, positives receive weight 5 and negatives about 0.56. Each class then contributes the same total training weight. This changes the fit, not the underlying class frequencies in the population.

Threshold selection is a different choice. Fit the model, obtain validation probabilities, and select a threshold that meets the required recall or precision trade-off. Use the evaluation metric that reflects the task. A high accuracy can still miss a rare class, and class weighting does not guarantee a required recall.

Keep preprocessing within validation

Imputers and encoders learn from data too. Place them in a scikit-learn Pipeline so that each cross-validation fit learns preprocessing only from that fold's training rows. Transform the held-out fold using those fitted steps.

For a numeric-only table requiring imputation, a candidate pipeline is:

from sklearn.pipeline import make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.ensemble import RandomForestClassifier

candidate = make_pipeline(
    SimpleImputer(strategy="median"),
    RandomForestClassifier(
        n_estimators=500,
        min_samples_leaf=3,
        random_state=7,
        n_jobs=-1,
    ),
)

Cross-validate the whole pipeline. If target encoding is used, training rows also need the encoder's internal cross-fitting. For OOB estimates, remember that a preprocessor fitted on all training rows is shared by the trees: OOB omission alone does not create a fold-local preprocessing fit.

Key Takeaways

  • Set enough trees for stable performance, then tune tree diversity and size.
  • max_features balances lower correlation against individual-tree strength.
  • OOB tuning saves fits but still requires a final test set.
  • Class weights change training contributions; threshold tuning changes decisions.
  • Cross-validate the whole preprocessing pipeline.

6.2 Search boosting settings without spending the test set

Boosting settings work together. A smaller correction can help only if the model is allowed enough rounds to learn; a deeper correction may need stronger regularization. Organize the search around these relationships instead of trying every combination at once.

Give each setting a role
GroupMain settingsEffect
Learning progresslearning_rate, n_estimatorsCorrection size and number of rounds
Tree sizemax_depth, min_child_weight, leaf limitsDetail and interactions per correction
Randomnesssubsample, colsample_bytreeRecords and features available per tree
Regularizationreg_lambda, reg_alpha, gammaShrinkage and split restraint

A practical start is learning rate 0.05 or 0.1 with a large round limit and early stopping. Tune tree size, sampling, and penalties around it. Then try a smaller rate with more rounds if the validation results justify further work. Lowering the rate while holding an already restrictive tree count fixed can leave the model underfit.

Possible search ranges include depths 3–8, min_child_weight 1–10, and row and column fractions 0.5–1.0. Sample learning rates 0.01–0.3 and L2 penalties 0.1–10 on a log scale: multiplying the value is more meaningful here than adding the same increment.

Count the computational cost

A grid with 3 rates, 3 depths, 2 row fractions, and 2 child-weight choices has 3×3×2×2=36 settings. Five-fold cross-validation needs 180 fits.

Randomized search draws parameter combinations from ranges. Thirty draws with five folds need 150 fits and avoid spending a fixed grid budget on every combination of a few arbitrary values. If each independent draw has a 5% chance of being good, 60 draws find at least one good setting with probability 1−0.9560≈0.95. This calculation depends on that assumed good fraction; it does not promise a specific gain on a dataset. Bayesian tools such as Optuna instead use earlier results to guide later trials.

Keep stopping data separate from fitting data

Training data fit the trees. Validation data choose settings and the stopping round. Test data evaluate the completed selection once. An early-stopping curve is part of model selection, so the test set must not supply that curve.

During cross-validation, each fold's early-stopping observations must be outside that fold's tree-fitting subset. Use the fold's held-out part or an inner validation split. A single global eval_set can accidentally overlap fold training rows, invalidating the intended separation. Fit preprocessing on the fitting subset and transform the stopping subset with the same fitted preprocessing.

Refit and inspect the curves

After selecting settings, refit on all development data with a fixed number of rounds obtained from early stopping. For XGBoost, best_iteration counts from zero: index 74 corresponds to 75 rounds, so a standard one-tree-per-round refit uses n_estimators=75. Evaluate once on the test set after this choice is fixed.

Plot training and validation loss across rounds. Falling training loss with rising validation loss indicates overfitting. Earlier stopping, shallower trees, more subsampling, or stronger penalties can address it; a lower learning rate usually also needs a new round budget. Compare the changes using validation scores, keeping the final test assessment independent.

Key Takeaways

  • Tune the learning rate together with the number of rounds.
  • Randomized search avoids the full combinatorial cost of a grid.
  • Use log-scale ranges for positive parameters whose effects depend on ratios.
  • Each fold needs early-stopping data excluded from its own fitting rows.
  • Refit with a fixed chosen round count before the final test evaluation.
  • Training and validation loss curves diagnose excess boosting complexity.

6.3 Choose for the data, the trend, and the user

The most useful model depends on the input structure and the job its predictions must do. Predictive score matters, but so do extrapolation, explanations, probability quality, and serving cost.

Start from the input and required behavior

For tabular data, such as customer records or sensor measurements, random forests and gradient-boosted trees are strong candidates. They learn nonlinear effects and interactions with little manual feature construction. Neural networks usually suit raw images, audio, and text better because they learn features from the unstructured input.

NeedUseful candidate
A few visible decision rulesShallow or pruned single tree
Strong tabular baseline with modest tuningRandom forest
High tabular accuracy with tuning time availableGradient-boosted trees
Near-linear effects or reported coefficientsLinear or logistic regression
Very wide sparse inputs, such as word countsLinear or logistic regression

A single tree is easy to draw but often loses predictive accuracy to an ensemble. Forest trees train in parallel and tend to be less sensitive to tuning. Boosting trains successive corrections and can achieve stronger tabular results after careful selection.

Check extrapolation before choosing a tree

A squared-error regression tree predicts training-target means in its leaves. A forest averages those means, so it remains within the training target range. For a boosted tree model, the sum is also constant once a feature moves beyond all its split thresholds, with the other features fixed. Its numeric output need not stay within the training target range, but it does not continue a sloping trend.

In the bike example, a tree trained over 5–30 °C repeats its outer-leaf prediction at 40 °C. If demand truly continues rising there, more trees do not supply that missing extrapolation rule. A justified linear model can extend a trend, although its validity beyond observed data still depends on the relationship holding.

Compare candidates on equal terms

Use the same validation folds, metric, and data access for each candidate. Apply the same leakage-safe preprocessing policy, while allowing preprocessing that each model needs; for example, scaling matters for some linear procedures but not for tree splits.

Include a simple mean or majority-class baseline and a linear or logistic candidate where suitable. Measure training time, prediction time, model size, and explanation needs alongside the validation score. A tiny score gain may have little value if the deployed system cannot meet its response-time or memory limits.

Evaluate probabilities as probabilities

A classifier can rank examples well while giving poorly calibrated probabilities. Calibration asks whether outcomes occur about as often as the predicted probabilities indicate: among records assigned about 0.7, roughly 70% should be positive over comparable cases.

Use a calibration curve on validation data when probabilities feed decisions directly. scikit-learn's CalibratedClassifierCV can fit sigmoid or isotonic recalibration using data separated appropriately from the base-model fitting. Choose the model and calibration procedure within validation, then assess the complete procedure once on the test data. A high ROC AUC alone does not establish that its probabilities are numerically reliable.

Key Takeaways

  • Choose a model for both its inputs and its required prediction behavior.
  • Single trees explain short rule paths; ensembles often improve tabular accuracy.
  • Tree ensembles do not extend a learned slope beyond their outer split thresholds.
  • Use the same validation design and relevant baselines for model comparisons.
  • Check memory, latency, and explanation needs alongside predictive scores.
  • Ranking quality and probability calibration are different properties.

Decision Trees and Ensemble Methods examples

6 Walkthroughs

1

Grow and read a small prediction tree

16 steps
Trace a record, compare class splits, and choose a regression threshold.
  1. 1
    IntroductionTurn a table into local rules

    A tree divides records into groups and attaches a prediction to each group. First read the route a record follows from the root to a leaf. Then put numbers on a split's improvement, so that a clear-looking rule can be judged against alternatives. Classification measures class mixture, such as Gini impurity; regression measures deviations from a group mean.

  2. 2
    ExplanationStart at the root

    The root is the first test, branches represent its answers, and leaves hold predictions. CART gives every test two outcomes, so each record follows exactly one path. Depth counts the splits on the longest path, not the total number of nodes. A short path can finish before other branches do.

  3. 3
    ExampleTrace a service request

    A tree asks, "Has the device operated for more than 800 hours?" No reaches failure probability 0.08. Yes leads to "Is vibration above 6 mm/s?" That test reaches 0.70 for yes and 0.25 for no.

    A device at 900 hours and 7 mm/s follows yes, yes, reaching 0.70. A device at 500 hours stops at 0.08, without testing its vibration.

  4. 4
    ChallengeFollow the boundary exactly

    The same tree tests operating time greater than 800 hours, then vibration greater than 6 mm/s. What probability does a device at exactly 800 hours and 9 mm/s receive, and why?

    ---reveal---

    It receives 0.08. Exactly 800 does not satisfy "greater than 800", so the first answer is no and the path ends. The large vibration value is never consulted on this route.

  5. 5
    Key InsightA leaf summarizes training records

    An unweighted classification leaf with 14 failures among 20 records estimates failure probability 0.70. A squared-error regression leaf instead predicts the mean numeric target of its records. These are local group summaries: a class proportion and a numeric mean answer different questions, even when both come from the same route through a tree.

  6. 6
    ExplanationMeasure class mixture

    For two classes with positive proportion p, Gini impurity is 2p(1−p). A balanced node has Gini 0.5; a pure one has zero. Entropy also measures mixture, using −∑kpklog⁡2pk, and reaches 1 bit for two balanced classes. A useful split lowers the size-weighted mixture of its children.

  7. 7
    ExampleCalculate the parent and children

    A 12-record parent has 6 positives and 6 negatives, giving Gini 0.5. A proposed split makes a pure child of 4 positives and a child with 2 positives and 6 negatives.

    The larger child's positive proportion is 1/4, so its Gini is 2(1/4)(3/4)=0.375. The pure child's Gini is zero. Now weight their contributions by their record counts.

  8. 8
    ExampleCombine the child impurities

    The 4-record child has weight 1/3 and the 8-record child has weight 2/3. Weighted child Gini is

    412(0)+812(0.375)=0.25.

    The parent had Gini 0.5, so the decrease is 0.25. An equal average would give 0.1875 and exaggerate the improvement, because it gives the smaller pure child too much weight.

  9. 9
    ChallengeCompare a competing split

    For the same balanced 12-record parent, another split makes two children of six records: class counts (4, 2) and (2, 4). Which split has the larger Gini decrease: this one or the split with weighted Gini 0.25?

    ---reveal---

    Each new child has Gini 4/9, so their weighted impurity is also 4/9, about 0.444. Its decrease is only about 0.056. The earlier split's decrease of 0.25 is larger.

  10. 10
    ExplanationPut thresholds between distinct values

    A numeric feature with sorted distinct values 2, 4, 8, and 10 has candidate thresholds 3, 6, and 9. Any threshold inside one of those gaps makes the same training groups. Repeating a value adds no new gap. With n distinct values there are n−1 candidates, each of which can be scored using the target values.

  11. 11
    ExampleCalculate regression leaf means

    At feature values 2, 4, 8, 10, suppose the targets are 6, 8, 18, 20. The parent mean is 13. Splitting at 6 gives means 7 and 19.

    The left deviations are −1 and 1, and so are the right deviations. Total child SSE is 1+1+1+1=4. Each child prediction is constant, even for inputs between the observed feature values.

  12. 12
    ExampleCheck the competing thresholds

    The parent SSE is 49+25+25+49=148. A threshold at 3 leaves target 6 alone and targets 8, 18, 20 together, with mean 46/3. Their total SSE is 248/3, about 82.67. Threshold 9 gives the same SSE by symmetry.

    Threshold 6 wins with SSE 4. The tree searches for the smallest total child error, using a separate mean in each child.

  13. 13
    ChallengePredict beyond the observed inputs

    The fitted stump predicts 7 for feature values at most 6 and 19 above 6. What does it predict at 25, and does this continue the increase in the observed targets?

    ---reveal---

    It predicts 19. The record still reaches the right leaf, which holds a constant mean. The model does not extend the slope suggested by the observations; a more distant input alone does not create another split or a larger prediction.

  14. 14
    TipPrepare categories and missing values

    Ordinary scikit-learn trees and forests need numeric category representations. One-hot encoding creates a column per category; ordinal encoding groups categories in code order. Target encoding must cross-fit training rows so their own labels cannot enter their values. Use native missing-value handling where supported, or fit an imputer inside the validation pipeline.

  15. 15
    ChallengeExplain a misleading improvement

    A fitted tree becomes deeper, its training impurity falls, and its validation accuracy gets worse. A colleague concludes that the split calculations must be wrong. What better explanation connects the calculations to the observed scores?

    ---reveal---

    The calculations can be correct while the model overfits. Splits are chosen to improve training purity, and finer regions can capture noise. Their local training improvement does not establish improved prediction on unseen records.

  16. 16
    RecapSeparate reading, fitting, and evaluation

    Read a tree by following its tests to a leaf. Fit it by comparing size-weighted class impurity or regression SSE. Evaluate its usefulness with held-out performance: that is the part a training split calculation cannot settle. Constant leaf predictions also explain why a tree's behavior outside observed inputs needs special attention.

2

Choose which branches earn their place

12 steps
Diagnose excess depth and compare a subtree with a replacement leaf.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionMake complexity a measured choice
  2. 2
    ExampleRead a depth comparison
  3. 3
    ExplanationChoose a growth control
  4. 4
    ChallengeCheck both children
  5. 5
    Key InsightA weak first step may enable the pattern
  6. 6
    ExplanationAdd a price per leaf
  7. 7
    ExampleCalculate the replacement risk
  8. 8
    ExampleFind the equality point
  9. 9
    ChallengeCount the leaves saved
  10. 10
    TipFollow the path, then validate
  11. 11
    ChallengeKeep the final score independent
  12. 12
    RecapUse two kinds of evidence
3

Build diversity and calculate OOB predictions

15 steps
Resample records, compare votes, and use only eligible trees for evaluation.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionAverage errors that differ
  2. 2
    ExampleRead a bootstrap draw
  3. 3
    ExplanationCalculate an omission probability
  4. 4
    ExampleCompare two ways of combining classes
  5. 5
    ChallengeLocate the variance floor
  6. 6
    ExplanationRandomize features at every split
  7. 7
    ExampleWork out feature availability
  8. 8
    ChallengePredict what too much restriction can do
  9. 9
    ConnectionKnow the implementation choices
  10. 10
    ExampleSelect eligible OOB trees
  11. 11
    ChallengeScore one omitted record
  12. 12
    TipRead the OOB score field
  13. 13
    ChallengeDiagnose a suspiciously strong OOB result
  14. 14
    Key InsightTuning spends evaluation information
  15. 15
    RecapTrack diversity and eligibility
4

Calculate boosting corrections on the right scale

18 steps
Fit residual trees, update log-odds, and regularize an XGBoost split.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionBuild one evolving prediction
  2. 2
    ExampleStart at the target mean
  3. 3
    ExampleApply shrinkage once
  4. 4
    ChallengeTake the next round
  5. 5
    ConnectionChoose the correction size and shape
  6. 6
    ExplanationLet the loss define the residual
  7. 7
    ExampleInitialize binary log-odds
  8. 8
    ExampleCalculate a classification leaf update
  9. 9
    ChallengeSpot the wrong output scale
  10. 10
    TipSelect a training implementation
  11. 11
    ExplanationUse gradient and Hessian sums
  12. 12
    ExampleShrink a two-child correction
  13. 13
    ExampleCompare gain scales carefully
  14. 14
    ChallengeDistinguish record count from curvature
  15. 15
    ExplanationMatch penalties to their role
  16. 16
    TipRead early stopping without an off-by-one error
  17. 17
    ChallengeCombine split control with validation
  18. 18
    RecapTrack three different scales
5

Read importance without overclaiming

12 steps
Calculate training credit, shuffle a feature, and inspect correlated information.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionChoose the question before the chart
  2. 2
    ExampleWeight a deep split
  3. 3
    ExampleNormalize the contributions
  4. 4
    ChallengeQuestion a strong identifier
  5. 5
    TipName the importance measure
  6. 6
    ExplanationHold the model fixed and shuffle
  7. 7
    ExampleCalculate a validation drop
  8. 8
    ChallengeInterpret two small individual scores
  9. 9
    ConnectionShow the direction of a prediction effect
  10. 10
    ChallengeCheck attribution units
  11. 11
    ChallengeCheck a predictor available too late
  12. 12
    RecapReport the measurement and its setting
6

Select a model with an honest final score

14 steps
Plan tuning cost, handle class imbalance, and check the deployment requirements.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionChoose the whole procedure
  2. 2
    ExplanationStabilize a forest before fine tuning
  3. 3
    ExampleBudget a forest comparison
  4. 4
    ExampleCalculate balanced weights
  5. 5
    ChallengeChoose where a threshold comes from
  6. 6
    ExplanationCoordinate progress and complexity
  7. 7
    ExampleCount search fits
  8. 8
    ChallengeDetect overlap in early stopping
  9. 9
    TipTurn the selected index into a refit count
  10. 10
    ConnectionMatch the model to the required behavior
  11. 11
    ChallengeJudge an extrapolation requirement
  12. 12
    ExplanationCheck probability quality
  13. 13
    ChallengeKeep a fair comparison intact
  14. 14
    RecapFix choices before the final evaluation

Decision Trees and Ensemble Methods practice questions

50 Practice Questions in 5 sets

Set 1: Read, grow, and prune a tree10 Practice Questions

Question 1 of 10

A squared-error regression leaf contains target values 9, 12, and 21. What number does it predict?
  1. 12
  2. 15
  3. 14
  4. 21
Show answerHide answer
Answer: C
A squared-error leaf predicts its training target mean: (9 + 12 + 21)/3 = 14. The value 12 is the median, which belongs to an absolute-error leaf rule; choosing an observed middle value does not minimize squared error in this group.

Question 2 of 10

A tree tests "moisture ≤ 35%?" at the root. Yes leads to "temperature > 22 °C?", with yes predicting 80 and no predicting 50. No at the root predicts 20. What does it predict for moisture 35% and temperature 22 °C?
  1. 50
  2. 80
  3. 20
  4. 65
Show answerHide answer
Answer: A
Moisture 35% satisfies the root condition, so the record reaches the temperature test. Exactly 22 °C does not satisfy "greater than 22", leading to prediction 50. Prediction 80 would treat a strict inequality as if its boundary were included.

Question 3 of 10

A node has 9 positive and 3 negative records. What is its Gini impurity?
  1. 0.250
  2. 0.625
  3. 0.750
  4. 0.375
Show answerHide answer
Answer: D
The class proportions are 0.75 and 0.25, giving Gini 1 − 0.75² − 0.25² = 0.375. The value 0.25 is the majority-label misclassification error. It counts label mistakes but does not use both squared proportions as Gini does.

Question 4 of 10

A parent has 20 records. A split makes a pure child of 5 records and a child of 15 records with Gini 0.32. What is the weighted child Gini?
  1. 0.16
  2. 0.24
  3. 0.08
  4. 0.32
Show answerHide answer
Answer: B
The children have weights 5/20 and 15/20, so their combined impurity is (5/20)0 + (15/20)0.32 = 0.24. The value 0.16 gives both children equal influence even though the impure child contains three times as many records.

Question 5 of 10

A node has 8 positives and 8 negatives. Split P makes children with class counts (6, 0) and (2, 8). Split Q makes children (6, 2) and (2, 6). Which split has the larger Gini decrease, and what is that decrease?
  1. Q, with decrease 0.125
  2. P, with decrease 0.300
  3. P, with decrease 0.340
  4. Q, with decrease 0.375
Show answerHide answer
Answer: B
The parent Gini is 0.5. P has weighted child Gini (6/16)0 + (10/16)0.32 = 0.20, so its decrease is 0.30; Q has child Gini 0.375 and decrease 0.125. A decrease of 0.34 for P comes from averaging its child impurities equally instead of weighting their sizes.

Question 6 of 10

A numeric feature takes values 1, 1, 5, 9, and 9 in a node. What distinct midpoint thresholds cover its possible training partitions?
  1. 1, 5, and 9
  2. 1, 3, 7, and 9
  3. 2, 4, 6, and 8
  4. 3 and 7
Show answerHide answer
Answer: D
The distinct sorted values are 1, 5, and 9. Their adjacent midpoints are 3 and 7, each defining a different partition. Repeated 1s or 9s create no new gap, so counting every row as a distinct threshold opportunity overcounts the candidates.

Question 7 of 10

For ordered feature values 1, 3, 5, 7, the targets are 2, 4, 10, 12. A squared-error stump may split at any candidate midpoint. Which threshold and pair of leaf predictions minimize SSE?
  1. Threshold 4; means 3 and 11
  2. Threshold 2; means 2 and 9
  3. Threshold 6; means 5 and 12
  4. Threshold 4; means 2 and 10
Show answerHide answer
Answer: A
The three midpoint thresholds are 2, 4, and 6. At 4, child means 3 and 11 give total SSE 4; the outer splits each give SSE 104/3, about 34.67. Predicting 2 and 10 after the middle split uses the first target in each group instead of its mean.

Question 8 of 10

A proposed split creates children with 11 and 3 records. Which setting directly blocks it by requiring at least four records in each child?
  1. min_samples_split=4
  2. max_leaf_nodes=4
  3. min_samples_leaf=4
  4. max_depth=4
Show answerHide answer
Answer: C
Minimum leaf size applies to both children after a split, so the three-record child violates a value of four. Minimum split size checks the parent, which has fourteen records here, and therefore would not block this candidate on the same grounds.

Question 9 of 10

A depth-3 tree has training/validation accuracies 0.84/0.82; depth 6 has 0.95/0.88; an unrestricted tree has 1.00/0.83. Which candidate should these validation results favor?
  1. Depth 6; its held-out score is highest.
  2. Unrestricted; it fits training perfectly.
  3. Depth 3; its accuracy gap is smallest.
  4. Unrestricted; more leaves lower its bias.
Show answerHide answer
Answer: A
Depth 6 gives the highest validation accuracy, 0.88, so it is the strongest candidate in this comparison. The unrestricted tree improves training fit but loses validation performance. A smaller gap alone is not the objective either: depth 3 has a small gap while underperforming on validation.

Question 10 of 10

A three-leaf subtree has weighted training risk 0.04. Collapsing it gives risk 0.10. What is its effective alpha?
  1. 0.02
  2. 0.06
  3. 0.07
  4. 0.03
Show answerHide answer
Answer: D
Collapse raises risk by 0.10 − 0.04 = 0.06 and removes two leaves, giving effective alpha 0.03. Dividing by three gives 0.02 but counts all original leaves as removed. One replacement leaf remains, so the saved complexity is three minus one.
Set 2: Resampling, forests, and honest OOB scores10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A bootstrap sample is drawn from six training records. How many draw positions does the usual sample contain, and can a record repeat?
  1. Six positions; repeats are forbidden.
  2. Six positions; repeats are allowed.
  3. About four positions; repeats are allowed.
  4. About four positions; repeats are forbidden.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Five trees predict positive probabilities 0.52, 0.52, 0.52, 0.10, and 0.10. What do hard and soft voting predict at a 0.5 threshold?
  1. Hard: positive; soft: negative.
  2. Hard: positive; soft: positive.
  3. Hard: negative; soft: positive.
  4. Hard: negative; soft: negative.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Forest A has individual-tree prediction variance 16 and pairwise correlation 0.1. Forest B has variance 9 and correlation 0.3. Each has 100 trees and satisfies the equal-variance, equal-correlation model. Which average has lower variance, and can doubling B to 200 trees make it lower than A?
  1. B is lower; doubling B preserves its lead.
  2. A is lower; doubling B reverses the ranking.
  3. B is lower; doubling B reverses the ranking.
  4. A is lower; doubling B does not reverse it.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

At what point does an ordinary random forest refresh its random feature-candidate subset?
  1. Once before fitting the forest.
  2. Once at the root of each tree.
  3. At each split within each tree.
  4. After each validation comparison.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A forest has 49 input features. A split considers 7 randomly selected features. What is the probability that one particular feature is absent from the candidates?
  1. 6/7
  2. 1/7
  3. 1/49
  4. 7/42
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

For row Z, trees 1 and 3 used it during training and predict probabilities 0.9 and 0.8. Trees 2 and 4 omitted it and predict 0.3 and 0.5. What is its OOB positive probability?
  1. 0.625
  2. 0.85
  3. 0.40
  4. 0.50
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A forest is trained on repeated rows from each device. Random-row OOB accuracy is high, but deployment will predict on entirely new devices. A device identifier also has high importance. What evaluation design best addresses the concern?
  1. Increase trees and average their OOB scores per device.
  2. Keep row splits and remove only the highest-importance ID.
  3. Keep all rows and tune minimum leaf size using OOB scores.
  4. Hold out devices and refit the whole pipeline per split.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A binary training set has 1,800 records, including 300 positives. What positive and negative per-record weights does class_weight="balanced" give?
  1. Positive 6.0; negative 1.2.
  2. Positive 3.0; negative 0.6.
  3. Positive 5.0; negative 1.0.
  4. Positive 0.6; negative 3.0.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A forest uses a target encoder fitted on all development labels before an OOB search over leaf sizes. You want a reliable final estimate on independent future records. What workflow corrects both information reuse problems?
  1. Keep the global encoder; test the best OOB model once after selection.
  2. Cross-fit the encoder globally; report the winning OOB score as final.
  3. Cross-validate a cross-fitting encoder pipeline; test once after selection.
  4. Keep the global encoder; add trees until the OOB score stops changing.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A deployment needs a model whose predictions can be shown as a few short feature-test paths. Training accuracy is less important than this explanation requirement. Which candidate is the best starting point?
  1. A forest of hundreds of deep trees.
  2. A shallow or pruned single tree.
  3. A boosted sum of shallow trees.
  4. An unrestricted single tree.
Show answerHide answer

Save this lesson to see this answer.

Set 3: Boosting updates and XGBoost decisions10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A boosting model currently predicts 24. The next tree gives correction −6 and the learning rate is 0.2. What is the updated prediction?
  1. 18.0
  2. 25.2
  3. 3.6
  4. 22.8
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Squared-error boosting starts with targets 3, 5, 11, 13. A stump groups the first two and last two records. At learning rate 0.25, what are the predictions after its first round?
  1. 4, 4, 12, 12
  2. −1, −1, 1, 1
  3. 7, 7, 9, 9
  4. 5, 5, 11, 11
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

For ordered feature values 1, 2, 3, 4, targets are 0, 2, 8, 10. Squared-error boosting uses stumps that group the first two and last two records, with learning rate 0.5. What is training MSE after two rounds?
  1. 2.0
  2. 1.0
  3. 5.0
  4. 0.5
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

For binary log loss, what pseudo-residual does a positive record have when its current predicted probability is 0.65?
  1. −0.35
  2. 0.35
  3. 0.65
  4. −0.65
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A binary boosted model has log-odds −0.4. A tree supplies correction 1.2 and learning rate 0.25. What is the updated log-odds score?
  1. 0.8
  2. 0.2
  3. −0.7
  4. −0.1
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A binary log-loss model starts from positive share 0.5. A leaf contains three positives and one negative. Using the unregularized Newton leaf correction and learning rate 0.5, what probability does the first update give records in that leaf?
  1. About 0.731
  2. About 0.622
  3. About 0.750
  4. About 1.000
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

An XGBoost leaf has gradient sum −12, Hessian sum 3, and reg_lambda=1. With L2 only and no other weight constraint, what is its unscaled leaf correction?
  1. 3
  2. −3
  3. 4
  4. −4
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

An XGBoost split has gradient/Hessian sums (6, 2) on the left and (−6, 2) on the right. Set reg_lambda=1, reg_alpha=0, gamma=15, and learning_rate=0.2; other constraints allow it. Does the library allow the split, and what corrections are added?
  1. Blocked; both corrections remain zero.
  2. Allowed; left −2.0, right +2.0.
  3. Allowed; left −0.4, right +0.4.
  4. Allowed; left +0.4, right −0.4.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A proposed binary-log-loss child contains 12 records, all currently predicted at probability 0.9. Its gradient sum is 2.8. With min_child_weight=1, reg_lambda=1, and no other weight constraint, does it meet the child-weight rule, and what is its unscaled correction if retained?
  1. Fails it; correction about −1.346.
  2. Meets it; correction about −1.346.
  3. Meets it; correction about −0.215.
  4. Meets it; correction about +1.346.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A standard binary XGBoost run records best_iteration=87. You refit on all development data with a fixed chosen length and no early stopping. What n_estimators should you use?
  1. 88
  2. 87
  3. 86
  4. 176
Show answerHide answer

Save this lesson to see this answer.

Set 4: Interpret results and select a model10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A feature has normalized MDI 0.70. What does this number describe?
  1. Its share of credited training impurity reduction.
  2. Its probability of causing a positive outcome.
  3. Its average increase in the predicted target value.
  4. Its fraction of correct held-out model predictions.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A split has local Gini decrease 0.18 and receives 25 of the 100 training records. What is its unnormalized whole-tree MDI contribution?
  1. 0.180
  2. 0.720
  3. 0.045
  4. 0.135
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Feature A supplies a root decrease of 0.08 and another decrease of 0.10 at a node reached by 20% of rows. Feature B supplies decrease 0.20 at a node reached by 50%. No other split contributions occur. What are normalized importances A and B?
  1. A: 0.64; B: 0.36.
  2. A: 0.33; B: 0.67.
  3. A: 0.44; B: 0.56.
  4. A: 0.50; B: 0.50.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Validation accuracy is 0.90. Four shuffles of a feature give accuracies 0.85, 0.87, 0.86, and 0.86. What is its mean permutation importance?
  1. 0.86 accuracy points
  2. 0.04 accuracy points
  3. 0.05 accuracy points
  4. 0.96 accuracy points
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Area and room count are strongly correlated. Either column shuffled alone gives an accuracy drop near zero, while both shuffled together give a large drop. MDI assigns most credit to area. What interpretation is supported?
  1. Shared information matters; individual credit depends on the method.
  2. Area alone matters; its larger MDI establishes the unique effect.
  3. Neither input matters; single-column drops settle their joint value.
  4. Both cause the outcome; their joint drop establishes causal influence.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Two binary classifiers are combined by soft voting. For one record, an XGBoost raw-output SHAP explanation has baseline −1.0 and feature contributions +0.6 and +0.8. The second classifier predicts positive probability 0.30. What is the ensemble's positive probability, rounded to three decimals?
  1. About 0.350
  2. About 0.587
  3. About 0.899
  4. About 0.449
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A forest's OOB accuracy is 0.874 with 400 trees and 0.875 with 800, while memory and prediction time nearly double. The scores are stable across repeated seeds. What does this suggest about tree count?
  1. The 800-tree forest is overfitting because it is larger.
  2. The 400-tree forest must be underfitting because it is smaller.
  3. About 400 trees may be sufficient for stable averaging.
  4. Exactly 800 trees are necessary because its score is higher.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

You must compare two boosting settings on four folds. Each fold also needs early stopping and target encoding. What design keeps held-out labels out of that fold's fitting process?
  1. Fit an encoder on all development labels; stop on the held-out fold.
  2. Fit a cross-fitting encoder on fit rows; transform separate stopping rows.
  3. Fit one encoder per fold using both fit and stopping labels before training.
  4. Fit trees on the whole fold; select their length from its training predictions.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Two models have similar validation ROC AUC. One will supply numerical event probabilities for a planning system. What further check directly addresses that use?
  1. Compare only the training ROC AUC curves.
  2. Compare only the number of model parameters.
  3. Compare MDI scores summed across all features.
  4. Compare calibration on held-out validation cases.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Deployment predicts probabilities for new devices and requires latency at most 5 ms. A forest has AUC 0.91 and latency 4 ms, evaluated by random-row splits and calibrated on its fitting rows. A pruned tree has AUC 0.88 and latency 2 ms, with device-held-out validation and separate calibration data. A boosted model has AUC 0.92 and latency 7 ms with device-held-out validation. Which candidate is best supported now, and how should its final performance be assessed?
  1. Forest; report its AUC because its latency satisfies the limit.
  2. Pruned tree; evaluate the fixed procedure on untouched devices.
  3. Boosting; its higher AUC compensates for the extra prediction time.
  4. Pruned tree; report its validation score as the final test result.
Show answerHide answer

Save this lesson to see this answer.

Set 5: Connect the methods in new situations10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A node has 9 positives and 3 negatives. Split U isolates 3 positives, leaving (6 positive, 3 negative). Split V makes children (5 positive, 1 negative) and (4 positive, 2 negative). Which split gives larger Gini reduction, and by how much?
  1. V exceeds U by about 0.0278.
  2. U exceeds V by about 0.0278.
  3. U exceeds V by about 0.0833.
  4. V exceeds U by about 0.0833.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A squared-error regression stump predicts 40 for temperature at most 14 °C and 75 above 14 °C. What does it predict at 42 °C?
  1. 42
  2. 117
  3. 225
  4. 75
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A node receives 30 of 150 rows and has Gini 0.4 if collapsed. Its current four-leaf subtree has total weighted risk 0.02. At ccp_alpha=0.025, is keeping this branch or collapsing it cheaper, and what is its effective alpha?
  1. Collapse is cheaper; effective alpha is 0.020.
  2. Keep is cheaper; effective alpha is 0.020.
  3. Collapse is cheaper; effective alpha is 0.015.
  4. Keep is cheaper; effective alpha is 0.127.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

An ensemble has individual prediction variance 25, pairwise correlation 0.2, and 50 trees. A new version lowers correlation to 0.1 but raises individual variance to 30, keeping 50 trees. Does the new average have lower variance, and what is it?
  1. No; its variance is 6.30.
  2. Yes; its variance is 3.00.
  3. Yes; its variance is 3.54.
  4. No; its variance is 5.40.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

After comparing thirty random-forest settings by OOB accuracy, you select the highest-scoring setting. What score should estimate its final generalization performance?
  1. Its highest observed OOB score across the search.
  2. Its training score after refitting all thirty settings.
  3. Its score on a reserved, untouched test set.
  4. Its OOB score averaged only over winning trees.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A binary boosting model starts at positive share 0.2. A leaf has two positive and two negative records. Using its unregularized Newton correction and learning rate 0.2, what is the updated probability, rounded to three decimals?
  1. 0.575
  2. 0.354
  3. 0.450
  4. 0.267
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

Two valid XGBoost candidate splits share a parent with G=0 and H=8. Split A has child sums (G,H)=(8,4) and (−8,4); split B has (6,2) and (−6,6). With reg_lambda=2, reg_alpha=0, gamma=15, which split has the larger implementation score, and is it permitted?
  1. A is larger and permitted.
  2. B is larger and permitted.
  3. A is larger but blocked.
  4. B is larger but blocked.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A model's accuracy is unchanged after repeated shuffles of feature R, but its ROC AUC falls substantially. Predicted probabilities change, and no data leakage is identified. What interpretation fits both results?
  1. R is unused because zero accuracy drop proves no model reliance.
  2. R helps ranking even though measured label accuracy stays fixed.
  3. R must be causal because ROC AUC responds to its permutation.
  4. R affects only training fit because label accuracy stays unchanged.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A search grid has 4 learning rates, 3 depths, and 3 row fractions. Using five-fold cross-validation, how many model fits does the full grid need?
  1. 36
  2. 60
  3. 540
  4. 180
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A squared-error forest and a boosted-tree regressor fit targets ranging from 10 to 60. On an unseen input, the forest predicts 72 and boosting predicts 68. With standard constant regression leaves and no transformed targets or output adjustment, which output conflicts with its model's structure?
  1. Both outputs conflict because every ensemble averages leaf means.
  2. Only boosting conflicts because its corrections stay in target range.
  3. The forest output conflicts; the boosting output can be valid.
  4. Neither conflicts because all ensembles extrapolate beyond the data.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

85 Key Terms, each with its definition

A

AdaBoost
AdaBoost increases the training emphasis on misclassified examples over successive rounds and combines learners with a weighted vote.
AdaBoost gives more influence to previously misclassified training rows when fitting the next learner.

B

Bagging
Bagging fits models to separate bootstrap samples and combines their predictions, mainly reducing variance for unstable learners.
Bagging makes deep-tree predictions more stable by averaging trees fitted to different resampled tables.
Balanced class weight
A balanced class weight gives each record weight n divided by K times its class count, equalizing total training weight across classes.
A rare class receives a larger balanced class weight per record than a common class.
Baseline model
A baseline model supplies a simple reference score, such as the mean target or majority class, for judging more complex candidates.
A baseline model predicting the majority class helps reveal when a high accuracy is mostly class imbalance.
Bayesian optimization
Bayesian optimization uses earlier trial results to guide later hyperparameter choices toward promising parts of the search space.
An Optuna study can use Bayesian optimization to adapt its next depth and learning-rate trial.
Best iteration
The best iteration is the validation-optimal boosting-round index recorded during early stopping; XGBoost counts that index from zero.
An XGBoost best iteration of 89 corresponds to 90 rounds in the selected prediction model.
Boosting
Boosting builds a model sequentially by adding learners that correct current errors, usually using small trees to reduce bias.
Boosting fits its second tree to errors remaining after the first correction has changed predictions.
Bootstrap sample
A bootstrap sample draws as many records as the original dataset contains, with replacement, allowing repeats and omissions.
A bootstrap sample of six records can contain the same record three times and omit several originals.
Bootstrap sample size
Bootstrap sample size is the number of replacement draws used to fit one tree, controlled by max_samples in a scikit-learn forest.
Reducing bootstrap sample size can make individual trees see fewer distinct records and add diversity.

C

Correlated substitutes
Correlated substitutes are inputs carrying overlapping information, allowing one to preserve predictive signal when another is shuffled.
Two correlated substitutes can each look weak in separate shuffles but matter strongly as a group.
Cost-complexity pruning
Cost-complexity pruning selects a subtree by balancing training leaf risk against a nonnegative penalty for the number of leaves.
Cost-complexity pruning can favor four leaves over twelve when the added fit is small.
Cover importance
Cover importance in XGBoost averages the Hessian mass associated with a feature's splits, reflecting loss curvature as well as reach.
Cover importance for log loss differs from a simple count of records reaching the selected splits.
Cross-fitting
Cross-fitting creates training-row transformations using mappings fitted without those rows, preventing their own targets entering the encoding.
Cross-fitting computes a fold's category values from other folds before training the downstream model.

D

Decision stump
A decision stump is a tree with one split and two leaves, contributing a simple one-feature effect when used in boosting.
A decision stump separates low and high temperatures but cannot include a nested humidity test.
Decision threshold
A decision threshold turns predicted probabilities into class decisions and is selected using validation data for the desired error trade-off.
Lowering a decision threshold can catch more positive cases while increasing false positives.
Decision tree
A decision tree predicts a target by following feature tests that divide records into smaller groups, each ending at a leaf.
A small decision tree predicts equipment failure from operating hours and vibration measurements.

E

Early stopping
Early stopping chooses a useful boosting length by stopping after the validation metric fails to improve for a specified number of rounds.
Early stopping may finish after round 160 while retaining round 130 as the best validation result.
Effective alpha
The effective alpha of a subtree is the increase in training risk on collapse divided by the number of leaves that collapse removes.
An effective alpha of 0.02 marks where a subtree and its replacement leaf have equal penalized cost.
Entropy
Entropy measures class mixture using the negative sum of proportion times base-2 log proportion, with zero-proportion terms set to zero.
Entropy is 1 bit in a binary node whose positive and negative classes are equally common.
Extrapolation
Extrapolation extends a predictive relationship beyond observed input values; constant-leaf trees do not extend a learned slope there.
A temperature model needs extrapolation if it must continue a justified trend beyond the training range.
Extremely randomized trees
Extremely randomized trees add random threshold proposals to feature randomness, then choose the best proposed split at each node.
Extremely randomized trees often fit faster because they do not exhaustively search all numeric thresholds.

F

Feature candidate subset
A feature candidate subset is the randomly selected group of input columns available when a random forest searches one split.
A feature candidate subset of 5 among 25 columns contains a particular column with probability 0.2.

G

Gain importance
Gain importance in XGBoost averages the improvements from splits using a feature, distinguishing improvement size from split frequency.
A rarely used feature can have high gain importance if its few splits make large improvements.
Gini impurity
Gini impurity measures class mixture as one minus the sum of squared class proportions; pure nodes have value zero.
A balanced binary node has Gini impurity 0.5, while a node containing one class has zero.
Gradient sum
A gradient sum adds the current loss derivatives for records in a leaf, summarizing their combined first-order correction demand.
A positive gradient sum gives a negative unconstrained XGBoost leaf correction under L2 regularization.
Greedy splitting
Greedy splitting chooses the best immediate split at each node without searching all possible complete trees for a global optimum.
Greedy splitting can choose a strong first rule even when a different first rule would enable a better full tree.
Grid search
Grid search evaluates every combination in specified lists of hyperparameter values, with fit count growing as their product.
A grid search over 3 rates and 4 depths evaluates twelve settings before accounting for validation folds.
Group-based validation
Group-based validation keeps related records together when splitting data, so held-out groups are absent from model fitting.
Group-based validation holds out all measurements from a person when predicting outcomes for new people.

H

Hard voting
Hard voting selects the class receiving the most predicted labels across models, discarding differences in their probability estimates.
Hard voting gives three narrow positive votes the majority even if two negative votes are very confident.
Hessian sum
A Hessian sum adds second loss derivatives for a group of records, measuring the curvature used in XGBoost updates and child constraints.
A Hessian sum for log loss can be small even in a large leaf when predictions are very confident.
High variance
High variance means a fitted model's predictions are sensitive to changes in the training sample, a common weakness of deep single trees.
High variance can make two trees fitted to slightly different samples choose very different root splits.
High-cardinality feature
A high-cardinality feature has many distinct values, creating many potential thresholds or category representations during tree fitting.
A unique device identifier is a high-cardinality feature that can encourage memorization.
Histogram gradient boosting
Histogram gradient boosting bins feature values before split search, reducing computation and supporting efficient training on large tables.
Histogram gradient boosting avoids testing every distinct raw feature threshold in a large sensor dataset.
Hyperparameter
A hyperparameter is a model setting selected outside the fitting of learned rules, such as tree depth, leaf size, or feature restriction.
A forest hyperparameter search compares leaf sizes using validation scores from the same folds.

I

Information gain
Information gain is a split's reduction in entropy, calculated as parent entropy minus the size-weighted entropy of its children.
The tree prefers the candidate with information gain 0.4 bits over one with gain 0.1 bits at the same parent.
Interaction
An interaction occurs when one feature's effect on a prediction depends on another feature, which trees can express through nested splits.
An interaction makes vibration important for older devices but less useful for newer devices.

L

L2 leaf regularization
L2 leaf regularization penalizes squared leaf corrections, shrinking XGBoost weights through the denominator H plus lambda.
Stronger L2 leaf regularization changes a correction from −6/2 to −6/5 when lambda increases by 3.
Leaf
A leaf is a terminal node that stores a prediction, such as a class proportion or the mean numeric target of its training records.
A classification leaf with 9 positives and 3 negatives estimates positive probability 0.75.
Learning rate
The learning rate scales each tree correction before it is added to the current boosted model, controlling the speed of learning.
A learning rate of 0.1 turns a leaf correction of −5 into an update of −0.5.
Log loss
Log loss penalizes probabilistic classification errors through negative logarithms, strongly penalizing confident incorrect predictions.
Log loss rises sharply when the model assigns probability 0.01 to a positive outcome.
Log-odds
Log-odds are the natural logarithm of p divided by one minus p, forming the additive score in binary log-loss boosting.
Log-odds of zero correspond to probability 0.5 before any positive or negative tree correction.
Log-scale sampling
Log-scale sampling explores positive settings through proportional spacing, giving small and large orders of magnitude meaningful coverage.
Log-scale sampling can compare L2 penalties near 0.1, 1, and 10 without favoring only large values.

M

Mean decrease in impurity
Mean decrease in impurity credits features for training split improvements, weighted by node size and normalized across features.
Mean decrease in impurity can favor a random identifier that supplies many candidate split thresholds.
Minimum child weight
Minimum child weight is the lower bound on a child's Hessian sum in XGBoost, limiting poorly supported or low-curvature leaves.
Minimum child weight cannot be read as a record count for confident binary-log-loss predictions.
Minimum leaf size
Minimum leaf size is the smallest allowed number of training records in each child after a split, limiting very small prediction groups.
A minimum leaf size of 6 blocks a proposed split with children of 18 and 4 records.
Misclassification error
Misclassification error is one minus the largest class proportion in a node, measuring the share misclassified by its majority label.
Two proposed splits can have identical misclassification error but different Gini improvements.

N

Newton leaf correction
A Newton leaf correction uses loss curvature as well as gradients to choose a change in a leaf's additive model score.
The binary Newton leaf correction divides the sum of y − p by the sum of p(1 − p).
Normalized importance
A normalized importance expresses a feature's credited training improvement as a share of the total positive improvement across features.
A normalized importance of 0.6 allocates 60% of training credit without stating an outcome effect size.

O

One-hot encoding
One-hot encoding represents a categorical feature with binary indicator columns, each identifying whether a record has one category.
One-hot encoding turns three service plans into three columns that ordinary tree splits can test.
One-standard-error rule
The one-standard-error rule chooses the simplest candidate whose validation score lies within one standard error of the best score.
The one-standard-error rule can select a more strongly pruned tree with nearly the best validated score.
OOB prediction
An OOB prediction combines only predictions from trees whose bootstrap samples omitted the record being evaluated.
A row's OOB prediction averages 0.2, 0.4, and 0.6 from its eligible trees to obtain probability 0.4.
OOB score
An OOB score evaluates the forest's row-level out-of-bag predictions, providing a held-out-style estimate without extra tree fits.
A classifier's default OOB score of 0.86 means 86% accuracy on its out-of-bag predictions.
Ordinal encoding
Ordinal encoding assigns one numeric code to each category, making threshold-based category groups follow the chosen code order.
Ordinal encoding naturally represents small, medium, and large, but can impose an arbitrary order on colors.
Out-of-bag record
An out-of-bag record is a training record omitted from the bootstrap sample used to fit one particular tree.
The same row can be an out-of-bag record for one tree and appear twice in another tree's sample.

P

Partial dependence
Partial dependence averages model predictions while varying a selected feature and keeping other inputs at observed values.
A partial dependence curve shows how average predicted demand changes across tested temperatures.
Permutation importance
Permutation importance measures the score drop after shuffling a feature in a fixed model's evaluation data, averaged across repeats.
Permutation importance of 0.03 in accuracy means a three-percentage-point drop after shuffling.
Piecewise-constant prediction
A piecewise-constant prediction assigns one fixed output throughout each input region, changing only when a split boundary is crossed.
A regression tree gives a piecewise-constant prediction of 300 rentals for every temperature in its right leaf.
Pipeline
A pipeline combines learned preprocessing and a model into one fitting procedure, keeping those learned steps inside each validation fit.
Cross-validating a pipeline that contains an imputer fits that imputer using each training fold before transforming held-out rows.
Post-pruning
Post-pruning simplifies a grown tree by replacing selected subtrees with leaves, trading some training fit for a smaller rule structure.
Post-pruning removes a detailed branch whose validation benefit is too small to justify its complexity.
Pre-pruning
Pre-pruning restricts a tree during growth using controls such as maximum depth, minimum child size, or minimum impurity improvement.
Pre-pruning with a depth limit prevents the fitted tree from adding a sixth split along any path.
Prediction latency
Prediction latency is the time needed to produce a model output for an input, an operational cost that can increase with many deep trees.
A forest may gain little accuracy from extra trees while its prediction latency exceeds the application limit.
Probability calibration
Probability calibration describes agreement between predicted event probabilities and the event frequencies observed among comparable predictions.
Good probability calibration means cases assigned about 0.7 are positive roughly 70% of the time.
Pruning path
A pruning path is a nested sequence of subtrees obtained by repeatedly removing weakest links as the complexity penalty increases.
The pruning path ends with a candidate that retains only the original root as a prediction leaf.
Pseudo-residual
A pseudo-residual is the negative loss gradient at a record's current score, giving the direction a new boosting tree should follow.
For binary log loss, a positive label with predicted probability 0.2 has pseudo-residual 0.8.

R

Random forest
A random forest combines trees fitted to bootstrap samples while restricting each split to a fresh random subset of input features.
A random forest can force some root splits to use alternatives to the strongest predictor.
Random seed
A random seed sets the starting state for pseudorandom choices, making repeated fits with the same setup reproducible.
A fixed random seed helps compare forest settings without changing every sampling choice arbitrarily.
Randomized search
Randomized search draws a chosen number of parameter combinations from ranges or distributions, controlling the total search budget.
A randomized search can test thirty combinations without evaluating every point in a large grid.
Residual
A residual is the observed target minus the current prediction, giving the correction target in squared-error boosting.
A target of 18 and current prediction of 14 produce a residual of +4 for the next tree to fit.
Root
The root is the first node in a decision tree, where every record starts before following the branches selected by feature tests.
When a tree's root tests contract length, every customer encounters that question first.

S

SHAP value
A SHAP value assigns one feature a contribution to an individual model output relative to a baseline on a specified output scale.
A raw-output SHAP value for an XGBoost classifier contributes log-odds, not probability points.
Soft voting
Soft voting averages model probabilities for each class and selects the class with the highest resulting average probability.
Soft voting can disagree with a label majority when the minority trees give much more confident probabilities.
Split gain
Split gain measures the improvement from replacing a parent leaf with two children, accounting for their fit and the split penalty.
A split gain from a custom implementation must be on XGBoost's own scale before comparison with gamma.
Split threshold
A split threshold is the cutoff in a numeric feature test, separating values at or below the cutoff from values above it.
A split threshold of 12.5 °C sends a 10 °C day left and an 18 °C day right.
Stochastic gradient boosting
Stochastic gradient boosting fits each successive tree on a random fraction of training rows, adding randomness to regularize fitting.
Stochastic gradient boosting with subsample 0.7 uses 70% of training rows in each round.
Sum of squared errors
The sum of squared errors adds squared differences between targets and predictions; regression split comparisons use each child's own mean.
Targets 3 and 7 around leaf mean 5 contribute a sum of squared errors equal to 8.

T

Tabular data
Tabular data arrange records in rows and input variables in columns, often mixing numeric and categorical features.
A table of service requests and device measurements is tabular data suited to forest and boosting baselines.
Target encoding
Target encoding replaces a category with a target-based statistic learned from training records, such as its average target value.
Target encoding of a rare location must not include the training row's own label in that row's value.
Target leakage
Target leakage occurs when an input contains outcome information unavailable at prediction time, creating misleading predictive performance.
A refund date recorded after cancellation creates target leakage in a model predicting future cancellation.
Tree correlation
Tree correlation describes shared variation in tree predictions, which limits how much averaging can reduce an ensemble's variance.
High tree correlation leaves a variance floor even when the forest contains many more trees.
Tree depth
Tree depth is the number of splits on the longest path from the root to a leaf, describing the maximum length of a decision path.
A tree depth of 3 allows up to eight leaves, although some branches may finish earlier.
TreeSHAP
TreeSHAP is an efficient algorithm for calculating SHAP feature contributions for tree models under the chosen explanation assumptions.
TreeSHAP makes individual attributions practical for an ensemble containing hundreds of trees.

V

Validation curve
A validation curve compares training and held-out scores across a model setting, showing where added complexity helps or hurts generalization.
A depth validation curve peaks at depth 5 even though training accuracy keeps rising beyond it.

W

Weak learner
A weak learner is a simple base predictor whose limited individual fit can be improved by combining it with successive learners.
A shallow regression tree acts as a weak learner that supplies one modest correction to a boosted model.
Weighted child impurity
Weighted child impurity is the average child impurity after giving each child a weight equal to its share of the parent's records.
Weighted child impurity gives a 90-record child nine times the influence of a 10-record child.

X

XGBoost
XGBoost is a gradient-boosted-tree library that uses gradients, Hessians, and explicit regularization to build efficient additive models.
XGBoost can fit a binary probability model with validation-based early stopping and missing feature values.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started