Extra Trees: random thresholds still compete
极端随机树
Inspect random threshold proposals, distinguish value-uniform from gap-uniform sampling, and compute exact stump-ensemble expectations.
extra-treesA random threshold can still compete
Suppose four test objects have measurements 0, 1, 9 and 10, with responses 0, 0, 10 and 10. Searching every possible training partition finds a perfect split between 1 and 9. Extra Trees tries a different route: propose a threshold at random, measure how good it is, and compare it with random proposals from other features. It saves threshold search, while making individual trees more varied.
The distinction is easy to miss. Extra Trees does not normally select a winning split without looking at the targets. The proposals are randomized; competition among them still uses supervised loss. In the original method, this operation repeats down each tree and predictions are combined across trees. Geurts, Ernst and Wehenkel introduced the method in their 2006 paper, whose Table 1 specifies this two-stage choice. Original paper, section 2.1.
Our executable experiment isolates that choice in regression stumps: trees with at most one split. It records every proposed threshold, fits leaf means and averages several stumps. An exact finite-grid calculation then shows what averaging can and cannot remove. For recursive growth and pruning, see CART; for bootstrap sampling and out-of-bag evaluation, see random forests chapter.
Randomize the proposal, retain the loss comparison
At a node, the numerical version of the original algorithm samples K nonconstant features and draws one cut-point uniformly from each feature’s observed minimum-to-maximum range. It chooses the highest-scoring proposal, then recurses. It stops for a small node, constant features or a constant target. The original trees use the full training sample, rather than bootstrap replicas, and regression combines them by averaging. Geurts et al., section 2.1 and Table 1.
For squared-error regression, the parent is the same for all proposals, so maximizing variance reduction is equivalent to minimizing child squared errors. With n observations and candidate set C, our comparison is:
The random candidate set restricts this optimization. Its winning training loss cannot be smaller than the optimum over every feature and every admissible training partition. That statement concerns one node on the same data and loss. It neither ranks the generalization error of complete forests nor says that the same feature wins at later nodes.
Increasing K gives the node more proposals to compare. If one explicitly adds candidates while keeping the previous ones, the minimum training loss cannot increase. Separate runs with different K and random streams need not have nested candidate sets, so their realized losses need not follow that ordering. Even considering all features leaves threshold randomness. With K=1 there is no competition between proposals, but leaf predictions still use targets; a target-dependent stopping rule also prevents an unqualified claim that the entire algorithm ignores labels.
Uniform values are not uniform gaps
Let a feature’s sorted distinct values be v₁ through vₘ. For an ideal continuously uniform threshold t in its range, the probability of obtaining the partition after value vᵢ is:
This follows from interval length divided by total length. Endpoints have probability zero in the continuous model. For 0, 1, 9, 10, the three partition probabilities are 1/10, 8/10 and 1/10, not one third each. A uniform choice among adjacent midpoints would implement a different distribution.
This also explains a useful invariance boundary. Positive affine feature transformations preserve relative interval lengths and can map every threshold to the same partition. A general increasing transformation preserves the order of observations but changes interval lengths. Mapping 0, 1, 9, 10 to 0, 1, 2, 3 changes the ideal partition probabilities to one third each. Exhaustive threshold optimization still sees the same training partitions; uniform-range randomization sees a different proposal distribution.
A finite grid makes the randomness inspectable
The program uses G equally likely midpoint locations inside each observed range, rather than claiming exact continuous random sampling:
Every proposed threshold is strictly between the feature minimum aⱼ and maximum bⱼ, so both children are nonempty. An interior observation can still equal the threshold: our explicit convention sends equality left. The finite partition probability is the number of grid locations in that partition’s interval divided by G. With G=10, the first example has probabilities 1/10, 8/10, 1/10 exactly. After the transformation to 0, 1, 2, 3, that grid gives 3/10, 4/10, 3/10, approximating rather than equaling the continuous thirds.
Averaging reduces a random component, not every error
Fix a training dataset and an evaluation pair (x,y). Let Z be the prediction of a stump under the declared randomization. For B independent draws from that same distribution:
To derive it, subtract and add E Z inside the square. The centered average has mean zero; its cross terms vanish by independence, leaving Var(Z)/B. Averaging this identity over fixed evaluation points gives the corresponding mean squared error. The expectation here is over algorithmic draws with the data held fixed. It is not a statement about noise, new samples or training-data variability.
For the one-feature example at G=10, the limiting mean predictions on the four training inputs are 1/3, 1, 9 and 29/3. Their MSE is 5/9, although the best deterministic stump has zero error. The expected single-stump MSE is 10/3. Therefore:
The remaining 5/9 is the squared discrepancy of this randomization’s mean predictor on these fixed points. Calling it an irreducible noise level would be wrong. The zero-error deterministic split already provides a counterexample. Three ideal independent grid draws have expected MSE 40/27; a particular draw can lie above or below that value.
Read the proposals, then inspect the winner
fit_stumps accepts a nonempty rectangular matrix X and matching targets y, all integers or Fraction values. It rejects booleans and floats. The numbers of stumps, grid points and requested features are positive integers; max_features cannot exceed the matrix dimension. At each draw it samples up to that many nonconstant features without replacement, sorts their indices, and generates one threshold per selected feature. Ties favor the lower feature index. A zero-gain proposal is permitted; constant targets or entirely constant features instead produce a mean-only leaf.
Random(seed) supplies repeatable pseudorandom choices for this code and runtime. The exact distribution calculation separately assumes ideal independent uniform grid draws; a fixed seed is not a proof of independence. There is no row resampling, recursive growth, pruning or missing-value handling. Every stump sees every training row. The internal split helpers expect validated, nonempty partitions, and predict expects a model returned by fit_stumps, not an arbitrary external dictionary.
from collections import namedtuple
from fractions import Fraction as F
from random import Random
Split = namedtuple('Split', 'feature threshold left_mean right_mean mse')
def rational(value):
if type(value) is int or isinstance(value, F):
return F(value)
raise ValueError('expected integer or Fraction, not bool or float')
def positive_int(value):
if type(value) is not int or value < 1:
raise ValueError('expected positive integer')
return value
def prepare(X, y):
if type(X) not in (list, tuple) or not X:
raise ValueError('nonempty feature matrix required')
if type(y) not in (list, tuple) or len(y) != len(X):
raise ValueError('matching target sequence required')
rows = []
for row in X:
if type(row) not in (list, tuple) or not row:
raise ValueError('nonempty feature rows required')
rows.append(tuple(rational(v) for v in row))
d = len(rows[0])
if any(len(row) != d for row in rows):
raise ValueError('ragged matrix')
return tuple(rows), tuple(rational(v) for v in y)
def moments(values):
mean = sum(values, F()) / len(values)
return mean, sum(((y - mean)**2 for y in values), F())
def leaf(y):
mean, sse = moments(y)
return Split(None, None, mean, mean, sse / len(y))
def split(X, y, feature, threshold):
left = tuple(v for row, v in zip(X, y) if row[feature] <= threshold)
right = tuple(v for row, v in zip(X, y) if row[feature] > threshold)
a, s = moments(left)
b, t = moments(right)
return Split(feature, threshold, a, b, (s + t) / len(y))
def value(stump, row):
if stump.feature is None or row[stump.feature] <= stump.threshold:
return stump.left_mean
return stump.right_mean
def fit_stumps(X, y, trees=3, max_features=1, grid=10, seed=0):
X, y = prepare(X, y)
trees, k, grid = map(positive_int, (trees, max_features, grid))
if k > len(X[0]) or type(seed) is not int:
raise ValueError('max_features exceeds dimension or seed is not integer')
ranges = tuple((min(row[j] for row in X), max(row[j] for row in X))
for j in range(len(X[0])))
active = tuple(j for j, (lo, hi) in enumerate(ranges) if lo < hi)
rng, stumps, traces = Random(seed), [], []
for _ in range(trees):
candidates = []
if active and len(set(y)) > 1:
for j in sorted(rng.sample(active, min(k, len(active)))):
lo, hi = ranges[j]
r = rng.randrange(grid)
threshold = lo + (hi - lo) * F(2*r + 1, 2*grid)
candidates.append(split(X, y, j, threshold))
chosen = min(candidates, key=lambda s: (s.mse, s.feature, s.threshold)) if candidates else leaf(y)
stumps.append(chosen)
traces.append(tuple(candidates))
return {'dimension': len(X[0]), 'stumps': tuple(stumps), 'candidates': tuple(traces)}
def best_stump(X, y):
X, y = prepare(X, y)
chosen = leaf(y)
if len(set(y)) == 1:
return chosen
for j in range(len(X[0])):
values = sorted(set(row[j] for row in X))
for low, high in zip(values, values[1:]):
candidate = split(X, y, j, (low + high) / 2)
if chosen.feature is None or candidate.mse < chosen.mse:
chosen = candidate
return chosen
def predict(model, X):
# model is the output of fit_stumps, not an arbitrary external dictionary.
if type(X) not in (list, tuple):
raise ValueError('query list or tuple required')
queries = []
for row in X:
if type(row) not in (list, tuple) or len(row) != model['dimension']:
raise ValueError('query dimension mismatch')
queries.append(tuple(rational(v) for v in row))
return tuple(sum((value(s, row) for s in model['stumps']), F()) / len(model['stumps'])
for row in queries)
def grid_summary(X, y, grid=10, trees=3):
X, y = prepare(X, y)
grid, trees = map(positive_int, (grid, trees))
if len(X[0]) != 1:
raise ValueError('exact grid summary requires one feature')
lo, hi = min(row[0] for row in X), max(row[0] for row in X)
if lo == hi or len(set(y)) == 1:
law = (leaf(y),) * grid
else:
law = tuple(split(X, y, 0, lo + (hi-lo)*F(2*r+1, 2*grid)) for r in range(grid))
means = tuple(sum((value(s, row) for s in law), F()) / grid for row in X)
single = sum((s.mse for s in law), F()) / grid
mean_mse = sum(((a-b)**2 for a,b in zip(means,y)), F()) / len(y)
return {'mean_predictions': means, 'single_mse': single, 'mean_mse': mean_mse,
'expected_ensemble_mse': mean_mse + (single-mean_mse)/trees}
if __name__ == '__main__':
X = ((0,0), (1,1), (9,2), (10,3))
y = (0,0,10,10)
model = fit_stumps(X,y,trees=3,max_features=2,grid=10,seed=6)
for i, (candidates, chosen) in enumerate(zip(model['candidates'],model['stumps'])):
print('draw',i,tuple((s.feature,str(s.threshold),str(s.mse)) for s in candidates),
'winner',chosen.feature)
optimum = best_stump(X,y)
print('best threshold:',optimum.feature,optimum.threshold,'MSE:',optimum.mse)
print('sampled predictions:',tuple(str(v) for v in predict(model,X)))
law = grid_summary(tuple((row[0],) for row in X),y,grid=10,trees=3)
print('exact mean predictions:',tuple(str(v) for v in law['mean_predictions']))
print('single / mean / three:',str(law['single_mse']),str(law['mean_mse']),
str(law['expected_ensemble_mse']))
Actual output:
draw 0 ((0, '9/2', '0'), (1, '3/20', '50/3')) winner 0
draw 1 ((0, '19/2', '50/3'), (1, '9/4', '50/3')) winner 0
draw 2 ((0, '1/2', '50/3'), (1, '27/20', '0')) winner 1
best threshold: 0 5 MSE: 0
sampled predictions: ('10/9', '10/9', '70/9', '10')
exact mean predictions: ('1/3', '1', '9', '29/3')
single / mean / three: 10/3 5/9 40/27
The first experiment uses two differently spaced measurements of the same ordering. Each draw compares two proposals. On draw 1 both miss the zero-error partition, so the selected MSE is 50/3. The routine does not secretly scan more thresholds to rescue it. On draw 2 the second feature wins with a zero-error proposal. Their average predictions are 10/9, 10/9, 70/9 and 10. All three stumps used the same four rows.
best_stump enumerates all adjacent-value midpoints on all features for a training-loss comparison. It uses lower feature index and lower threshold for equal minima, and returns a mean leaf when the target is constant or no feature can split. The two-feature optimum is feature 0 at threshold 5, with MSE zero.
grid_summary is a separate one-feature experiment using only the first measurement. It enumerates every grid location, including duplicates of the same training partition, because each location carries its own probability mass. It computes the mean prediction and both single-stump and ensemble expected training MSE. It does not apply the one-feature law to the earlier two-feature competition. The tests independently enumerate rank partitions and short sequences of outcomes to check that expectation.
For n rows, d features and B stumps, this implementation prepares data and ranges in O(nd) operations. Each draw costs at most O(d+kn+k log(k+1)), where k is max_features; this includes feature sampling, sorting and rescanning observations for its candidates. Temporary data and retained candidate records use O(nd+Bk+d) slots. Exhaustive best_stump takes O(dn²) operations with O(nd) working storage. These are arithmetic/expected-hashing bounds for this straightforward code, not optimized-library benchmarks.
For q query rows, predict uses O(q(d+B)+1) operations and O(qd+1) auxiliary slots, including validation and copied queries; an empty query list returns an empty tuple. grid_summary accepts only d=1 and takes O(n(G+1)) arithmetic operations and O(n+G) storage. Large rational numerators, denominators and random integer ranges add bit costs. Exact fractions and retained proposal records make this teaching run inspectable, at a computational and storage cost.
Keep sampling choices separate
Random thresholds and bootstrap sampling are independent design choices. In the fixed scikit-learn 1.7.2 ExtraTreesRegressor documentation, bootstrap=False means that each tree uses the full dataset, while max_features=1.0 considers all features. It still draws random thresholds. Bootstrap can be enabled, and the documented out-of-bag score requires it. These defaults are not a requirement that all Extra Trees implementations must follow. ExtraTreesRegressor API.
The same version’s guide contrasts random-forest threshold search with the random proposals of Extra Trees, and distinguishes their default row sampling. Its general discussion of variance and bias describes a motivation, not a promise that either method wins on every dataset. Randomized tree ensembles, sections 1.11.2.1–1.11.2.3.
The range calculation is sensitive to extreme feature values: an outlier can stretch a range so that many uniform proposals fall into a large, sparsely occupied gap. A nonlinearly transformed feature can therefore alter the randomization even when its ranks do not change. These are properties of the proposal mechanism, not evidence that scaling always improves prediction.
Our one-split limit cannot represent an interaction requiring several successive questions. The grid may also give a narrow but useful interval no probability mass at all. Increasing the number of sampled stumps cannot recover a candidate assigned probability zero by that grid. Change the proposal family or grid resolution if that distinction matters. A real comparison should hold the data split and evaluation loss fixed while examining depth, feature count, sampling and computational budget; retain a final test set outside tuning.
Predict a distribution, not just a seed
- For observed values 0, 1, 9, 10, what are the probabilities of the three training partitions under a continuously uniform threshold? Does uniformly choosing one adjacent midpoint reproduce them? Answer: 1/10, 8/10, 1/10. Uniform midpoint selection instead gives one third each. The two procedures favor different partitions.
- In the G=10 one-feature experiment, calculate the expected three-stump training MSE and its limit as B increases. Why is the limit not irreducible noise? Answer: the formula gives 40/27 for B=3 and limit 5/9. A deterministic threshold between 1 and 9 fits all four observations exactly, so the remainder comes from this randomized mean predictor, not unavoidable noise.
- If
max_featuresequals the input dimension andbootstrap=False, is the method deterministic? What if the only varying feature gives zero gain? Answer: threshold draws still vary. In this teaching program a nonconstant target with a valid zero-gain proposal is split; constant targets stop. A fixed seed reproduces a run but does not remove the algorithm’s randomization. - Apply an increasing transformation taking 0, 1, 9, 10 to 0, 1, 2, 3. Compare continuous and G=10 grid partition probabilities, and the best achievable deterministic training split. Answer: continuous probabilities become one third each; the finite grid gives 3/10, 4/10, 3/10. The same zero-error rank partition remains available to exhaustive optimization. Positive affine transformations would preserve the relative gap widths instead.
The distribution of candidate splits is part of the model
The 2006 paper separates random cut-point generation, feature competition and ensemble aggregation. It also studies geometric and kernel interpretations of the resulting partitions. Its experiments use particular datasets and parameter settings; they do not establish a universal ranking against random forests. The paper’s use of whole-sample training and unpruned trees helps explain why “more random thresholds” should not be interpreted as simply adding one option to an otherwise identical training pipeline.
The fixed-version implementation guide connects the mechanism to practical parameters. A useful next experiment is to hold the sampled features fixed, vary only the threshold proposal distribution, and record which partitions become more common. Then compare that change with increasing depth. Those interventions answer different questions: one changes the distribution over candidate questions; the other changes how many questions each tree can ask.
Make a prediction, then check
For observed values 0, 1, 9, 10, what is the chance that an ideal uniform-range threshold lies between 1 and 9?
Learning objectives
- Separate random threshold proposals, supervised candidate selection and optional bootstrap sampling.
- Derive gap probabilities and explain why increasing feature transforms can change uniform-range randomization.
- Compute a finite stump ensemble’s exact expectation while distinguishing algorithmic randomness from new-data uncertainty.
Prerequisites & connections
Explore related knowledge →References
- Extremely randomized trees
Pierre Geurts, Damien Ernst and Louis Wehenkel · 2006 - scikit-learn 1.7 — Ensembles: gradient boosting, random forests, bagging, voting, stacking
scikit-learn developers - ExtraTreesRegressor — scikit-learn 1.7
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.
- Nine tests passed. Twelve small fitted datasets use pairwise response-difference SSE to verify all returned proposals, winner scores and exhaustive optimal thresholds. Seeded visible competition includes a missed optimal split, a tied choice and a win by the other feature. Target-independent proposals, feature limits and exact grid membership were checked.
- A separate rank-partition probability law counts grid mass by integer inequalities, then enumerates short independent outcome sequences for four models and B=1,2,3. All twelve ensemble expectations agree. Verified gap probabilities 1/10,8/10,1/10 versus transformed 3/10,4/10,3/10; exact equality routing; single MSE 10/3, mean-predictor MSE 5/9 and three-stump expected MSE 40/27.
- Checked constant features/targets, accepted zero-gain splits, positive affine transforms, target scaling, seed reproducibility, copied inputs, empty prediction queries and invalid contracts. Complete original bilingual prose with identical Python, seven actual stdout lines, five identical displays, six anchors and four answered exercises. Strict MDX/KaTeX and actual React HTML passed, with all five mathematical annotations matching. Humanizer reread; AI author checks only, review written pending independent review. No repository edits or whole-site build.
- All nine author tests passed. Independently solved two-column least-squares normal equations for 33 proposed splits across eight fitted models, using the quadratic-form residual objective rather than group residuals or pairwise differences. Winner/tie choices and 32 ensemble predictions agree.
- A second reference constructs exact orthogonal projection matrices for possible partitions. Closed-form threshold CDFs supply grid probabilities without enumerating grid draws; E[H] and E[H]^2 give single, mean-predictor and finite-ensemble quadratic risks using H^2=H and independence. Seven models and B=1,2,5,11 yield 28 matching full reports, including duplicates, equality routing, one-point grids, constant inputs/targets and rational coordinates.
- Reviewed the original algorithm versus bounded stump model, one random proposal per selected feature, supervised winner selection, zero-gain acceptance, constant-target stopping and optional bootstrap. Numerical-uniform gaps differ from uniform adjacent-midpoint sampling; positive affine invariance does not extend to arbitrary increasing transformations. Candidate-set monotonicity is asserted only for genuinely nested proposals.
- Reviewed exact finite-grid expectation 10/3, mean-predictor loss 5/9 and three-stump expected loss 40/27, conditional algorithmic randomness versus new-data noise, helper preconditions and conservative arithmetic/storage bounds. Both full languages, exercises and source attribution are consistent. Strict actual HTML gives five displays, six required anchors and four answers each; all five math annotations match and the final five SHA values match the frozen manifest.
- 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:
- Extremely randomized trees · Actually opened author-hosted 40-page PDF. First page lines 0–16 gives authors, DOI 10.1007/s10994-006-6226-1, online date 2 March 2006 and abstract geometric/kernel scope. Read PDF pages 3–4, section 2.1/Table 1, lines 95–160: K nonconstant features, uniform min-to-max cut-point, best proposal, node/feature/target stopping, full sample and regression averaging. Read pages 5–6 lines 193–240: comparisons, parameter settings and variance-reduction score. This preprint has blank journal page headers; locations refer to PDF page order, not invented printed pages. Text extraction only; no copied assets or full-paper visual review.
- scikit-learn 1.7 — Ensembles: gradient boosting, random forests, bagging, voting, stacking · Actually read https://scikit-learn.org/1.7/modules/ensemble.html, rendered 1.7.2, sections 1.11.2.1–1.11.2.3, lines 514–563: search over thresholds in random forests, one random threshold per candidate feature in Extra Trees, bias/variance motivation and default row sampling. Did not adopt the guide’s loose bagging equivalence as a claim that max_features=1.0 removes threshold randomness.
- ExtraTreesRegressor — scikit-learn 1.7 · Actually opened fixed API rendered 1.7.2. Lines 671–690: max_features default 1.0, all-feature meaning and valid-partition search caveat; lines 711–732: bootstrap default False, full-data meaning, OOB requiring True and random feature/cut-point sources. No library run or exact source-code replication claimed; the article explicitly implements bounded stumps with finite grid proposals.
- Extremely randomized trees · Independently opened the author-hosted 40-page paper. First page identifies authors, DOI and online publication 2 March 2006. Read PDF pages 3–4, section 2.1/Table 1, on nonconstant feature selection, uniform numerical cuts, supervised competition, stopping, full-sample training and aggregation; pages 5–6 compare algorithms and specify variance reduction. Locations are PDF order, not invented printed page numbers. Text extraction; no benchmark reproduction or copied code.
- scikit-learn 1.7 — Ensembles: gradient boosting, random forests, bagging, voting, stacking · Independently read the fixed 1.7 guide rendered 1.7.2, sections 1.11.2.1–1.11.2.3 (lines 514–562), on exhaustive versus randomly proposed thresholds, averaging and parameters. The loose all-feature/bagging equivalence is not adopted: the article correctly retains threshold randomness when all features are considered.
- ExtraTreesRegressor — scikit-learn 1.7 · Independently opened the fixed API rendered 1.7.2, lines 637–690 and 711–732: squared-error means, all-feature default, valid-split search qualification, bootstrap=False, OOB requiring bootstrap=True and separate randomness sources. No library execution. The article correctly limits its own implementation to exact finite-grid stumps.
Related topics