CatBoost: decide which answers each row may see
CatBoost
Trace ordered target statistics and prefix residuals with exact small examples, and distinguish them from ordinary cross-fitted encoding.
catboostA feature that has already seen the answer
A quality inspector records a batch label such as red or blue and whether an item failed inspection. Replacing each batch label with its historical failure rate sounds reasonable. But if an item’s own inspection result contributes to its training feature, changing the answer changes the question shown to the model.
CatBoost is a gradient-boosted tree system whose ordering principle addresses two related dependencies: how categorical target statistics are constructed, and which fitted predictions are used to calculate the next round’s residuals. Its 2018 paper develops both; neither name means that every fitted prediction is an unbiased estimate of the real response. Original paper
Our six inspection records are red, blue, red, green, blue, red, with labels 1, 0, 0, 1, 1, 1. Give each new category a fixed prior of one half with strength one. Before the third record is processed, red has one previous failure, so that record’s feature is three quarters. Only after recording this feature may its zero label enter the red summary. This is a question about information flow, not about sorting categories into a meaningful numerical order.
The executable example contains a prefix encoder and a separate constant-model residual experiment. Read decision trees first; gradient boosting explains the broader additive-model framework.
What each row is allowed to know
Let the supplied permutation list be π, with π(t) denoting the original row at position t. For row i, let Hᵢ contain only earlier rows of the same category; mᵢ is its size. Binary targets, a fixed prior p in [0,1] and strength a greater than zero give
The prior is the result when history is empty. With a nonempty history, this is a weighted average of p and the observed category mean. Larger a keeps sparse estimates closer to p. It is also the unique minimizer of a(z−p)² plus the sum of (z−yⱼ)² over that history: the quadratic coefficient a+mᵢ is positive.
The crucial implementation order is read, emit, update. At every step the dictionary contains exactly the already visited rows, an invariant established by induction. After all rows, that same dictionary is suitable for encoding new records without their labels. The fixed version of the CatBoost categorical guide describes prior-smoothed statistics from previous records; our strength parameter makes this small binary case explicit.
Compare using the full training-category mean as a feature for a training row. If that category contains N_c records and its label changes by Δ, with categories, prior, strength and ordering held fixed,
This zero sensitivity is an exact dependency statement. It does not prove identical train/test feature distributions, low estimation variance or good predictions. Earlier positions have shorter histories. If p is instead calculated as the mean of all n labels, an excluded current label still contributes through the prior:
The program therefore takes p as an externally fixed input. Label-dependent ordering also breaks the exclusion argument. For IID statistical reasoning, choose permutations independently of labels; for time-dependent records, respect the actual information available at prediction time.
Ordered encoding and ordered boosting are separate operations. For squared loss, ordinary boosting computes a residual from a model that may already have fitted that record. The paper calls the resulting training-versus-new-record conditional prediction discrepancy prediction shift. Its conceptual ordered procedure maintains one model per prefix and obtains a row’s residual from the previous prefix. A practical tree implementation shares structures and manages multiple permutations; it is more than precomputing one encoded column. Paper, §§4–5
To make those dependencies inspectable, restrict each model to a single constant. Number rows by permutation position, start every constant at zero, freeze the previous round, and update
Here i and j start at one, and η is in (0,1]. The mean residual is the least-squares constant fit on that prefix. By induction, Mᵢ depends only on the first i targets; the prediction used in rⱼ excludes y at position j. The residual itself must include that target. A single round’s updates use the same frozen family, so this is not an in-place sweep in which early updates affect later residuals.
Two small experiments with visible dependencies
This complete Python 3.10+ program uses exact rational arithmetic. Categories are nonempty strings, labels are integer zero or one, and the order is a complete permutation of zero-based row indices. Booleans, floats, missing categories, empty training data and invalid permutations are rejected. An empty prediction query is allowed. encode expects its own returned model and never updates it.
ordered_constants has no categorical feature, tree search or classifier threshold: it isolates the prefix-residual recurrence. Its constants can leave [0,1]; they are regression values, not probabilities. Zero rounds returns the zero initial model. The first prefix can grow without bound as rounds increase, so this experiment carries no optimization or generalization guarantee.
from fractions import Fraction as F
def sequence(value):
if type(value) not in (list, tuple):
raise ValueError('expected list or tuple')
return value
def rational(value):
if type(value) not in (int, F):
raise ValueError('expected integer or Fraction, not bool or float')
return F(value)
def names(values):
values = tuple(sequence(values))
if any(type(v) is not str or not v for v in values):
raise ValueError('categories must be nonempty strings')
return values
def data(categories, labels, order):
categories = names(categories)
labels, order = tuple(sequence(labels)), tuple(sequence(order))
n = len(categories)
if not n or len(labels) != n or any(type(y) is not int or y not in (0, 1) for y in labels):
raise ValueError('nonempty matching binary labels required')
if len(order) != n or any(type(i) is not int for i in order) or set(order) != set(range(n)):
raise ValueError('order must be a permutation of row indices')
return categories, labels, order
def ordered_stats(categories, labels, order, prior=F(1, 2), strength=1):
categories, labels, order = data(categories, labels, order)
prior, strength = rational(prior), rational(strength)
if not 0 <= prior <= 1 or strength <= 0:
raise ValueError('prior in [0,1] and positive strength required')
stats, scores, audit = {}, [None] * len(labels), []
for i in order:
count, total = stats.get(categories[i], (0, 0))
score = (total + strength * prior) / (count + strength)
scores[i] = score
audit.append((i, count, total, score))
stats[categories[i]] = (count + 1, total + labels[i])
return {'scores': tuple(scores), 'audit': tuple(audit),
'model': {'prior': prior, 'strength': strength, 'stats': stats}}
def encode(model, categories):
# model is returned by ordered_stats; no labels or updates are accepted here.
output = []
for category in names(categories):
count, total = model['stats'].get(category, (0, 0))
output.append((total + model['strength'] * model['prior']) /
(count + model['strength']))
return tuple(output)
def ordered_constants(labels, order, rounds=2, rate=1):
labels = tuple(sequence(labels))
_, labels, order = data(('group',) * len(labels), labels, order)
if type(rounds) is not int or rounds < 0:
raise ValueError('rounds must be a nonnegative integer')
rate = rational(rate)
if not 0 < rate <= 1:
raise ValueError('rate must be in (0,1]')
y = tuple(F(labels[i]) for i in order)
models, trace = (F(0),) * (len(y) + 1), []
for _ in range(rounds):
# Freeze the old family before calculating this round's residuals.
residuals = tuple(y[j] - models[j] for j in range(len(y)))
total, updated = F(0), [F(0)]
for i, residual in enumerate(residuals, 1):
total += residual
updated.append(models[i] + rate * total / i)
models = tuple(updated)
trace.append((residuals, models))
return {'order': order, 'models': models, 'trace': tuple(trace),
'prediction': models[-1]}
if __name__ == '__main__':
categories = ('red', 'blue', 'red', 'green', 'blue', 'red')
labels = (1, 0, 0, 1, 1, 1)
order = tuple(range(6))
result = ordered_stats(categories, labels, order)
print('prefix scores:', tuple(map(str, result['scores'])))
print('full-data scores:', tuple(map(str, encode(result['model'], categories))))
print('new red / unseen:', tuple(map(str, encode(result['model'], ('red', 'violet')))))
changed = ordered_stats(categories, (1, 0, 1, 1, 1, 1), order)
print('row 2 before / after:', result['scores'][2], changed['scores'][2])
print('row 5 before / after:', result['scores'][5], changed['scores'][5])
toy = ordered_constants((1, 0, 1, 0), (0, 1, 2, 3), rounds=2)
for i, (residuals, models) in enumerate(toy['trace'], 1):
print('round', i, 'residuals', tuple(map(str, residuals)), 'models', tuple(map(str, models)))
print('ordered constant / ordinary two-step constant:', toy['prediction'], F(1, 2))
The output is
prefix scores: ('1/2', '1/2', '3/4', '1/2', '1/4', '1/2')
full-data scores: ('5/8', '1/2', '5/8', '3/4', '1/2', '5/8')
new red / unseen: ('5/8', '1/2')
row 2 before / after: 3/4 3/4
row 5 before / after: 1/2 5/6
round 1 residuals ('1', '0', '1', '0') models ('0', '1', '1/2', '2/3', '1/2')
round 2 residuals ('1', '-1', '1/2', '-2/3') models ('0', '2', '1/2', '5/6', '11/24')
ordered constant / ordinary two-step constant: 11/24 1/2
Changing record 2 from zero to one leaves its own ordered feature at 3/4, but changes record 5 from 1/2 to 5/6. New red items use 5/8 from the original complete training table; unseen violet uses 1/2. Re-encoding the training table with the deployment encoder produces the printed full-data scores, not the original training features.
In the constant experiment, round two uses residuals 1, −1, 1/2, −2/3. Their sum is −1/6, so the full-prefix constant moves from 1/2 to 1/2−1/24=11/24. Ordinary constant boosting with the same zero start and unit step reaches the sample mean 1/2 in round one and then stays there. The difference verifies a mechanism; it does not show which predictor is better on new inspections.
For n records and C distinct categories, validation plus one encoding pass uses expected O(n+1) dictionary operations and O(n+C+1) stored items, including returned scores and audit. Encoding q new names uses expected O(q+1) operations and O(q+1) extra items. The constant experiment takes O(n(T+1)) arithmetic operations and storage for T rounds because it retains every residual and model family. Without the trace, its working storage could be linear in n. These are unit-cost arithmetic/hash bounds; rational bit lengths and category-string lengths also affect actual time and memory.
Excluding one label does not finish the evaluation design
Ordinary out-of-fold target encoding trains a statistic on other folds and applies it to the held-out fold. That can be a useful pipeline component, but it does not construct the prefix model families used in ordered boosting. In scikit-learn 1.7.2, fit_transform uses cross-fitting whereas fit(...).transform(...) uses fitted full-data encodings. Those calls deliberately have different training semantics. Its global-mean/automatic-smoothing behavior also differs from our fixed prior.
A leave-one-out statistic deserves its own audit: removing a row’s label from one computation does not establish independence of the jointly constructed features and fitted downstream model. Likewise, a random row split can place the same customer or future information on both sides. Choose evaluation units before encoding, fit statistics within the allowed training data, and reserve validation labels for selecting or assessing the intended procedure. Artificial permutation order does not repair an invalid temporal or grouped split.
The fixed CatBoost parameter reference distinguishes Ordered and Plain boosting, input-order handling, and multiple tree-growth policies. Consequently, “CatBoost always uses ordered boosting” and “all supported trees must be symmetric” are both too broad. The paper’s symmetric trees apply one split condition across a level; the library interface has evolved beyond that single construction.
Our code omits category combinations, target quantization, multiple permutations, tree structures, regularization, categorical-statistic selection and production memory optimizations. A prior score for an unseen category is a fallback estimate, not evidence that the new category behaves like the population average. Evaluate its coverage and errors separately when new categories matter.
Check the information boundary
- For the original red category, what is record 2’s full-data encoding? How much does it change if its label is flipped from zero to one, with p=1/2 and a=1 fixed?
Show answer
Answer: There are three red records with target sum two, so the encoding is (2+1/2)/4=5/8. The flipped version is 7/8, an increase of 1/4. Its ordered encoding stays 3/4 because only the earlier red record is available.
- If the first record’s encoding uses a prior calculated from the mean of all six targets, is that encoding independent of its own target?
Show answer
Answer: No. With no history it equals that prior. Changing its target by one changes the encoding by 1/6. Excluding it from a category sum does not remove the global-prior dependency.
- Recalculate the final constant after two rounds for ordered labels 1,0,1,0, unit rate and zero initialization. Why must all residuals be computed before any model update?
Show answer
Answer: Round one gives prefix constants 0,1,1/2,2/3,1/2. Round two residuals are 1,−1,1/2,−2/3, summing to −1/6. The final constant is 11/24. Updating a prefix early and using that new value in a later residual would implement a different recurrence.
- A model uses out-of-fold target encoding followed by an ordinary boosted tree estimator. Has it implemented CatBoost’s ordered boosting? What can the pipeline still do correctly?
Show answer
Answer: No prefix family of boosting predictions has been constructed, so the boosting procedure remains ordinary. Properly isolated cross-fitting can still avoid directly using a row’s label in the statistic fitted on its other folds. Validation, group/time separation, smoothing and deployment encodings still need an explicit design.
Follow the dependency, then the implementation
The 2018 CatBoost paper links two uses of ordering: categorical statistics and residual construction. Its conceptual prefix algorithm explains the statistical motivation; the practical algorithm changes representation and computation to make tree boosting feasible. The title’s “unbiased” claim should be read with those models and assumptions, not as a blanket guarantee about every fitted function.
The versioned categorical guide connects that reasoning to configurable statistics and category combinations. The fixed TargetEncoder interface provides a useful contrasting design: fold-based encoding is a reusable transformation, while CatBoost coordinates encoding with boosting. Continue with data leakage and train/validation/test splits to place either method inside an evaluation protocol.
Make a prediction, then check
With a fixed prior and order, changing row 2’s target leaves its ordered statistic unchanged. Does this alone prove that the deployed predictor is unbiased?
Learning objectives
- Trace which labels can influence an ordered categorical statistic and a deployment encoding.
- Distinguish prefix residual models from ordinary cross-fitted target encoding.
- Audit fixed priors, permutations, finite recurrences and evaluation boundaries without assuming a general unbiasedness guarantee.
Prerequisites & connections
Explore related knowledge →References
- CatBoost: unbiased boosting with categorical features
Liudmila Prokhorenkova; Gleb Gusev; Aleksandr Vorobev; Anna Veronika Dorogush; Andrey Gulin · 2018 - CatBoost v1.2.8 — Transforming categorical features to numerical features
CatBoost developers - CatBoost v1.2.8 — Common training parameters
CatBoost developers - TargetEncoder — scikit-learn 1.7.2
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.
- Eight tests pass. Twelve encoder configurations use independently constructed category/position masks and quadratic stationarity to check scores and audit summaries. Thirty-two constant-prefix configurations use a finite nilpotent-matrix binomial expansion, not round-by-round recursion, to check final families and every retained round.
- Verified current/future-label exclusion under fixed priors and order, full deployment counts, unknown-category fallback, unchanged input/model state, smoothing bounds, order sensitivity, global-mean-prior leakage and zero rounds. The visible six-row case yields ordered scores 1/2,1/2,3/4,1/2,1/4,1/2; changing row 2 changes row 5 to 5/6. The constant experiment yields 11/24 versus ordinary 1/2, and a one-row four-round case reaches 4, demonstrating that outputs are not probabilities or generally convergent.
- Rejects eleven invalid training/order forms, seven invalid prior/strength pairs, six invalid round/rate pairs, four invalid query forms and empty constant training. Complete original Python is identical in both articles with eight actual stdout lines. Four displays, six anchors and four answered exercises per language pass strict MDX/KaTeX and actual React HTML; all four mathematical annotations match. A details-block formatting issue and Chinese literal emphasis markers were corrected before freezing.
- Read full bilingual prose under pinned Humanizer guidance. Research prose discusses contributions and contrasts; access and checking methods stay in metadata. All linked topic IDs exist in the catalogue; only currently available articles use direct wiki links. Complexity includes retained traces and validates empty-query/zero-round bounds. AI author checks only; review remains written pending independent technical review. No library training, benchmark, browser check or whole-site build.
- All eight author tests passed. A separate exact integration oracle multiplies Bernoulli likelihood polynomials and integrates against integer-shape or arcsine Beta priors: 32 complete encoder reports, 240 training/deployment values. A simultaneous residual/least-squares linear system solved by rational Gauss–Jordan elimination checks 48 complete constant-model reports and 256 unknowns; it does not replay rounds or use the author’s nilpotent-matrix formula. Four target perturbations independently check excluded labels and deployment sensitivity.
- Fully reread both languages, code, all four exercise answers and metadata. Verified fixed-prior dependence, read/emit/update order, frozen-prefix recurrence, unbounded first-prefix example, full deployment counts, unseen fallback, returned trace storage, finite hash/arithmetic complexity and no automatic probability/generalization guarantee. Strict MDX/KaTeX/React HTML independently passes four identical displayed formulas, six ordered anchors and four answers per language; actual MathML annotations and emphasis markers checked.
- 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:
- CatBoost: unbiased boosting with categorical features · Actually opened the proceedings PDF, 11 pages. Read cover authors/NeurIPS 2018, section 3.2 (PDF pages 3–4, lines 165–304) on greedy/leave-one-out/ordered target statistics, section 4 (pages 4–5, lines 305–535) on conditional prediction shift and prefix models, Algorithm 1 and section 5 (pages 6–7, lines 539–695) on shared structures, permutations, deployment statistics and categorical combinations. Did not reproduce the two-step theorem, benchmarks, supplementary proofs or example datasets. The original constant-model recurrence is an explicit restricted instantiation; no full CatBoost claim.
- CatBoost v1.2.8 — Transforming categorical features to numerical features · Direct web/raw and GitHub reads initially failed; this author shell also could not resolve raw.githubusercontent.com. Root fetched https://raw.githubusercontent.com/catboost/catboost/v1.2.8/catboost/docs/en/concepts/algorithm-main-stages_cat-to-numberic.md. Actually read the complete 5383-byte local source-v1.2.8-algorithm-main-stages_cat-to-numberic.md: beginning stages, combination section, binary formula and explicit previous-object note, and one_hot_max_size footer. Included external files were not expanded. A later mutable rendered page also succeeded, but article citation binds the tag.
- CatBoost v1.2.8 — Common training parameters · Root fetched https://raw.githubusercontent.com/catboost/catboost/v1.2.8/catboost/docs/en/references/training-parameters/common.md after confirming boosting.md is not the filename. Actually read local source-v1.2.8-training-common.md lines 570–602 (symmetric/depthwise/lossguide descriptions), 733–753 (has_time order), 1256–1285 (boosting schemes and conditional defaults). Raw macros remain; the article makes no exact default or hardware-speed claim. This is documentation reading, not library execution.
- TargetEncoder — scikit-learn 1.7.2 · Actually opened fixed 1.7 API rendered 1.7.2, lines 623–632 (shrinkage, unseen-category global mean, differing fit_transform semantics), 666–680 (smooth and cross-fitting), 685–699 (stored full encodings/mean), 777–783 (method note). No source examples or library execution used.
- CatBoost: unbiased boosting with categorical features · Independently opened the official 11-page proceedings PDF. Read §3.2 pages 3–4, §4.1–4.2 pages 4–5 and Algorithm 1/§5 pages 6–7: target-statistic leakage, prefix residual construction, conceptual versus shared tree implementation, Ordered/Plain modes and same-level split condition. Text extraction only; no supplementary theorem reproduction or benchmark verification claimed.
- CatBoost v1.2.8 — Transforming categorical features to numerical features · Independently read the complete retained source-v1.2.8-algorithm-main-stages_cat-to-numberic.md: previous-object formula, category combinations and one-hot footer. Root supplied this fixed-tag download; this reviewer did not fetch its bytes anew or expand included macros.
- CatBoost v1.2.8 — Common training parameters · Independently read the retained fixed-tag training-common.md lines 570–602, 733–753 and 1256–1285: growth policies, input order and Ordered/Plain schemes. Unexpanded macros prevent literal-default claims; the article correctly avoids those.
- TargetEncoder — scikit-learn 1.7.2 · Independently opened the official 1.7 API displayed as 1.7.2; read lines 623–632, 666–699, including cross-fitting versus full encodings, global prior and unknown-category handling. This supports a comparison of transformations, not a CatBoost implementation claim.
Related topics