1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
//! Divergence pins for `ferrolearn-tree/src/gradient_boosting.rs`
//! (`GradientBoostingRegressor` / `GradientBoostingClassifier`) against
//! scikit-learn 1.5.2.
//!
//! Reference: scikit-learn 1.5.2 (commit 156ef14), `sklearn/ensemble/_gb.py`:
//! - `_update_terminal_regions` :129-264 — after fitting
//! `DecisionTreeRegressor` to the negative gradient, REPLACE each leaf with
//! the loss-optimal line-search value (`argmin_x loss(y, raw_old + x*value)`,
//! :149-151), THEN `raw_prediction[:, k] += learning_rate *
//! tree.value[:,0,0].take(terminal_regions)` :262-264.
//! * `HalfSquaredError`: update is the IDENTITY — leaves stay the mean
//! residual, only raw is updated :155-157/:186 (→ the L2 GREEN linchpin).
//! * generic `else` (AbsoluteError / Huber) :241-247 —
//! `update = loss.fit_intercept_only(y[idx] - raw[idx,k], sw)`; for
//! `AbsoluteError` the WEIGHTED MEDIAN of the leaf residuals
//! (`sklearn/_loss/loss.py:565-574`).
//! * `HalfBinomialLoss` :191-206 — single Newton step
//! `Σw·neg_g / Σw·p(1-p)`, `p = y - neg_g = expit(raw)`.
//! - `__init__` defaults: GBR `loss='squared_error'`, `learning_rate=0.1`,
//! `n_estimators=100`, `subsample=1.0`, `max_depth=3` (:2051-2097); GBC
//! `loss='log_loss'`, same numerics (:1451-1495).
//!
//! Structural divergence (`.design/tree/gradient_boosting.md`, REQ-5/REQ-7):
//! ferrolearn's GBR `fit` loop and GBC `fit_binary`/`fit_multiclass` add the
//! regression tree's MEAN-residual leaf DIRECTLY (`f_vals[i] += lr*value`) for
//! EVERY loss — there is no `_update_terminal_regions` analog. The mean residual
//! IS the L2-optimal leaf (`HalfSquaredError` update is the identity), so
//! `loss='squared_error'` matches sklearn exactly (the GREEN linchpin below);
//! `absolute_error` (weighted median) and `log_loss` (Newton step) diverge from
//! round 1's leaf onward.
//!
//! All oracle values below come from a LIVE sklearn 1.5.2 run (the exact
//! `python3 -c "..."` invocation is quoted above each constant), NEVER copied
//! from the ferrolearn side (goal.md R-CHAR-3).
//!
//! `tests/*.rs` is anti-pattern-gate-exempt: `.unwrap()`/`assert!` are used
//! deliberately (no `panic!`/`unreachable!`).
use ;
use ;
use ;
/// `X = [[1],[2],...,[8]]`, the shared single-feature regression fixture.
// ===========================================================================
// GREEN — L2 GBR end-to-end parity (REQ-4 linchpin). MUST PASS now and stay
// green after the builder lands the terminal-region updates.
// ===========================================================================
/// GREEN (linchpin) — `GradientBoostingRegressor(loss='squared_error')`
/// `predict` matches sklearn array-by-array. The L2 `_update_terminal_regions`
/// is the identity (`_gb.py:155-157`/:186), so ferrolearn's mean-residual leaf
/// equals sklearn's optimal leaf, validating the whole init→residual→tree→
/// shrinkage→predict framework. Deterministic at `subsample=1.0`.
///
/// Live oracle (sklearn 1.5.2; deterministic, no RNG at subsample=1.0):
/// ```text
/// python3 -c "
/// import numpy as np
/// from sklearn.ensemble import GradientBoostingRegressor
/// X=np.arange(1,9.).reshape(-1,1); y=np.array([1,1,1,1,5,5,5,5.])
/// m=GradientBoostingRegressor(loss='squared_error',n_estimators=5,
/// learning_rate=0.1,max_depth=2,random_state=0,subsample=1.0).fit(X,y)
/// print(np.round(m.predict(X),12).tolist())
/// "
/// # -> [2.18098, 2.18098, 2.18098, 2.18098, 3.81902, 3.81902, 3.81902, 3.81902]
/// ```
// ===========================================================================
// GREEN — constructor numeric defaults (REQ-1) match sklearn get_params().
// ===========================================================================
/// GREEN — GBR/GBC constructor defaults match `get_params()` (sklearn 1.5.2)
/// for the exposed numeric params.
///
/// Live oracle:
/// ```text
/// python3 -c "
/// from sklearn.ensemble import GradientBoostingRegressor as R, GradientBoostingClassifier as C
/// print({k:R().get_params()[k] for k in ['n_estimators','learning_rate','max_depth','subsample']})
/// print({k:C().get_params()[k] for k in ['n_estimators','learning_rate','max_depth','subsample']})
/// "
/// # -> {'n_estimators': 100, 'learning_rate': 0.1, 'max_depth': 3, 'subsample': 1.0} (both)
/// ```
// ===========================================================================
// GREEN — deterministic reproducibility at subsample=1.0 (REQ-9/AC-8).
// ===========================================================================
/// GREEN — two `fit` calls with identical params + the same seed produce
/// IDENTICAL `predict` (subsample=1.0 → deterministic, no RNG boundary).
/// GREEN — GBC reproducibility (subsample=1.0, deterministic).
// ===========================================================================
// RED (REQ-5, blocker #734) — LAD weighted-MEDIAN terminal-region update.
// ===========================================================================
/// RED (HEADLINE) — `GradientBoostingRegressor(loss='absolute_error')` `predict`
/// must equal sklearn's. The fixture is SKEWED within each split leaf
/// (`y=[0,0,0,10,1,1,1,20]`) so the leaf MEAN differs sharply from the leaf
/// MEDIAN. sklearn replaces each leaf with the WEIGHTED MEDIAN of the leaf's
/// residuals `y[idx]-raw[idx]` (`_update_terminal_regions` generic `else`
/// `_gb.py:241-247` → `AbsoluteError.fit_intercept_only`,
/// `sklearn/_loss/loss.py:565-574`). ferrolearn instead adds the regression
/// tree's L2-mean-residual leaf directly (`f_vals[i] += lr*value`, GBR `fit`
/// loop) — there is NO `_update_terminal_regions` analog, so it diverges from
/// round 1.
///
/// Live oracle (sklearn 1.5.2; deterministic at subsample=1.0):
/// ```text
/// python3 -c "
/// import numpy as np
/// from sklearn.ensemble import GradientBoostingRegressor
/// X=np.arange(1,9.).reshape(-1,1); y=np.array([0,0,0,10,1,1,1,20.])
/// m=GradientBoostingRegressor(loss='absolute_error',n_estimators=3,
/// learning_rate=0.1,max_depth=2,random_state=0,subsample=1.0).fit(X,y)
/// print(np.round(m.predict(X),12).tolist())
/// "
/// # -> [0.729, 0.729, 0.729, 1.0, 1.0, 1.0, 1.0, 1.0]
/// ```
/// The init is `median(y) == 1.0` (matches); the divergence is entirely the
/// missing per-leaf median line-search. ferrolearn's mean-leaf output is
/// squared-error-shaped (pulled toward the 10/20 outliers) — it does NOT match
/// the clean L1-median family above. MUST currently FAIL.
///
/// Tracking: #734
// ===========================================================================
// RED (REQ-7, blocker #735) — LogLoss binary Newton terminal-region update.
// ===========================================================================
/// RED (HEADLINE) — `GradientBoostingClassifier` (binary) `predict_proba[:,1]`
/// must equal sklearn's. sklearn replaces each leaf with the single
/// Newton-Raphson step `Σw·(y-p) / Σw·p(1-p)` (`p = y - neg_g = expit(raw)`,
/// `_update_terminal_regions` `HalfBinomialLoss` branch `_gb.py:191-206`), then
/// `raw += lr*leaf` (:262-264). ferrolearn's GBC `fit_binary` adds the regression
/// tree's MEAN-residual leaf directly (`f_vals[i] += lr*value`) — no Newton
/// update — so the cumulative log-odds (and hence `predict_proba`) diverge from
/// round 1.
///
/// Live oracle (sklearn 1.5.2; deterministic at subsample=1.0):
/// ```text
/// python3 -c "
/// import numpy as np
/// from sklearn.ensemble import GradientBoostingClassifier
/// X=np.array([[1,2],[2,3],[3,3],[4,4],[5,6],[6,7],[7,8],[8,9.]])
/// y=np.array([0,0,0,0,1,1,1,1])
/// m=GradientBoostingClassifier(n_estimators=5,learning_rate=0.1,max_depth=2,
/// random_state=0,subsample=1.0).fit(X,y)
/// print(np.round(m.predict_proba(X)[:,1],12).tolist())
/// print(np.round(m.decision_function(X).ravel(),12).tolist())
/// "
/// # predict_proba[:,1] -> [0.297947595479 x4, 0.702052404521 x4]
/// # decision_function -> [-0.857090434608 x4, 0.857090434608 x4]
/// ```
/// The init log-odds is `log(0.5/0.5) == 0.0` (matches); the divergence is
/// entirely the missing per-leaf Newton step. ferrolearn's mean-leaf raw scores
/// produce a different probability family. MUST currently FAIL.
///
/// Tracking: #735
// ===========================================================================
// RED (NEW divergence, blocker #737) — LAD leaf median uses np.median
// (mean of the two middle values for even counts) instead of sklearn's
// `_weighted_percentile(residuals, ones, 50)` LOWER percentile (a single
// sorted element).
// ===========================================================================
/// RED (NEW) — `GradientBoostingRegressor(loss='absolute_error')` leaf value
/// for an EVEN-count leaf diverges.
///
/// `gradient_boosting.rs::lad_leaf_value` computes the leaf value as the numpy
/// median of the leaf residuals — for an even count it averages the two middle
/// sorted values (`(diffs[n/2-1] + diffs[n/2]) / 2`). sklearn does NOT use
/// `np.median` here: in `_update_terminal_regions` (`sklearn/ensemble/_gb.py:255`)
/// `sw = None if sample_weight is None else sample_weight[indices]`, and `fit`
/// always passes `sample_weight = _check_sample_weight(None, X) = np.ones(n)`
/// (NEVER `None`). So `AbsoluteError.fit_intercept_only`
/// (`sklearn/_loss/loss.py:571-574`) takes the
/// `_weighted_percentile(y_true, sample_weight, 50)` branch — the LOWER weighted
/// percentile (`sklearn/utils/stats.py:53-68`, `np.searchsorted` left), which
/// returns a SINGLE sorted element (the lower-middle for an even count), never an
/// average.
///
/// Fixture: `X=[[1]..[8]]`, `y=[0,0,0,0,10,20,30,41]`, `n_estimators=1,
/// learning_rate=1.0, max_depth=2`. `init = median(y) = 5`. The sign-gradient
/// tree splits at 4.5 → right leaf = samples {5..8} with residuals
/// `y[idx]-init = [5,15,25,36]` (even count, distinct middles). ferrolearn's
/// round-1 tree STRUCTURE is identical to sklearn's (verified), so the ONLY
/// divergence is the leaf-value rule:
/// * sklearn leaf = `_weighted_percentile([5,15,25,36], ones, 50) = 15.0`
/// (lower-middle) → predict = `5 + 1.0*15 = 20.0`.
/// * ferrolearn leaf = `np.median([5,15,25,36]) = (15+25)/2 = 20.0`
/// → predict = `5 + 1.0*20 = 25.0`.
///
/// Live oracle (sklearn 1.5.2; deterministic at subsample=1.0):
/// ```text
/// python3 -c "
/// import numpy as np
/// from sklearn.ensemble import GradientBoostingRegressor
/// X=np.arange(1,9.).reshape(-1,1); y=np.array([0,0,0,0,10,20,30,41.])
/// m=GradientBoostingRegressor(loss='absolute_error',n_estimators=1,
/// learning_rate=1.0,max_depth=2,random_state=0,subsample=1.0).fit(X,y)
/// print(m.predict(X).tolist())
/// "
/// # -> [0.0, 0.0, 0.0, 0.0, 20.0, 20.0, 20.0, 20.0]
/// # cross-check the leaf rule:
/// python3 -c "import numpy as np; from sklearn.utils.stats import _weighted_percentile; \
/// print(_weighted_percentile(np.array([5.,15.,25.,36.]), np.ones(4), 50))" # -> 15.0
/// ```
/// ferrolearn currently returns 25.0 for samples 5..8. MUST FAIL.
///
/// Tracking: #737
// ===========================================================================
// RED (NEW divergence, blocker #738) — Huber leaf median tie. The
// median fed into the clipped-mean term uses np.median (mean of two middles)
// instead of `_weighted_percentile(.,ones,50)` (lower percentile), so the
// Huber leaf value (and predict) diverges on even-count leaves.
// ===========================================================================
/// RED (NEW) — `GradientBoostingRegressor(loss='huber')` leaf value diverges on
/// an even-count leaf because its internal median uses the np.median tie
/// (average of the two middle values) instead of sklearn's lower percentile.
///
/// `HuberLoss.fit_intercept_only` (`sklearn/_loss/loss.py:704-710`) with
/// `sample_weight` (= np.ones, never None — see #737 / `_gb.py:255`) computes
/// `median = _weighted_percentile(y_true, sample_weight, 50)` (LOWER percentile),
/// then `median + np.average(sign(d-median)*min(delta,|d-median|))`. ferrolearn's
/// `huber_leaf_value` instead uses `(sorted[n/2-1]+sorted[n/2])/2` for the
/// median, so on an even-count leaf both the median AND the resulting clipped
/// mean diverge.
///
/// Fixture: `X=[[1]..[8]]`, `y=[0,0,0,0,10,20,30,41]`, `alpha=0.5`,
/// `n_estimators=1, learning_rate=1.0, max_depth=2`. `init = median(y) = 5`,
/// stage `delta = _weighted_percentile(|y-init|, ones, 50) = 5.0`. Right leaf
/// residuals `[5,15,25,36]`:
/// * sklearn: median = 15 (lower), term = sign(d-15)*min(5,|d-15|) =
/// `[-5,0,5,5]`, mean = 1.25 → leaf = 16.25 → predict = `5 + 16.25 = 21.25`.
/// * ferrolearn: median = (15+25)/2 = 20, term = `[-5,-5,5,5]`, mean = 0
/// → leaf = 20 → predict = `5 + 20 = 25.0`.
///
/// Live oracle (sklearn 1.5.2; deterministic at subsample=1.0):
/// ```text
/// python3 -c "
/// import numpy as np
/// from sklearn.ensemble import GradientBoostingRegressor
/// X=np.arange(1,9.).reshape(-1,1); y=np.array([0,0,0,0,10,20,30,41.])
/// m=GradientBoostingRegressor(loss='huber',alpha=0.5,n_estimators=1,
/// learning_rate=1.0,max_depth=2,random_state=0,subsample=1.0).fit(X,y)
/// print([round(v,12) for v in m.predict(X).tolist()])
/// "
/// # -> [0.0, 0.0, 0.0, 0.0, 21.25, 21.25, 21.25, 21.25]
/// ```
/// ferrolearn currently returns 25.0 for samples 5..8. MUST FAIL.
///
/// Tracking: #738