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
//! Gradient Boosting Classifier implementation.
//!
//! Implements gradient boosting with decision trees as weak learners.
use super::DecisionTreeClassifier;
use crate::error::Result;
/// Gradient Boosting Classifier.
///
/// Implements gradient boosting with decision trees as weak learners.
/// Uses gradient descent in function space to iteratively improve predictions.
///
/// # Algorithm
///
/// 1. Initialize with constant prediction (log-odds)
/// 2. For each boosting iteration:
/// - Compute negative gradients (pseudo-residuals)
/// - Fit a small decision tree to residuals
/// - Update predictions with `learning_rate` * `tree_prediction`
/// 3. Final prediction = sigmoid(sum of all tree predictions)
#[derive(Debug, Clone)]
pub struct GradientBoostingClassifier {
/// Number of boosting iterations (trees)
n_estimators: usize,
/// Learning rate (shrinkage parameter)
learning_rate: f32,
/// Maximum depth of each tree
max_depth: usize,
/// Initial prediction (log-odds for class 1)
init_prediction: f32,
/// Ensemble of decision trees
estimators: Vec<DecisionTreeClassifier>,
}
impl GradientBoostingClassifier {
/// Creates a new Gradient Boosting Classifier with default parameters.
///
/// # Default Parameters
///
/// - `n_estimators`: 100
/// - `learning_rate`: 0.1
/// - `max_depth`: 3
#[must_use]
pub fn new() -> Self {
Self {
n_estimators: 100,
learning_rate: 0.1,
max_depth: 3,
init_prediction: 0.0,
estimators: Vec::new(),
}
}
/// Sets the number of boosting iterations (trees).
#[must_use]
pub fn with_n_estimators(mut self, n_estimators: usize) -> Self {
self.n_estimators = n_estimators;
self
}
/// Sets the learning rate (shrinkage parameter).
///
/// Lower values require more trees but often lead to better generalization.
/// Typical values: 0.01 - 0.3
#[must_use]
pub fn with_learning_rate(mut self, learning_rate: f32) -> Self {
self.learning_rate = learning_rate;
self
}
/// Sets the maximum depth of each tree.
///
/// Smaller depths prevent overfitting. Typical values: 3-8
#[must_use]
pub fn with_max_depth(mut self, max_depth: usize) -> Self {
self.max_depth = max_depth;
self
}
/// ONE PATH: Delegates to `nn::functional::sigmoid_scalar` (UCBD §4).
fn sigmoid(x: f32) -> f32 {
crate::nn::functional::sigmoid_scalar(x)
}
/// Trains the Gradient Boosting Classifier.
///
/// # Arguments
///
/// - `x`: Feature matrix (`n_samples` × `n_features`)
/// - `y`: Binary labels (0 or 1)
///
/// # Returns
///
/// Ok(()) on success, Err with message on failure.
// Contract: gbm-v1, equation = "gradient_boost"
pub fn fit(&mut self, x: &crate::primitives::Matrix<f32>, y: &[usize]) -> Result<()> {
if x.n_rows() != y.len() {
return Err("x and y must have the same number of samples".into());
}
if x.n_rows() == 0 {
return Err("Cannot fit with 0 samples".into());
}
let n_samples = x.n_rows();
// Convert labels to {0.0, 1.0}
let y_float: Vec<f32> = y.iter().map(|&label| label as f32).collect();
// Initialize prediction with log-odds
let positive_count = y_float.iter().filter(|&&label| label == 1.0).count();
let p = positive_count as f32 / n_samples as f32;
self.init_prediction = if p > 0.0 && p < 1.0 {
(p / (1.0 - p)).ln()
} else if p >= 1.0 {
5.0 // Large positive value
} else {
-5.0 // Large negative value
};
// Current raw predictions (in log-odds space)
let mut raw_predictions = vec![self.init_prediction; n_samples];
// Clear any existing estimators
self.estimators = Vec::with_capacity(self.n_estimators);
// Gradient boosting iterations
for _ in 0..self.n_estimators {
// Compute probabilities from raw predictions
let probabilities: Vec<f32> =
raw_predictions.iter().map(|&r| Self::sigmoid(r)).collect();
// Compute negative gradients (pseudo-residuals)
// For log-loss: residual = y - p
let residuals: Vec<f32> = y_float
.iter()
.zip(probabilities.iter())
.map(|(&yi, &pi)| yi - pi)
.collect();
// Convert residuals to discrete labels for tree fitting
// Positive residual -> predict 1, Negative residual -> predict 0
let residual_labels = self.residuals_to_labels(&residuals);
// Fit a tree to the residuals
let mut tree = DecisionTreeClassifier::new().with_max_depth(self.max_depth);
tree.fit(x, &residual_labels)?;
// Get tree predictions (these are class labels 0 or 1)
let tree_preds = tree.predict(x);
// Convert tree predictions back to residual estimates
// Map 0 -> -1, 1 -> +1 for residual direction
let tree_residuals: Vec<f32> = tree_preds
.iter()
.map(|&pred| if pred == 0 { -1.0 } else { 1.0 })
.collect();
// Update raw predictions
for i in 0..n_samples {
raw_predictions[i] += self.learning_rate * tree_residuals[i];
}
self.estimators.push(tree);
}
Ok(())
}
/// Converts residuals to class labels for tree fitting.
///
/// Positive residuals -> class 1, negative residuals -> class 0
#[allow(clippy::unused_self)]
fn residuals_to_labels(&self, residuals: &[f32]) -> Vec<usize> {
residuals.iter().map(|&r| usize::from(r >= 0.0)).collect()
}
/// Predicts class labels for the given samples.
///
/// # Arguments
///
/// - `x`: Feature matrix (`n_samples` × `n_features`)
///
/// # Returns
///
/// Vector of predicted labels (0 or 1).
// Contract: gbm-v1, equation = "predict"
pub fn predict(&self, x: &crate::primitives::Matrix<f32>) -> Result<Vec<usize>> {
let probas = self.predict_proba(x)?;
Ok(probas
.iter()
.map(|probs| usize::from(probs[1] >= 0.5))
.collect())
}
/// Predicts class probabilities for the given samples.
///
/// # Arguments
///
/// - `x`: Feature matrix (`n_samples` × `n_features`)
///
/// # Returns
///
/// Vector of probability distributions, one per sample.
/// Each distribution is [P(class=0), P(class=1)].
pub fn predict_proba(&self, x: &crate::primitives::Matrix<f32>) -> Result<Vec<Vec<f32>>> {
if self.estimators.is_empty() {
return Err("Model not trained yet".into());
}
let n_samples = x.n_rows();
let mut raw_predictions = vec![self.init_prediction; n_samples];
// Sum predictions from all trees
for tree in &self.estimators {
let tree_preds = tree.predict(x);
let tree_residuals: Vec<f32> = tree_preds
.iter()
.map(|&pred| if pred == 0 { -1.0 } else { 1.0 })
.collect();
for i in 0..n_samples {
raw_predictions[i] += self.learning_rate * tree_residuals[i];
}
}
// Convert raw predictions to probabilities
Ok(raw_predictions
.iter()
.map(|&raw| {
let prob_class1 = Self::sigmoid(raw);
let prob_class0 = 1.0 - prob_class1;
vec![prob_class0, prob_class1]
})
.collect())
}
/// Returns the number of estimators (trees) in the ensemble.
#[must_use]
pub fn n_estimators(&self) -> usize {
self.estimators.len()
}
/// Returns the learning rate.
#[must_use]
pub fn learning_rate(&self) -> f32 {
self.learning_rate
}
/// Returns the max depth.
#[must_use]
pub fn max_depth(&self) -> usize {
self.max_depth
}
/// Returns the number of configured estimators.
#[must_use]
pub fn configured_n_estimators(&self) -> usize {
self.n_estimators
}
/// Returns a reference to the estimators.
#[must_use]
pub fn estimators(&self) -> &[DecisionTreeClassifier] {
&self.estimators
}
}
impl Default for GradientBoostingClassifier {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
#[path = "tests_gbm_contract.rs"]
mod tests_gbm_contract;