Gradient boosting: fit a correction, then fit the next one
梯度提升
Connect functional gradients to residual fitting, prove the squared-loss step, and select a fitted prefix with a separate validation curve.
gradient-boostingLearn the correction that the current model still needs
Suppose a regression dataset contains (0, 0), (1, 1), (2, 3) and (3, 4). Predicting the mean, two, is a reasonable constant starting point. Its errors have a pattern: the predictions are too high on the left and too low on the right. A small tree can describe that correction.
Fit a stump to the residuals −2, −1, +1 and +2. It splits at 1.5 and predicts corrections −1.5 on the left and +1.5 on the right. Adding half of this correction changes the predictions to 1.25, 1.25, 2.75 and 2.75. The next tree fits the new residuals. It does not fit the original targets again, and it does not replace the existing model.
Gradient boosting generalizes this idea by asking for a direction that decreases a chosen loss. Ordinary residuals give that direction for squared error. Other losses produce different training targets, often called pseudo-residuals. The fitted model is an initial function plus successive corrections. Familiarity with gradient descent, decision trees and empirical risk helps connect the pieces.
The gradient is with respect to the prediction
For n training records and a pointwise loss ell, the empirical objective is
The constant initializer depends on the loss. For half squared error, it is the target mean. For absolute error, any appropriate sample median minimizes the constant objective. Neither is a universal initializer for every loss.
At a differentiable loss, compute the negative derivative with respect to the current prediction, fit a regressor to those values, and add a scaled correction:
The derivative is not taken with respect to an input feature or a tree threshold. It describes desired changes in the predictions at the training points. Under the empirical inner product, which averages products over those points, the gradient of the average loss has these pointwise derivatives. With the unscaled Euclidean inner product on the prediction vector, the gradient instead has an additional factor 1/n. The update convention must be consistent with that choice of scale.
The argmin expression is an ideal fitting target; a practical tree builder may only approximate it. A learner constrained to a family H cannot necessarily reproduce every desired change. Least-squares fitting projects the derivative targets toward functions the learner can express; the fitted function also supplies predictions away from the training points. A one-dimensional search can choose rho using the original loss, when a suitable minimizer exists. The learning rate eta then scales the step. With a general loss, both the step search and its existence need attention. Directly minimizing an unconstrained linear Taylor approximation is not a complete algorithm: without a step or norm constraint it may be unbounded. Friedman’s formulation separates derivative fitting from the step search. Greedy Function Approximation: A Gradient Boosting Machine, Algorithm 1
Why squared error is especially simple
For ell(y,z)=(y−z)²/2, the pseudo-residual is exactly y−z. In each leaf of a fitted regression tree, the least-squares prediction is the mean residual of the records in that leaf. Calling the fitted training-point corrections h_i gives
Here A denotes the leaf containing i. Within each leaf, its mean times the sum of its residuals equals the leaf size times the squared mean. Summing across leaves proves the middle identity. Expanding the squared loss along a fixed correction then gives rho=1. This holds for these least-squares leaf values without an added leaf penalty; it should not be carried over unchanged to another loss or a regularized leaf fit.
With that unit line-search coefficient, the exact change in half mean squared loss is
For a nonzero fitted correction, any eta strictly between zero and two reduces this training objective. Eta equal to two leaves it unchanged; a larger eta increases it. Our program deliberately accepts only the usual shrinkage range 0 < eta ≤ 1. A zero fitted correction offers no decrease. This proof is about a full-data squared-loss step, not a claim that every gradient-boosting variant decreases every loss for any positive learning rate.
Smaller eta also changes future residuals. Training with a smaller learning rate is therefore generally different from fitting once with eta=1 and multiplying the completed ensemble by eta. The thresholds selected later can change. The round count and learning rate should be considered together. Friedman, §5, official gradient-boosting guide
Fit the training path, then compare its prefixes
The example is a one-feature squared-loss regressor using exact integers and Fraction values. Every stump tests the constant residual mean and all midpoints between consecutive distinct training feature values. The left leaf includes the threshold. A constant wins a tie with a split; otherwise the smaller threshold wins.
For a proposed split, let S_L and S_R be the residual sums in its two nonempty leaves, with counts n_L and n_R. The minimized residual sum of squares is
The first term is the same for every split, so the code maximizes the two explained-sum terms. It sorts record indices once and scans residual prefix sums at each round. Equal feature values cannot be split apart; repeated records still contribute separately to sums and counts.
fit_gradient_boosting accepts training data only. Its MSE curve includes the initial constant at stage zero. A zero-update status means the best searched stump predicts zero correction at every training point; the zero tree is not added. That can occur despite nonzero residuals, as the conflicting-response example shows. round-limit means the requested number of attempts was used without that stop. It makes no claim of convergence. A zero limit still produces the mean model, with no stump attempts.
validation_curve receives the already fitted model and separate labeled records. It evaluates stages zero through the last accepted stump and selects the earliest stage with the lowest validation MSE:
Here v is the nonzero validation-set size and R the number of accepted trees. This is selection among fitted prefixes after training; it does not stop the training loop as soon as validation worsens. It also does not mutate or truncate the model. Pass best_stage to predict explicitly to use the chosen prefix. Omitting the stage predicts with all fitted trees.
from fractions import Fraction as F
def exact(value):
if isinstance(value, bool) or not isinstance(value, (int, F)):
raise ValueError('values must be integers or Fractions')
return F(value)
def read_data(rows):
if not isinstance(rows, (list, tuple)) or not rows:
raise ValueError('data must be a nonempty list or tuple')
result = []
for row in rows:
if not isinstance(row, (list, tuple)) or len(row) != 2:
raise ValueError('each row must contain one feature and a target')
result.append(tuple(exact(v) for v in row))
return tuple(result)
def tree_value(tree, x):
threshold, left, right = tree
return left if threshold is None or x <= threshold else right
def residual_stump(data, residuals, order):
n = len(data)
total = sum(residuals, F(0))
# Minimizing residual SSE is equivalent to maximizing this explained sum.
best_gain = total * total / n
best = (None, total/n, total/n)
prefix = F(0)
for k in range(1, n):
prefix += residuals[order[k-1]]
lo, hi = data[order[k-1]][0], data[order[k]][0]
if lo == hi:
continue
right = total-prefix
gain = prefix*prefix/k + right*right/(n-k)
if gain > best_gain:
best_gain = gain
best = ((lo+hi)/2, prefix/k, right/(n-k))
return best
def mse(data, values):
return sum(((y-f)**2 for (x,y),f in zip(data, values)), F(0))/len(data)
def fit_gradient_boosting(rows, max_rounds, learning_rate=F(1,2)):
data = read_data(rows)
if type(max_rounds) is not int or max_rounds < 0:
raise ValueError('max_rounds must be a nonnegative integer')
rate = exact(learning_rate)
if not 0 < rate <= 1:
raise ValueError('learning_rate must be in (0, 1]')
n = len(data)
initial = sum((y for x,y in data), F(0))/n
values = (initial,)*n
order = sorted(range(n), key=lambda i:data[i][0])
trees, curve = [], [mse(data, values)]
attempts, status = 0, 'round-limit'
for _ in range(max_rounds):
residuals = tuple(y-f for (x,y),f in zip(data, values))
tree = residual_stump(data, residuals, order)
update = tuple(tree_value(tree, x) for x,y in data)
attempts += 1
if all(v == 0 for v in update):
status = 'zero-update'
break
trees.append(tree)
values = tuple(f+rate*h for f,h in zip(values, update))
curve.append(mse(data, values))
return {'initial': initial, 'learning_rate': rate, 'trees': tuple(trees),
'train_mse': tuple(curve), 'train_predictions': values,
'attempts': attempts, 'status': status}
def predict(model, xs, stage=None):
# model is an unmodified fit_gradient_boosting result.
if not isinstance(xs, (list, tuple)):
raise ValueError('queries must be a list or tuple')
queries = tuple(exact(x) for x in xs)
count = len(model['trees']) if stage is None else stage
if type(count) is not int or not 0 <= count <= len(model['trees']):
raise ValueError('stage must be an available nonnegative integer')
if not queries:
return ()
values = [model['initial']]*len(queries)
for k in range(count):
tree = model['trees'][k]
for i,x in enumerate(queries):
values[i] += model['learning_rate']*tree_value(tree,x)
return tuple(values)
def validation_curve(model, rows):
data = read_data(rows)
values = [model['initial']]*len(data)
curve = [mse(data, values)]
for tree in model['trees']:
values = [f+model['learning_rate']*tree_value(tree,x)
for (x,y),f in zip(data, values)]
curve.append(mse(data, values))
best = min(range(len(curve)), key=lambda k:(curve[k],k))
return {'mse':tuple(curve), 'best_stage':best}
if __name__ == '__main__':
training = ((0,0),(1,1),(2,3),(3,4))
validation = ((F(1,4),1),(F(11,4),3))
model = fit_gradient_boosting(training,4,F(1,2))
report = validation_curve(model,validation)
print('initial:',model['initial'],'status:',model['status'])
print('training MSE:',', '.join(map(str,model['train_mse'])))
print('validation MSE:',', '.join(map(str,report['mse'])))
print('selected stage:',report['best_stage'])
print('selected predictions:',', '.join(map(str,predict(model,(F(1,4),F(11,4)),report['best_stage']))))
print('all-stage predictions:',', '.join(map(str,predict(model,(F(1,4),F(11,4))))))
stalled = fit_gradient_boosting(((0,0),(0,2)),4)
print('same feature:',stalled['status'],'MSE:',stalled['train_mse'][-1])
The complete program prints:
initial: 2 status: round-limit
training MSE: 5/2, 13/16, 25/64, 51/256, 611/9216
validation MSE: 1, 1/16, 1/64, 449/2304, 36149/82944
selected stage: 2
selected predictions: 7/8, 25/8
all-stage predictions: 91/288, 349/96
same feature: zero-update MSE: 1
Training MSE decreases at every accepted stage, from 5/2 to 611/9216. The two constructed validation records favor stage two, whose predictions are 7/8 and 25/8. Later corrections continue to improve training fit but increase validation error. This is a small arithmetic demonstration, not a performance estimate for a deployed system.
For n training records and A stump attempts, sorting takes O(n log(n+1)) comparisons and fitting takes O(An) arithmetic/comparison operations. Temporary training storage and the retained model use O(n+R) entries for R accepted trees; the MSE history stores one scalar per stage, not every residual vector. Predicting m queries through k stages costs O(1+m(k+1)) operations and O(1+m) additional entries. The validation curve costs O(v(R+1)) operations and O(v+R) entries. Exact rational bit lengths are excluded from these bounds and can grow with the number of rounds. Raw training data, validation data, rates, limits and queries are validated; prediction and validation expect an unmodified fitted model.
Residual fitting is a special case, and validation is a choice
For binary log loss with labels zero and one and raw score z, the modeled probability is sigmoid(z). The negative derivative is y−sigmoid(z), not y−z. A regression tree can fit these real-valued derivative targets even though the final task is classification. The mapping from an additive score to a probability or class depends on the loss. For absolute error, a subgradient away from zero depends on the sign of the residual, while a suitable leaf update uses a median. Fitting the original numeric residual with a mean leaf would not implement that loss. scikit-learn: mathematical formulation and loss functions
Even for squared error, the proof needs the stated leaf fit and step. Subsampling records, penalizing leaf values or approximating the fit changes the argument. These may be useful modifications, but their behavior needs its own analysis. The program handles one numeric feature, no missing values, no sample weights and no random sampling. A sum of its stumps is a step function, with constant predictions beyond the extreme split thresholds; no straight-line extrapolation is learned.
Two records with the same input and different responses cannot both be fitted exactly by a deterministic function of that input. For (0,0) and (0,2), the initial prediction is one, the residuals cancel in the only available leaf, and the program stops with MSE one. Adding rounds cannot introduce a missing explanatory variable. More generally, a zero-update result concerns the available correction family on the observed data, not the usefulness of every possible model or feature.
The minimum validation error is a score used to choose a model, so it should not be reported as an untouched final test result. Repeatedly comparing learning rates, depths and round counts uses more information from validation. A later assessment must be protected from those choices, with group or temporal separation when the sampling structure requires it. If the selected model is refitted on more data, its residual path may change; preserving a stage number does not preserve the original predictions. See training, validation and test splits and generalization.
Track the correction and the model choice
- For the four training records, compute the initial model, first residuals and first update with eta=1/2.
Answer: The initial mean is two. Residuals are −2, −1, +1 and +2. The best split is at 1.5, with leaf means −3/2 and +3/2. Adding half of those corrections gives predictions 5/4, 5/4, 11/4 and 11/4. Their MSE is 13/16; the half-squared objective used in the derivation is 13/32.
- A least-squares leaf correction is nonzero. Does an arbitrarily large positive learning rate preserve the descent proof?
Answer: No. The change is negative for 0 < eta < 2, zero for eta=2 and positive for eta>2. Our code accepts only 0 < eta ≤ 1. These conclusions use the projection identity for the specified full-data leaf means; another loss or altered leaf optimization needs a separate argument.
- The validation routine selects stage two. Does calling
predict(model, xs)automatically use it, and is the selected validation MSE a final test estimate?
Answer: No on both counts. Pass stage=2, or the returned best_stage, to use the selected prefix. The default uses every accepted tree. The validation score has participated in selection and must be distinguished from a final assessment protected from that choice. The original model remains intact.
- What happens on training records
(0,0)and(0,2)? Would squared-loss residuals also be correct derivative targets for binary log loss?
Answer: The mean is one, residuals are −1 and +1, and no split can separate equal inputs. The best fitted correction is zero, so training stops with MSE one. For binary log loss, the derivative target is y−sigmoid(F), rather than y−F. Changing the loss requires changing the derivative, initialization and appropriate step or leaf update.
Function-space optimization and tree-based corrections
Friedman’s formulation connects greedy additive modeling with steepest descent in the space of predictions. Its generic algorithm separates the loss derivative, a least-squares approximation to that direction and a search for the step size. The squared-loss case reduces to repeated residual fitting; the same framework also motivates different procedures for absolute, Huber and logistic losses. This distinction explains why “keep fitting the residuals” is a useful introduction but an incomplete definition of gradient boosting. Friedman, Algorithms 1–2 and §4
The shrinkage discussion adds a second question: how far should each correction move the model before the next one is fitted? It links step size with the number of stages and model selection. Neither the next tree nor the eventual optimum of a validation curve is fixed independently of that choice. The 1999 manuscript develops these ideas; the later journal article appeared in The Annals of Statistics in October 2001. Friedman, §5, journal publication record
Continue with AdaBoost to compare exponential-loss reweighting, and XGBoost to study a particular boosted-tree system beyond this basic construction. The common additive structure does not make their objectives, tree builders, score scales or stopping rules identical. When comparing implementations, specify the loss, initializer, leaf fit, learning rate and evaluation protocol before comparing results.
Make a prediction, then check
Why is training with a smaller learning rate generally different from scaling an already fitted ensemble?
Learning objectives
- Distinguish prediction-space derivatives from feature derivatives and explain when pseudo-residuals equal ordinary residuals.
- Derive the projection identity and learning-rate descent range for unpenalized squared-loss leaf means.
- Train a reproducible correction path and select an explicit prefix using separate validation records.
Prerequisites & connections
Explore related knowledge →References
- Greedy Function Approximation: A Gradient Boosting Machine — February 24, 1999 manuscript
Jerome H. Friedman · 1999 - Gradient boosting — scikit-learn 1.7.2 mathematical formulation and shrinkage
scikit-learn contributors - Greedy function approximation: A gradient boosting machine — journal publication record
Jerome H. Friedman · 2001
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- Nine tests pass. An independent leaf-projection-matrix and affine-recurrence reference verifies 174 complete fits over 29 datasets, two rates and three limits. Six additional paths verify the projection identity and exact loss decrease; direct boundary calculations cover rates two and three outside the accepted API range.
- Main validation curve selects stage 2 with MSE 1/64 while training MSE continues down to 611/9216. Verified every validation prefix by a step-function sum, earliest ties including stage zero, explicit selected-prefix prediction, model immutability, rate-versus-posthoc-scaling difference, conflicting identical inputs, constant and singleton data, empty queries, stage validation, permutation/duplication/translation, invalid inputs and 90-digit exact features/targets.
- Complete original bilingual prose, identical Python and seven output lines, six matching display formulas, six anchors and four answered exercises. Strict MDX/KaTeX/React HTML and MathML checks pass. Fixed author-detected raw less-than markup in prose and returned empty predictions after stage validation to match the stated empty-query cost. Only article_text controls article paths. Humanizer rereading completed; written records AI author checks, not human review, external benchmarking, full-site build or browser acceptance.
- All nine author tests passed. An additional reference reconstructs each candidate loss quadratic from values at -1,0,+1 and minimizes it, rather than using residual-prefix sums or author projection matrices. Twelve complete fits, 212 candidate leaf quadratics and 32 accepted steps match; independently interpolated step-loss polynomials verify the descent coefficient.
- An aggregated boundary-jump representation verifies 44 validation prefixes and explicit staged predictions. During validation, both fitting entry points were replaced with failure stubs; no refitting occurs. Reviewed earliest ties, stage-zero eligibility, nonmutating selection, default full-stage predictions, zero-update versus round-limit and conflicting identical inputs.
- Read the full bilingual theory and code: empirical-inner-product scaling, prediction rather than input derivatives, unpenalized leaf projection identity, eta in (0,2) descent versus the API’s (0,1] range, loss-dependent targets and shrinkage-versus-posthoc scaling are consistent. Complexity includes initialization, stored curves and the empty-query return. Historical manuscript/publication dates and source scope are distinguished.
- Strict MDX/KaTeX and actual React HTML pass: each language has six displays, six stable anchors and four answers; all six mathematical annotations match. Full bilingual prose, exercises and metadata are consistent. All five SHA values match the frozen manifest; source IDs and URLs below are exact metadata identities.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Greedy Function Approximation: A Gradient Boosting Machine — February 24, 1999 manuscript · Actually opened and read the 34-page IIT Bombay-hosted original PDF. First page identifies author and February 24, 1999 date. Algorithm 1 on printed page 4 separates derivative targets, least-squares fitting and line search; §4.1 and Algorithm 2 on page 5 reduce half squared loss to residual fitting; §4.2 pages 5–6 treats absolute loss and median leaf updates; §5 pages 11–13 and equation 33 describe per-stage shrinkage and joint selection of learning rate and stage count. Author Stanford URL timed out, journal PDF returned no readable paper, and CUHK mirror failed; these are not claimed as full-text reads.
- Gradient boosting — scikit-learn 1.7.2 mathematical formulation and shrinkage · Actually read official §1.11.1.2.3–1.11.1.2.5, extracted lines 379–449: loss-dependent constant initialization, first-order derivative target, classification score mapping, squared/absolute/Huber/log losses, and per-stage learning rate. The text explicitly constrains/project-fits the derivative rather than treating an unbounded linearized argmin as a complete solver; it does not repeat the guide’s overstrong statement that a tree fitted to ±1 targets can output only integers.
- Greedy function approximation: A gradient boosting machine — journal publication record · Publisher DOI/Project Euclid search result returned complete publication metadata: October 2001, Ann. Statist. 29(5):1189–1232, DOI 10.1214/aos/1013203451; also distinguishes first availability on the platform as February 8, 2002. Direct DOI opening returned an iframe shell and the journal PDF endpoint did not expose the paper. Used only for the publication sentence; no journal-page reading asserted.
- Greedy Function Approximation: A Gradient Boosting Machine — February 24, 1999 manuscript · Independently opened the 34-page IIT Bombay-hosted PDF. First page identifies Jerome H. Friedman and February 24, 1999. Read Algorithm 1 on PDF page 4 for negative derivative fitting and line search; section 4.1/Algorithm 2 on page 5 for least-squares residuals; section 4.2 on pages 5–6 for sign targets and median leaf updates; section 5 on pages 11–12, including equation 33 and learning-rate/stage-count interaction. Text extraction; no manuscript dataset, figure or benchmark reproduced.
- Gradient boosting — scikit-learn 1.7.2 mathematical formulation and shrinkage · Independently read fixed 1.7 documentation rendered 1.7.2, sections 1.11.1.2.3–1.11.1.2.5, lines 379–449. Checked loss-dependent initializers, prediction derivatives, classification links, absolute-error median updates and shrinkage. The chapter correctly qualifies the unconstrained linear approximation and does not adopt the documentation’s integer-only claim for trees fitted to sign targets. No library execution.
- Greedy function approximation: A gradient boosting machine — journal publication record · Independently retrieved the DOI/Project Euclid publisher search result: October 2001, Annals of Statistics 29(5), 1189–1232, DOI 10.1214/aos/1013203451. It separately states first platform availability February 8, 2002. Used only to verify publication metadata, not as a full journal-PDF read.
Related topics