hnbm 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
hnbm-0.1.0/Dockerfile ADDED
@@ -0,0 +1,11 @@
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ COPY requirements.txt setup.py setup.cfg MANIFEST.in README.md LICENSE ./
6
+ COPY hnbm/ hnbm/
7
+
8
+ RUN pip install --no-cache-dir --upgrade pip \
9
+ && pip install --no-cache-dir .
10
+
11
+ CMD ["python", "-c", "from hnbm import HNBM; print('HNBM ready')"]
hnbm-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 qiancapital-dev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
hnbm-0.1.0/MANIFEST.in ADDED
@@ -0,0 +1,3 @@
1
+ include README.md
2
+ include requirements.txt
3
+ include Dockerfile
hnbm-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,143 @@
1
+ Metadata-Version: 2.4
2
+ Name: hnbm
3
+ Version: 0.1.0
4
+ Summary: Heterogeneous Newton Boosting Machine
5
+ Home-page: https://github.com/qiancapital-dev/hnbm
6
+ Author: Qian Capital
7
+ Author-email: Qian Capital <samson.qian@qiancapital.com>
8
+ License: MIT
9
+ Project-URL: Homepage, https://github.com/qiancapital-dev/hnbm
10
+ Keywords: boosting,gradient-boosting,hnbm,heterogeneous-newton
11
+ Requires-Python: >=3.8
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: numpy>=1.20
15
+ Requires-Dist: scikit-learn>=1.0
16
+ Requires-Dist: tqdm>=4.50
17
+ Dynamic: author
18
+ Dynamic: home-page
19
+ Dynamic: license-file
20
+ Dynamic: requires-python
21
+
22
+ # HNBM
23
+
24
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
25
+ [![scikit-learn](https://img.shields.io/badge/scikit--learn-compatible-blue.svg)](https://scikit-learn.org/)
26
+
27
+ **Heterogeneous Newton Boosting Machine (HNBM)** — a scikit-learn-compatible gradient boosting framework that stochastically mixes heterogeneous base learners at each iteration.
28
+
29
+ Unlike standard gradient boosting libraries that use a single learner type (typically decision trees), HNBM lets you define a pool of base learners with selection probabilities. At each boosting round, a learner is drawn from that pool and fit to the Newton step (gradient divided by Hessian, weighted by the Hessian).
30
+
31
+ This is the core framework behind [SnapBoost](https://github.com/qiancapital/snapboost), inspired by [SnapBoost: A Heterogeneous Boosting Machine](https://arxiv.org/abs/2006.09745) (Parnell et al., NeurIPS 2020).
32
+
33
+ ---
34
+
35
+ ## Installation
36
+
37
+ **From source** (recommended until PyPI release):
38
+
39
+ ```bash
40
+ git clone https://github.com/qiancapital-dev/hnbm.git
41
+ cd hnbm
42
+ pip install .
43
+ ```
44
+
45
+ **Requirements**: Python ≥ 3.8, NumPy, scikit-learn, tqdm.
46
+
47
+ ---
48
+
49
+ ## Quick Start
50
+
51
+ Subclass `HNBM` and configure your base learner pool before training:
52
+
53
+ ```python
54
+ from sklearn.datasets import load_breast_cancer
55
+ from sklearn.model_selection import train_test_split
56
+ from sklearn.tree import DecisionTreeRegressor
57
+ from hnbm import HNBM
58
+
59
+ X, y = load_breast_cancer(return_X_y=True)
60
+ X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
61
+
62
+
63
+ class TreeBoost(HNBM):
64
+ def __init__(self, max_depth=5, **kwargs):
65
+ super().__init__(**kwargs)
66
+ self.base_learners_ = [DecisionTreeRegressor(max_depth=max_depth)]
67
+ self.probabilities_ = [1.0]
68
+
69
+
70
+ model = TreeBoost(
71
+ num_iterations=100,
72
+ learning_rate=0.1,
73
+ mode="classification",
74
+ random_state=42,
75
+ )
76
+ model.fit(X_train, y_train)
77
+
78
+ print("Accuracy:", model.score(X_test, y_test))
79
+ model.evaluate(X_test, y_test)
80
+ ```
81
+
82
+ ---
83
+
84
+ ## API Reference
85
+
86
+ ### `HNBM`
87
+
88
+ | Parameter | Type | Default | Description |
89
+ |-----------|------|---------|-------------|
90
+ | `num_iterations` | `int` | `100` | Number of boosting rounds |
91
+ | `learning_rate` | `float` | `0.1` | Shrinkage per learner |
92
+ | `mode` | `str` | `"classification"` | `"classification"` or `"regression"` |
93
+ | `random_state` | `int` or `None` | `None` | Seed for learner selection |
94
+ | `verbose` | `bool` | `True` | Show tqdm progress bar |
95
+
96
+ **Methods**
97
+
98
+ | Method | Mode | Description |
99
+ |--------|------|-------------|
100
+ | `fit(X, y)` | both | Train the ensemble |
101
+ | `predict(X)` | both | Class labels (0/1) or continuous values |
102
+ | `predict_proba(X)` | classification | Probabilities, shape `(n_samples, 2)` |
103
+ | `decision_function(X)` | classification | Raw logits |
104
+ | `score(X, y)` | both | Accuracy or R² |
105
+ | `evaluate(X, y)` | both | Prints and returns log loss or RMSE |
106
+
107
+ **Subclass contract**: set `base_learners_` (list of unfitted sklearn regressors) and `probabilities_` (list summing to 1) before calling `fit`.
108
+
109
+ ### Loss functions
110
+
111
+ `hnbm.losses` provides `Logistic` (classification) and `MeanSquaredError` (regression), each with a `compute_derivatives(y, f)` method returning gradient and Hessian vectors.
112
+
113
+ ---
114
+
115
+ ## Docker
116
+
117
+ ```bash
118
+ docker build -t hnbm .
119
+ docker run --rm hnbm
120
+ ```
121
+
122
+ ---
123
+
124
+ ## Development
125
+
126
+ ```bash
127
+ git clone https://github.com/qiancapital-dev/hnbm.git
128
+ cd hnbm
129
+ pip install -r requirements.txt
130
+ pip install -e .
131
+ ```
132
+
133
+ ---
134
+
135
+ ## Related projects
136
+
137
+ - **[snapboost](https://github.com/QianCapital/snapboost)** — a concrete HNBM using decision trees and kernel ridge regressors
138
+
139
+ ---
140
+
141
+ ## License
142
+
143
+ MIT — See [LICENSE](LICENSE) for full text.
hnbm-0.1.0/README.md ADDED
@@ -0,0 +1,122 @@
1
+ # HNBM
2
+
3
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4
+ [![scikit-learn](https://img.shields.io/badge/scikit--learn-compatible-blue.svg)](https://scikit-learn.org/)
5
+
6
+ **Heterogeneous Newton Boosting Machine (HNBM)** — a scikit-learn-compatible gradient boosting framework that stochastically mixes heterogeneous base learners at each iteration.
7
+
8
+ Unlike standard gradient boosting libraries that use a single learner type (typically decision trees), HNBM lets you define a pool of base learners with selection probabilities. At each boosting round, a learner is drawn from that pool and fit to the Newton step (gradient divided by Hessian, weighted by the Hessian).
9
+
10
+ This is the core framework behind [SnapBoost](https://github.com/qiancapital/snapboost), inspired by [SnapBoost: A Heterogeneous Boosting Machine](https://arxiv.org/abs/2006.09745) (Parnell et al., NeurIPS 2020).
11
+
12
+ ---
13
+
14
+ ## Installation
15
+
16
+ **From source** (recommended until PyPI release):
17
+
18
+ ```bash
19
+ git clone https://github.com/qiancapital-dev/hnbm.git
20
+ cd hnbm
21
+ pip install .
22
+ ```
23
+
24
+ **Requirements**: Python ≥ 3.8, NumPy, scikit-learn, tqdm.
25
+
26
+ ---
27
+
28
+ ## Quick Start
29
+
30
+ Subclass `HNBM` and configure your base learner pool before training:
31
+
32
+ ```python
33
+ from sklearn.datasets import load_breast_cancer
34
+ from sklearn.model_selection import train_test_split
35
+ from sklearn.tree import DecisionTreeRegressor
36
+ from hnbm import HNBM
37
+
38
+ X, y = load_breast_cancer(return_X_y=True)
39
+ X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
40
+
41
+
42
+ class TreeBoost(HNBM):
43
+ def __init__(self, max_depth=5, **kwargs):
44
+ super().__init__(**kwargs)
45
+ self.base_learners_ = [DecisionTreeRegressor(max_depth=max_depth)]
46
+ self.probabilities_ = [1.0]
47
+
48
+
49
+ model = TreeBoost(
50
+ num_iterations=100,
51
+ learning_rate=0.1,
52
+ mode="classification",
53
+ random_state=42,
54
+ )
55
+ model.fit(X_train, y_train)
56
+
57
+ print("Accuracy:", model.score(X_test, y_test))
58
+ model.evaluate(X_test, y_test)
59
+ ```
60
+
61
+ ---
62
+
63
+ ## API Reference
64
+
65
+ ### `HNBM`
66
+
67
+ | Parameter | Type | Default | Description |
68
+ |-----------|------|---------|-------------|
69
+ | `num_iterations` | `int` | `100` | Number of boosting rounds |
70
+ | `learning_rate` | `float` | `0.1` | Shrinkage per learner |
71
+ | `mode` | `str` | `"classification"` | `"classification"` or `"regression"` |
72
+ | `random_state` | `int` or `None` | `None` | Seed for learner selection |
73
+ | `verbose` | `bool` | `True` | Show tqdm progress bar |
74
+
75
+ **Methods**
76
+
77
+ | Method | Mode | Description |
78
+ |--------|------|-------------|
79
+ | `fit(X, y)` | both | Train the ensemble |
80
+ | `predict(X)` | both | Class labels (0/1) or continuous values |
81
+ | `predict_proba(X)` | classification | Probabilities, shape `(n_samples, 2)` |
82
+ | `decision_function(X)` | classification | Raw logits |
83
+ | `score(X, y)` | both | Accuracy or R² |
84
+ | `evaluate(X, y)` | both | Prints and returns log loss or RMSE |
85
+
86
+ **Subclass contract**: set `base_learners_` (list of unfitted sklearn regressors) and `probabilities_` (list summing to 1) before calling `fit`.
87
+
88
+ ### Loss functions
89
+
90
+ `hnbm.losses` provides `Logistic` (classification) and `MeanSquaredError` (regression), each with a `compute_derivatives(y, f)` method returning gradient and Hessian vectors.
91
+
92
+ ---
93
+
94
+ ## Docker
95
+
96
+ ```bash
97
+ docker build -t hnbm .
98
+ docker run --rm hnbm
99
+ ```
100
+
101
+ ---
102
+
103
+ ## Development
104
+
105
+ ```bash
106
+ git clone https://github.com/qiancapital-dev/hnbm.git
107
+ cd hnbm
108
+ pip install -r requirements.txt
109
+ pip install -e .
110
+ ```
111
+
112
+ ---
113
+
114
+ ## Related projects
115
+
116
+ - **[snapboost](https://github.com/QianCapital/snapboost)** — a concrete HNBM using decision trees and kernel ridge regressors
117
+
118
+ ---
119
+
120
+ ## License
121
+
122
+ MIT — See [LICENSE](LICENSE) for full text.
@@ -0,0 +1,5 @@
1
+ from .estimator import HNBM
2
+ from .losses import Logistic, MeanSquaredError
3
+
4
+ __all__ = ["HNBM", "Logistic", "MeanSquaredError"]
5
+ __version__ = "0.1.0"
@@ -0,0 +1,276 @@
1
+ import numpy as np
2
+ from tqdm import tqdm
3
+ from sklearn.base import BaseEstimator, clone
4
+ from sklearn.exceptions import NotFittedError
5
+ from sklearn.metrics import accuracy_score, mean_squared_error, log_loss, r2_score
6
+ from sklearn.utils.validation import check_is_fitted
7
+
8
+ from .losses import Logistic, MeanSquaredError
9
+
10
+
11
+ def _normalize_classification_labels(y):
12
+ """Convert 0/1 labels to -1/+1 for logistic loss."""
13
+ y = np.asarray(y, dtype=float).ravel()
14
+ if np.any(np.isnan(y)):
15
+ raise ValueError("Classification labels must not contain NaN values.")
16
+ unique = np.unique(y)
17
+ if np.array_equal(unique, [-1.0, 1.0]) or np.array_equal(unique, [-1.0]) or np.array_equal(unique, [1.0]):
18
+ return y
19
+ if np.all(np.isin(unique, [0.0, 1.0])):
20
+ return np.where(y == 0, -1.0, 1.0)
21
+ raise ValueError("Classification labels must be 0/1 or -1/+1.")
22
+
23
+
24
+ def _labels_for_log_loss(y):
25
+ """Convert labels to 0/1 for sklearn's log_loss."""
26
+ y = np.asarray(y, dtype=float).ravel()
27
+ if np.any(np.isnan(y)):
28
+ raise ValueError("Classification labels must not contain NaN values.")
29
+ unique = np.unique(y)
30
+ if np.all(np.isin(unique, [0.0, 1.0])):
31
+ return y
32
+ if np.all(np.isin(unique, [-1.0, 1.0])):
33
+ return np.where(y == -1, 0.0, 1.0)
34
+ raise ValueError("Classification labels must be 0/1 or -1/+1.")
35
+
36
+
37
+ def _validate_X(X):
38
+ """Validate and reshape feature matrix."""
39
+ X = np.asarray(X)
40
+ if X.ndim == 1:
41
+ X = X.reshape(1, -1)
42
+ elif X.ndim != 2:
43
+ raise ValueError(f"X must be a 2D array, got shape {X.shape}.")
44
+ if X.shape[0] == 0:
45
+ raise ValueError("X must contain at least one sample.")
46
+ return X
47
+
48
+
49
+ def _validate_X_y(X, y):
50
+ """Validate feature matrix and label vector shapes."""
51
+ X = _validate_X(X)
52
+ y = np.asarray(y)
53
+ if y.ndim == 2 and y.shape[1] == 1:
54
+ y = y.ravel()
55
+ elif y.ndim != 1:
56
+ raise ValueError(f"y must be a 1D array, got shape {y.shape}.")
57
+ if y.shape[0] == 0:
58
+ raise ValueError("y must contain at least one label.")
59
+ if X.shape[0] != y.shape[0]:
60
+ raise ValueError(
61
+ f"X and y have inconsistent lengths: {X.shape[0]} vs {y.shape[0]}."
62
+ )
63
+ return X, y
64
+
65
+
66
+ class HNBM(BaseEstimator):
67
+ """
68
+ Heterogeneous Newton Boosting Machine.
69
+
70
+ A gradient boosting framework that stochastically selects base learners
71
+ from a heterogeneous pool at each iteration. Subclass HNBM and configure
72
+ ``base_learners_`` and ``probabilities_`` before calling ``fit``.
73
+
74
+ Parameters
75
+ ----------
76
+ num_iterations : int, default=100
77
+ Number of boosting iterations.
78
+ learning_rate : float, default=0.1
79
+ Shrinkage applied to each learner's contribution.
80
+ mode : {'classification', 'regression'}, default='classification'
81
+ Training objective.
82
+ random_state : int or None, default=None
83
+ Random seed for base learner selection.
84
+ verbose : bool, default=True
85
+ Whether to show a progress bar during training.
86
+
87
+ Attributes
88
+ ----------
89
+ ensemble_ : list
90
+ Fitted base learners after training.
91
+ base_learners_ : list
92
+ Candidate base learners (must be set before ``fit``).
93
+ probabilities_ : list
94
+ Selection probabilities for each base learner (must be set before ``fit``).
95
+ """
96
+
97
+ def __init__(
98
+ self,
99
+ num_iterations=100,
100
+ learning_rate=0.1,
101
+ mode="classification",
102
+ random_state=None,
103
+ verbose=True,
104
+ ):
105
+ if mode not in ("classification", "regression"):
106
+ raise ValueError("Invalid mode: specify 'classification' or 'regression'.")
107
+ if num_iterations < 1:
108
+ raise ValueError(f"num_iterations must be >= 1, got {num_iterations}.")
109
+ if learning_rate <= 0:
110
+ raise ValueError(f"learning_rate must be > 0, got {learning_rate}.")
111
+
112
+ self.num_iterations = num_iterations
113
+ self.learning_rate = learning_rate
114
+ self.mode = mode
115
+ self.random_state = random_state
116
+ self.verbose = verbose
117
+ self.base_learners_ = []
118
+ self.probabilities_ = []
119
+ self.ensemble_ = []
120
+
121
+ def __sklearn_tags__(self):
122
+ tags = super().__sklearn_tags__()
123
+ tags.estimator_type = (
124
+ "classifier" if self.mode == "classification" else "regressor"
125
+ )
126
+ return tags
127
+
128
+ def _check_fitted(self):
129
+ check_is_fitted(self, "ensemble_")
130
+ if not self.ensemble_:
131
+ raise NotFittedError(
132
+ "This HNBM instance is not fitted yet. Call 'fit' with appropriate arguments."
133
+ )
134
+
135
+ def set_params(self, **params):
136
+ result = super().set_params(**params)
137
+ if params:
138
+ if "num_iterations" in params and self.num_iterations < 1:
139
+ raise ValueError(
140
+ f"num_iterations must be >= 1, got {self.num_iterations}."
141
+ )
142
+ if "learning_rate" in params and self.learning_rate <= 0:
143
+ raise ValueError(
144
+ f"learning_rate must be > 0, got {self.learning_rate}."
145
+ )
146
+ if "mode" in params and self.mode not in ("classification", "regression"):
147
+ raise ValueError(
148
+ "Invalid mode: specify 'classification' or 'regression'."
149
+ )
150
+ self.ensemble_ = []
151
+ return result
152
+
153
+ def fit(self, X, y):
154
+ """
155
+ Train the model.
156
+
157
+ Parameters
158
+ ----------
159
+ X : array-like of shape (n_samples, n_features)
160
+ Feature matrix.
161
+ y : array-like of shape (n_samples,)
162
+ Target values.
163
+
164
+ Returns
165
+ -------
166
+ self
167
+ """
168
+ if not self.base_learners_:
169
+ raise ValueError(
170
+ "No base learners configured. Subclass HNBM and set base_learners_ "
171
+ "and probabilities_ before calling fit."
172
+ )
173
+
174
+ X, y = _validate_X_y(X, y)
175
+ if self.mode == "classification":
176
+ y = _normalize_classification_labels(y)
177
+ self.classes_ = np.array([0, 1])
178
+ else:
179
+ y = np.asarray(y, dtype=float).ravel()
180
+
181
+ rng = np.random.default_rng(self.random_state)
182
+ z = np.zeros(X.shape[0])
183
+ self.ensemble_ = []
184
+ iterations = range(self.num_iterations)
185
+ if self.verbose:
186
+ iterations = tqdm(iterations, desc="Training")
187
+
188
+ for _ in iterations:
189
+ g, h = self.loss_.compute_derivatives(y, z)
190
+ idx = rng.choice(len(self.base_learners_), p=self.probabilities_)
191
+ base_learner = clone(self.base_learners_[idx])
192
+ base_learner.fit(X, -np.divide(g, h), sample_weight=h)
193
+ z += base_learner.predict(X) * self.learning_rate
194
+ self.ensemble_.append(base_learner)
195
+
196
+ return self
197
+
198
+ @property
199
+ def loss_(self):
200
+ return Logistic if self.mode == "classification" else MeanSquaredError
201
+
202
+ @property
203
+ def num_iterations_(self):
204
+ return self.num_iterations
205
+
206
+ @property
207
+ def learning_rate_(self):
208
+ return self.learning_rate
209
+
210
+ def _raw_predict(self, X):
211
+ """Return raw model output (logits for classification, values for regression)."""
212
+ self._check_fitted()
213
+ X = _validate_X(X)
214
+ preds = np.zeros(X.shape[0])
215
+ for learner in self.ensemble_:
216
+ preds += self.learning_rate * learner.predict(X)
217
+ return preds
218
+
219
+ def decision_function(self, X):
220
+ """Return classification logits."""
221
+ if self.mode != "classification":
222
+ raise ValueError("decision_function is only available in classification mode.")
223
+ return self._raw_predict(X)
224
+
225
+ def predict(self, X):
226
+ """
227
+ Predict using the model.
228
+
229
+ Classification returns 0/1 labels; regression returns continuous values.
230
+ """
231
+ if self.mode == "classification":
232
+ logits = self.decision_function(X)
233
+ return (logits >= 0).astype(int)
234
+ return self._raw_predict(X)
235
+
236
+ def predict_proba(self, X):
237
+ """
238
+ Predict class probabilities (classification mode only).
239
+
240
+ Returns
241
+ -------
242
+ ndarray of shape (n_samples, 2)
243
+ Probabilities ``[P(y=0), P(y=1)]``.
244
+ """
245
+ if self.mode != "classification":
246
+ raise ValueError("predict_proba is only available in classification mode.")
247
+ logits = self.decision_function(X)
248
+ prob_pos = 1.0 / (1.0 + np.exp(-logits))
249
+ return np.column_stack([1.0 - prob_pos, prob_pos])
250
+
251
+ def score(self, X, y):
252
+ """Return accuracy (classification) or R² (regression)."""
253
+ self._check_fitted()
254
+ _, y = _validate_X_y(X, y)
255
+ if self.mode == "classification":
256
+ y = _labels_for_log_loss(y)
257
+ return accuracy_score(y, self.predict(X))
258
+ y = np.asarray(y, dtype=float).ravel()
259
+ return r2_score(y, self.predict(X))
260
+
261
+ def evaluate(self, X, y):
262
+ """Print and return log loss (classification) or RMSE (regression)."""
263
+ self._check_fitted()
264
+ if self.mode == "classification":
265
+ _, y = _validate_X_y(X, y)
266
+ y = _labels_for_log_loss(y)
267
+ prob_pos = self.predict_proba(X)[:, 1]
268
+ loss = log_loss(y, prob_pos, labels=[0, 1])
269
+ print("Log Loss: %.4f" % loss)
270
+ else:
271
+ _, y = _validate_X_y(X, y)
272
+ y = np.asarray(y, dtype=float).ravel()
273
+ preds = self._raw_predict(X)
274
+ loss = np.sqrt(mean_squared_error(y, preds))
275
+ print("RMSE: %.4f" % loss)
276
+ return loss
@@ -0,0 +1,23 @@
1
+ import numpy as np
2
+
3
+
4
+ class MeanSquaredError:
5
+ """Mean Squared Error loss for regression."""
6
+
7
+ @staticmethod
8
+ def compute_derivatives(y, f):
9
+ g = 2 * (f - y)
10
+ h = 2.0 * np.ones(y.shape[0])
11
+ return g, h
12
+
13
+
14
+ class Logistic:
15
+ """Logistic loss for binary classification."""
16
+
17
+ @staticmethod
18
+ def compute_derivatives(y, f):
19
+ tmp = np.exp(-np.multiply(y, f))
20
+ tmp2 = np.divide(tmp, 1 + tmp)
21
+ g = -np.multiply(y, tmp2)
22
+ h = np.multiply(tmp2, 1.0 - tmp2)
23
+ return g, h
@@ -0,0 +1,143 @@
1
+ Metadata-Version: 2.4
2
+ Name: hnbm
3
+ Version: 0.1.0
4
+ Summary: Heterogeneous Newton Boosting Machine
5
+ Home-page: https://github.com/qiancapital-dev/hnbm
6
+ Author: Qian Capital
7
+ Author-email: Qian Capital <samson.qian@qiancapital.com>
8
+ License: MIT
9
+ Project-URL: Homepage, https://github.com/qiancapital-dev/hnbm
10
+ Keywords: boosting,gradient-boosting,hnbm,heterogeneous-newton
11
+ Requires-Python: >=3.8
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: numpy>=1.20
15
+ Requires-Dist: scikit-learn>=1.0
16
+ Requires-Dist: tqdm>=4.50
17
+ Dynamic: author
18
+ Dynamic: home-page
19
+ Dynamic: license-file
20
+ Dynamic: requires-python
21
+
22
+ # HNBM
23
+
24
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
25
+ [![scikit-learn](https://img.shields.io/badge/scikit--learn-compatible-blue.svg)](https://scikit-learn.org/)
26
+
27
+ **Heterogeneous Newton Boosting Machine (HNBM)** — a scikit-learn-compatible gradient boosting framework that stochastically mixes heterogeneous base learners at each iteration.
28
+
29
+ Unlike standard gradient boosting libraries that use a single learner type (typically decision trees), HNBM lets you define a pool of base learners with selection probabilities. At each boosting round, a learner is drawn from that pool and fit to the Newton step (gradient divided by Hessian, weighted by the Hessian).
30
+
31
+ This is the core framework behind [SnapBoost](https://github.com/qiancapital/snapboost), inspired by [SnapBoost: A Heterogeneous Boosting Machine](https://arxiv.org/abs/2006.09745) (Parnell et al., NeurIPS 2020).
32
+
33
+ ---
34
+
35
+ ## Installation
36
+
37
+ **From source** (recommended until PyPI release):
38
+
39
+ ```bash
40
+ git clone https://github.com/qiancapital-dev/hnbm.git
41
+ cd hnbm
42
+ pip install .
43
+ ```
44
+
45
+ **Requirements**: Python ≥ 3.8, NumPy, scikit-learn, tqdm.
46
+
47
+ ---
48
+
49
+ ## Quick Start
50
+
51
+ Subclass `HNBM` and configure your base learner pool before training:
52
+
53
+ ```python
54
+ from sklearn.datasets import load_breast_cancer
55
+ from sklearn.model_selection import train_test_split
56
+ from sklearn.tree import DecisionTreeRegressor
57
+ from hnbm import HNBM
58
+
59
+ X, y = load_breast_cancer(return_X_y=True)
60
+ X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
61
+
62
+
63
+ class TreeBoost(HNBM):
64
+ def __init__(self, max_depth=5, **kwargs):
65
+ super().__init__(**kwargs)
66
+ self.base_learners_ = [DecisionTreeRegressor(max_depth=max_depth)]
67
+ self.probabilities_ = [1.0]
68
+
69
+
70
+ model = TreeBoost(
71
+ num_iterations=100,
72
+ learning_rate=0.1,
73
+ mode="classification",
74
+ random_state=42,
75
+ )
76
+ model.fit(X_train, y_train)
77
+
78
+ print("Accuracy:", model.score(X_test, y_test))
79
+ model.evaluate(X_test, y_test)
80
+ ```
81
+
82
+ ---
83
+
84
+ ## API Reference
85
+
86
+ ### `HNBM`
87
+
88
+ | Parameter | Type | Default | Description |
89
+ |-----------|------|---------|-------------|
90
+ | `num_iterations` | `int` | `100` | Number of boosting rounds |
91
+ | `learning_rate` | `float` | `0.1` | Shrinkage per learner |
92
+ | `mode` | `str` | `"classification"` | `"classification"` or `"regression"` |
93
+ | `random_state` | `int` or `None` | `None` | Seed for learner selection |
94
+ | `verbose` | `bool` | `True` | Show tqdm progress bar |
95
+
96
+ **Methods**
97
+
98
+ | Method | Mode | Description |
99
+ |--------|------|-------------|
100
+ | `fit(X, y)` | both | Train the ensemble |
101
+ | `predict(X)` | both | Class labels (0/1) or continuous values |
102
+ | `predict_proba(X)` | classification | Probabilities, shape `(n_samples, 2)` |
103
+ | `decision_function(X)` | classification | Raw logits |
104
+ | `score(X, y)` | both | Accuracy or R² |
105
+ | `evaluate(X, y)` | both | Prints and returns log loss or RMSE |
106
+
107
+ **Subclass contract**: set `base_learners_` (list of unfitted sklearn regressors) and `probabilities_` (list summing to 1) before calling `fit`.
108
+
109
+ ### Loss functions
110
+
111
+ `hnbm.losses` provides `Logistic` (classification) and `MeanSquaredError` (regression), each with a `compute_derivatives(y, f)` method returning gradient and Hessian vectors.
112
+
113
+ ---
114
+
115
+ ## Docker
116
+
117
+ ```bash
118
+ docker build -t hnbm .
119
+ docker run --rm hnbm
120
+ ```
121
+
122
+ ---
123
+
124
+ ## Development
125
+
126
+ ```bash
127
+ git clone https://github.com/qiancapital-dev/hnbm.git
128
+ cd hnbm
129
+ pip install -r requirements.txt
130
+ pip install -e .
131
+ ```
132
+
133
+ ---
134
+
135
+ ## Related projects
136
+
137
+ - **[snapboost](https://github.com/QianCapital/snapboost)** — a concrete HNBM using decision trees and kernel ridge regressors
138
+
139
+ ---
140
+
141
+ ## License
142
+
143
+ MIT — See [LICENSE](LICENSE) for full text.
@@ -0,0 +1,16 @@
1
+ Dockerfile
2
+ LICENSE
3
+ MANIFEST.in
4
+ README.md
5
+ pyproject.toml
6
+ requirements.txt
7
+ setup.cfg
8
+ setup.py
9
+ hnbm/__init__.py
10
+ hnbm/estimator.py
11
+ hnbm/losses.py
12
+ hnbm.egg-info/PKG-INFO
13
+ hnbm.egg-info/SOURCES.txt
14
+ hnbm.egg-info/dependency_links.txt
15
+ hnbm.egg-info/requires.txt
16
+ hnbm.egg-info/top_level.txt
@@ -0,0 +1,3 @@
1
+ numpy>=1.20
2
+ scikit-learn>=1.0
3
+ tqdm>=4.50
@@ -0,0 +1 @@
1
+ hnbm
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "hnbm"
7
+ version = "0.1.0"
8
+ description = "Heterogeneous Newton Boosting Machine"
9
+ readme = "README.md"
10
+ license = {text = "MIT"}
11
+ requires-python = ">=3.8"
12
+ authors = [{name = "Qian Capital", email = "samson.qian@qiancapital.com"}]
13
+ keywords = ["boosting", "gradient-boosting", "hnbm", "heterogeneous-newton"]
14
+ dependencies = [
15
+ "numpy>=1.20",
16
+ "scikit-learn>=1.0",
17
+ "tqdm>=4.50",
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://github.com/qiancapital-dev/hnbm"
22
+
23
+ [tool.setuptools.packages.find]
24
+ where = ["."]
25
+ include = ["hnbm*"]
@@ -0,0 +1,3 @@
1
+ numpy>=1.20
2
+ scikit-learn>=1.0
3
+ tqdm>=4.50
hnbm-0.1.0/setup.cfg ADDED
@@ -0,0 +1,9 @@
1
+ [metadata]
2
+ description_file = README.md
3
+ requirements-file = requirements.txt
4
+ docker-file = Dockerfile
5
+
6
+ [egg_info]
7
+ tag_build =
8
+ tag_date = 0
9
+
hnbm-0.1.0/setup.py ADDED
@@ -0,0 +1,36 @@
1
+ from setuptools import setup
2
+ import pathlib
3
+
4
+ HERE = pathlib.Path(__file__).parent
5
+ README = (HERE / "README.md").read_text()
6
+
7
+
8
+ def _parse_requirements(file_path):
9
+ with open(file_path) as f:
10
+ lines = f.read().splitlines()
11
+ reqs = []
12
+ for line in lines:
13
+ line = line.strip()
14
+ if not line or line.startswith("#"):
15
+ continue
16
+ if line.startswith("pip") or line.startswith("setuptools"):
17
+ continue
18
+ reqs.append(line)
19
+ return reqs
20
+
21
+
22
+ setup(
23
+ name="hnbm",
24
+ version="0.1.0",
25
+ author="Qian Capital",
26
+ author_email="samson.qian@qiancapital.com",
27
+ packages=["hnbm"],
28
+ url="https://github.com/qiancapital-dev/hnbm",
29
+ license="MIT",
30
+ description="Heterogeneous Newton Boosting Machine",
31
+ long_description=README,
32
+ long_description_content_type="text/markdown",
33
+ install_requires=_parse_requirements("requirements.txt"),
34
+ python_requires=">=3.8",
35
+ keywords="boosting gradient-boosting hnbm heterogeneous-newton",
36
+ )