AI Wiki中文/EN

Stacking: train a combiner on predictions made without seeing the answers

Stacking 集成

Build exact out-of-fold predictions, solve a two-model mixture and expose the difference between base-model holdout and final evaluation.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Ask each model a question it has not already answered

A one-nearest-neighbor regressor can return every training label exactly when feature values are distinct. That does not tell us how it will predict a new point. If a second model learns which predictors to trust from these memorized answers, it can learn the wrong lesson.

Stacking trains that second model on predictions made while the corresponding records were held out of the base models’ training. The resulting table has one row per training record and one column per base predictor. The original label is the target for the second learning problem. Afterward, the base models are fitted again on all the available training data to answer new queries.

Wolpert’s original account calls these the level 0 and level 1 learning problems. Its multiple-generalizer construction makes the held-out prediction table, then uses base models trained on the full original set for a new question. The framework is broader than a weighted average: a level 1 model may use other features or learn an error correction. Here we study a deliberately small two-predictor weighted combination. Wolpert, author preprint, §I(ii–iv), pp.8–13

Our two predictors are a ridge regression line and one nearest neighbor. They see identical training rows. Their different behavior makes the danger of using in-sample answers easy to inspect, without a large dataset or a model API.

Two learning stages, three different uses of predictions

Partition the n training indices into K nonempty, disjoint folds, with K at least two. Let k(i) identify the fold containing record i, and let A_j denote a complete base learning procedure. Its preprocessing and any internal model selection belong inside that procedure. The out-of-fold (OOF) table is

zij=Aj(D∖Fk(i))(xi),θ^∈arg⁡min⁡θ1n∑i=1nℓ ⁣(yi,gθ(zi1,…,ziM)).z_{ij}=A_j(D\setminus F_{k(i)})(x_i),\qquad \widehat\theta\in\arg\min_\theta\frac1n\sum_{i=1}^n\ell\!\left(y_i,g_\theta(z_{i1},\ldots,z_{iM})\right).

A base model generating row i must exclude the whole assigned fold, including its labels. This restriction does not make the rows of the OOF table independent: their training sets overlap. It also does not hide y_i from the meta-learner. The labels are intentionally used to train that second learner.

Once its parameters are chosen, refit the M base procedures on D and keep the learned meta-model:

f^(x)=gθ^ ⁣(A1(D)(x),…,AM(D)(x)).\widehat f(x)=g_{\widehat\theta}\!\left(A_1(D)(x),\ldots,A_M(D)(x)\right).

The fixed scikit-learn 1.7.2 API makes this distinction explicit: its stored base estimators use the full training set, while the final estimator is trained using cross-validated predictions. It also warns that using already fitted models’ predictions from the same training data can overfit the stack. Our implementation spells out the folds and fits directly; it does not use that library. StackingRegressor: fitting and cv

Solve one small meta-learning problem exactly

Call the ridge and neighbor columns a_i and b_i. Our combination has no extra intercept and uses one constant neighbor weight alpha between zero and one. With d_i=b_i−a_i, its objective and derivative are

J(α)=1n∑i(yi−ai−αdi)2,J′(α)=2n ⁣(α∑idi2−∑idi(yi−ai)).J(\alpha)=\frac1n\sum_i(y_i-a_i-\alpha d_i)^2,\qquad J'(\alpha)=\frac2n\!\left(\alpha\sum_i d_i^2-\sum_i d_i(y_i-a_i)\right).

If at least one d_i is nonzero, the second derivative is positive. The unconstrained optimum is a ratio, and minimizing over the interval clips it to its nearest endpoint when necessary:

α∗=clip⁡[0,1] ⁣(∑idi(yi−ai)∑idi2).\alpha^*=\operatorname{clip}_{[0,1]}\!\left(\frac{\sum_i d_i(y_i-a_i)}{\sum_i d_i^2}\right).

If every d_i is zero, all alpha values fit this meta-training table equally well. The program chooses zero and reports unique=False. The two full-data predictors can still differ at future inputs; the tied training objective does not establish identical future behavior. With a positive denominator, the constrained optimum is unique, including an endpoint solution.

The base ridge line minimizes the sum of squared residuals plus a positive slope penalty lambda; its intercept is unpenalized. Centering uses only the rows passed into that particular base fit:

b^=∑i(xi−xˉ)(yi−yˉ)λ+∑i(xi−xˉ)2,a^=yˉ−b^xˉ,λ>0.\widehat b=\frac{\sum_i(x_i-\bar x)(y_i-\bar y)}{\lambda+\sum_i(x_i-\bar x)^2},\qquad \widehat a=\bar y-\widehat b\bar x,\qquad \lambda>0.

The same numerical penalty is used in every fold and in the final refit. Because this is a summed-loss convention, it does not represent the same penalty relative to a mean loss at different sample sizes. With constant x or a single training row, the positive penalty makes the slope zero. The neighbor model returns the label at the closest training x; ties prefer smaller x, then earlier position in the fitted rows.

Save the folds as well as the fitted model

fit_stack accepts a nonempty sequence of integer or Fraction pairs (x,y), a nonnegative integer fold label for every row and a positive rational ridge penalty. At least two distinct fold labels are required. Repeated feature values are allowed and remain separate records. Booleans, floats, malformed rows and invalid fold labels are rejected.

The function never accepts final evaluation labels. It records each train/held-out index pair and writes held-out predictions back into original row order. The meta-weight is then fitted on that table, and a single final base pair is fitted on all training rows. base_predictions and predict accept empty query lists; mse requires nonempty aligned vectors. Internal base fitting expects validated rows, and prediction expects an unmodified fitted model.

from fractions import Fraction as F


def values(seq):
    if type(seq) not in (list, tuple):
        raise ValueError('expected list or tuple')
    if any(type(x) is not int and not isinstance(x, F) for x in seq):
        raise ValueError('use integers or Fraction')
    return tuple(F(x) for x in seq)


def table(rows):
    if type(rows) not in (list, tuple):
        raise ValueError('expected rows')
    data = tuple(values(row) for row in rows)
    if not data or any(len(row) != 2 for row in data):
        raise ValueError('nonempty two-column table required')
    return data


def fit_bases(data, penalty):
    # Internal: validated, nonempty training rows and positive penalty.
    n = len(data)
    mx = sum(x for x, y in data) / n
    my = sum(y for x, y in data) / n
    slope = sum((x-mx)*(y-my) for x, y in data) / (
        penalty + sum((x-mx)**2 for x, y in data))
    return {'intercept': my-slope*mx, 'slope': slope, 'rows': data}


def base_predictions(model, xs):
    result = []
    for q in values(xs):
        nearest = min(enumerate(model['rows']),
                      key=lambda item: (abs(item[1][0]-q), item[1][0], item[0]))[1][1]
        result.append((model['intercept']+model['slope']*q, nearest))
    return tuple(result)


def meta_weight(pairs, targets):
    pairs = table(pairs); targets = values(targets)
    if len(pairs) != len(targets):
        raise ValueError('matching predictions and targets required')
    delta = tuple(b-a for a, b in pairs)
    denominator = sum(d*d for d in delta)
    numerator = sum(d*(y-a) for (a, b), d, y in zip(pairs, delta, targets))
    alpha = min(F(1), max(F(0), numerator/denominator)) if denominator else F(0)
    return {'alpha': alpha, 'unique': bool(denominator)}


def fit_stack(rows, folds, penalty=F(1)):
    data = table(rows); penalty = values((penalty,))[0]
    if penalty <= 0:
        raise ValueError('positive ridge penalty required')
    if type(folds) not in (list, tuple) or len(folds) != len(data):
        raise ValueError('one fold label per row required')
    if any(type(f) is not int or f < 0 for f in folds) or len(set(folds)) < 2:
        raise ValueError('at least two nonnegative integer fold labels required')
    oof = [None]*len(data); splits = []
    for fold in sorted(set(folds)):
        train = tuple(i for i, f in enumerate(folds) if f != fold)
        valid = tuple(i for i, f in enumerate(folds) if f == fold)
        base = fit_bases(tuple(data[i] for i in train), penalty)
        for i, pair in zip(valid, base_predictions(base, tuple(data[i][0] for i in valid))):
            oof[i] = pair
        splits.append((train, valid))
    meta = meta_weight(tuple(oof), tuple(y for x, y in data))
    return {'bases': fit_bases(data, penalty), 'alpha': meta['alpha'],
            'unique': meta['unique'], 'oof': tuple(oof), 'splits': tuple(splits)}


def predict(model, xs):
    alpha = model['alpha']
    return tuple((1-alpha)*a+alpha*b for a, b in base_predictions(model['bases'], xs))


def mse(predictions, targets):
    p, y = values(predictions), values(targets)
    if not p or len(p) != len(y):
        raise ValueError('nonempty matching predictions and targets required')
    return sum((a-b)**2 for a, b in zip(p, y))/len(p)


if __name__ == '__main__':
    rows = tuple((x, 2*x+1) for x in range(6))
    folds = tuple(x % 3 for x in range(6))
    model = fit_stack(rows, folds)
    targets = tuple(y for x, y in rows)
    in_sample = base_predictions(model['bases'], tuple(x for x, y in rows))
    naive = meta_weight(in_sample, targets)
    test_x, test_y = (6, 7), (13, 15)
    print('folds:', model['splits'])
    print('OOF pairs:', tuple(tuple(str(v) for v in pair) for pair in model['oof']))
    print('OOF / in-sample alpha:', model['alpha'], naive['alpha'])
    print('OOF training MSE:', mse(tuple((1-model['alpha'])*a+model['alpha']*b for a,b in model['oof']), targets))
    print('new predictions:', tuple(str(v) for v in predict(model, test_x)))
    leaky = dict(model, alpha=naive['alpha'])
    print('new MSE / leaky MSE:', mse(predict(model, test_x), test_y), mse(predict(leaky, test_x), test_y))

Actual output:

folds: (((1, 2, 4, 5), (0, 3)), ((0, 2, 3, 5), (1, 4)), ((0, 1, 3, 4), (2, 5)))
OOF pairs: (('17/11', '3'), ('45/14', '1'), ('5', '3'), ('7', '5'), ('123/14', '7'), ('115/11', '9'))
OOF / in-sample alpha: 0 1
OOF training MSE: 2715/23716
new predictions: ('467/37', '537/37')
new MSE / leaky MSE: 260/1369 10

The data follow the simple line y=2x+1 at x=0 through 5. Fold membership is (0,1,2,0,1,2). For example, predicting the held-out row at x=0 uses rows 1,2,4,5. The ridge prediction is 17/11, while its nearest training neighbor gives 3. It cannot look up the held-out label 1.

The OOF optimization chooses neighbor weight zero. In contrast, a meta-fit on the final base models’ in-sample predictions chooses weight one: the nearest neighbor reproduces all six training labels, while the penalized line does not. The last two evaluation inputs, 6 and 7, are used only after fitting. On them, the proper stack has MSE 260/1369, while the in-sample choice has MSE 10.

These two explicitly constructed queries illustrate a failure mechanism; they are not an estimate of typical population performance. The stack selects just the ridge endpoint in this example, so it does not beat that ridge model. A separate executed example with training labels (0,1,1,4,3,3) and the same features/folds has alpha=15151/105395, an interior combination. Stacking can select an endpoint or a mixture.

The printed OOF training MSE, 2715/23716, is used to fit alpha. It is therefore training performance for the meta-model, even though the base predictions were held out. To evaluate the entire stack, use untouched test records or an outer validation loop that rebuilds both stages inside each outer training split.

For K folds and n records, the direct program takes O(Kn+n²) rational arithmetic/comparison operations: ridge fitting is linear per fold, but nearest-neighbor queries scan their fold’s training rows. Saved split indices use O(Kn) slots; the OOF table and final base models use O(n). Predicting m new inputs costs O(1+mn) operations and O(1+m) extra slots, apart from the stored model. These counts assume expected constant-time set operations, and exclude rational bit lengths. The nearest-neighbor step uses a direct scan.

Holding out one layer does not hold out the whole workflow

Preprocessing can leak. A scaler, imputer, target encoder or feature selector fitted before the folds can carry held-out information into a base model. Treat the entire base pipeline as the object to refit. The means used by our ridge fits are computed inside each call, not once over the original table.

The split must match the question. If several rows come from one subject or source, assign that unit consistently to a fold. If prediction must use only the past, ordinary complementary folds can expose future records. This program implements disjoint complementary folds; it is not a time-series splitting engine. The example’s numerical x values are features, not timestamps.

Refitting changes the base models. The meta-model learned from smaller-fold fits but receives full-data fits at deployment. Their predictions can differ in scale, bias and variability. More folds may reduce this training-size difference while increasing cost; they do not prove that the resulting stack improves. Similar base models can also yield nearly identical OOF columns and unstable unconstrained weights. Our interval constraint limits the mixture but does not guarantee useful predictors.

Selecting the stack is another learning problem. Trying many base sets, fold rules or meta-models and reporting the smallest score from the same data can be optimistic. Fixed averaging has no learned weights; selecting one base learner is a different restricted choice; hold-out blending can learn a combination on a separate subset without making K complementary fits. None of these names by itself establishes how final performance was measured. Wolpert, §I(iv); fixed API, cv and prefit

Identify which learner has seen the answer

  1. In the main example, can the model producing the OOF row for x=0 use the label at x=3? Can the meta-learner use the label at x=0?

Answer: The base fit excludes indices 0 and 3 because both belong to fold zero. It cannot use either label. The meta-learner deliberately uses all original targets, including y at x=0, to learn alpha. Its fitted-table score is not an untouched test score.

  1. Let the two prediction columns be (0,2) and (2,0), with targets (1,1). What is the optimal mixture? What if the two columns are identical?

Answer: The difference vector is (2,−2), giving numerator 4 and denominator 8, so alpha=1/2 and both fitted predictions equal one. If the columns are identical, the denominator is zero: every alpha fits equally, and this implementation chooses zero with unique=False.

  1. Why not keep the fold-specific models for new inputs and average their predictions while silently retaining the same meta-model?

Answer: That defines a different deployment construction from the full-data refit specified here. It may be useful, but it changes the inputs received by the meta-model and must be described and evaluated as such. A held-out training table alone does not show that the two constructions are equivalent.

  1. A base model achieves zero in-sample error. Is giving it all the mixture weight justified? Which number in the example demonstrates the problem?

Answer: No. A nearest neighbor can memorize distinct training rows. The in-sample meta-fit chooses alpha=1, yet its MSE on the two new queries is 10. The OOF choice has alpha=0 and MSE 260/1369. This counterexample defeats the inference from training fit; it does not prove that OOF stacking always wins.

A prediction can become a new feature

The lasting idea in Wolpert’s framework is to make model behavior part of a second learning problem. Its multiple-model construction gives a concrete separation between the data used to fit a base predictor and the records it predicts for the next layer. The original framework also includes one-model correction and extra inputs at the higher level. Our constrained two-column regression covers only one small case.

The widely cited journal article appeared in Neural Networks 5(2), pp.241–259, in 1992. The linked 57-page author preprint carries report identifier LA-UR-90-3460 and different pagination; the report identifier is not used to invent a specific publication day. Author preprint; fixed official reference list

A useful next investigation is to compare the same base pair under fixed averaging, OOF weight fitting and an outer evaluation of the whole procedure. Save every split, keep the candidate search budget fixed and examine errors as well as the selected weights. For classification, distinguish hard labels, raw decision scores and probabilities as meta-features. For richer combinations, ask what regularization and sample size support the added flexibility before treating another layer as an improvement.

Make a prediction, then check

The base predictions are out of fold, but alpha was fitted on their targets. Is the resulting fitted-table MSE an untouched test score?

Choose one answer

Learning objectives

  • Build base-model held-out predictions while preserving each row’s training exclusion.
  • Derive and compute the exact constrained mixture of two prediction columns.
  • Separate meta-model training scores, full-data refits and outer evaluation of the complete workflow.

Prerequisites & connections

Explore related knowledge →

References

  1. Stacked Generalization — author preprint LA-UR-90-3460
    David H. Wolpert
  2. scikit-learn 1.7 — StackingRegressor
    scikit-learn developers

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.

  • Six tests pass. Independent uncentered two-by-two normal equations and sorted distance records verify 52 OOF pairs and 30 full-fit query pairs over 10 fits. Exact quadratic finite differences verify constrained stationarity and curvature for 12 meta problems; eleven candidate weights per problem also satisfy the objective comparison.
  • Perturbing each held-out fold’s labels leaves all predictions for that fold unchanged while changing the full-data fits. Checked split exclusion/coverage, original row alignment, input preservation, duplicate features, deterministic neighbor ties, singleton base fits, empty queries and invalid tail values.
  • The main example yields OOF/in-sample neighbor weights 0/1, fitted-meta MSE 2715/23716, new-query predictions 467/37 and 537/37 and MSE 260/1369 versus 10. A second dataset yields interior weight 15151/105395. These are constructed finite examples; no population or universal superiority claim.
  • Complete bilingual articles share five displays, six stable anchors, four answered exercises, the full Python program and six stdout lines. Strict MDX/KaTeX/actual React HTML passes with the shared fatal diagnostic guard. Uses fixed Humanizer editorial guidance; source-access details stay in metadata. Review remains written pending another agent’s check.
  • 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.

Source locations checked:

  • Stacked Generalization — author preprint LA-UR-90-3460 · Root downloaded the original PDF with TLS verification from the non-www mirror hostname (126810 bytes,57 pages; SHA 1c1205975743765207ef8b0099226b41310e6469688c489689682bb14cfd2b84). pypdf text actually read: title/report identifier p.1, abstract/noiseless framing pp.2–3; §I(ii–iv) pp.8–13 defines partition sets, level0/1, held-out guesses, full-set refitting and averaging/selection cases. The manuscript uses leave-one-out for its detailed examples; our K-fold extension is separately explained and supported by fixed API. No complete57-page reading or figure inspection. The www hostname had a certificate mismatch; it was not bypassed, and the non-www hostname succeeded. No precise report publication date inferred.
  • scikit-learn 1.7 — StackingRegressor · Actually read fixed /1.7/ page displaying1.7.2, lines623–666: full-X estimators versus cross_val_predict final estimator, cv options/prefit and risk when training data reused, cv is for prediction rather than evaluation; lines673–674 passthrough and721–722 journal citation1992/5.2/241–259. Also inspected matching guide §1.11.6, but no second source card is counted for it. Its informal best-base performance claim is not adopted as a guarantee. No sklearn code run.
  • Stacked Generalization — author preprint LA-UR-90-3460 · Actually read the provided local source-wolpert.txt, extracted from the 57-page author manuscript whose PDF SHA independently matches 1c1205975743765207ef8b0099226b41310e6469688c489689682bb14cfd2b84. Read page 1 title/report identifier, pages 2–3 abstract and noiseless framing, pages 8–13 partition sets, level 0/1 tables, held-out guesses, full-set refits and averaging/selection cases. The author narrows later examples to leave-one-out; the article’s K-fold procedure is supported separately by the API. Text review only, not visual verification or all-page reading.
  • scikit-learn 1.7 — StackingRegressor · Actually opened the exact /1.7/ StackingRegressor URL, rendered 1.7.2. Read lines 623–626 full-data base fits and cross-validated final inputs, 644–674 cv/prefit risk, prediction versus evaluation and passthrough, and 719–722 journal bibliography. No sklearn execution; custom implementation scope is accurate.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.