forestgeom 0.1.0__py3-none-any.whl

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.
forestgeom/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .proximity import ForestProximity
2
+
3
+ __all__ = ["ForestProximity"]
@@ -0,0 +1,88 @@
1
+ from sklearn.ensemble import (
2
+ RandomForestClassifier,
3
+ RandomForestRegressor,
4
+ ExtraTreesClassifier,
5
+ ExtraTreesRegressor,
6
+ GradientBoostingClassifier,
7
+ GradientBoostingRegressor,
8
+ )
9
+
10
+ from .rf_et import RFETAdapter
11
+ from .gbt import GBTAdapter
12
+
13
+
14
+ try:
15
+ from lightgbm import LGBMClassifier, LGBMRegressor
16
+ from .lgbm import LightGBMAdapter
17
+
18
+ _LGBM_CLASSES = (LGBMClassifier, LGBMRegressor)
19
+ except ImportError:
20
+ LightGBMAdapter = None
21
+ _LGBM_CLASSES = ()
22
+
23
+
24
+ try:
25
+ from xgboost import XGBClassifier, XGBRegressor
26
+ from .xgb import XGBoostAdapter
27
+
28
+ _XGB_CLASSES = (XGBClassifier, XGBRegressor)
29
+ except ImportError:
30
+ XGBoostAdapter = None
31
+ _XGB_CLASSES = ()
32
+
33
+
34
+ _RF_ET_CLASSES = (
35
+ RandomForestClassifier,
36
+ RandomForestRegressor,
37
+ ExtraTreesClassifier,
38
+ ExtraTreesRegressor,
39
+ )
40
+
41
+ _GBT_CLASSES = (
42
+ GradientBoostingClassifier,
43
+ GradientBoostingRegressor,
44
+ )
45
+
46
+
47
+ def make_adapter(estimator, weight_scheme=None):
48
+ """
49
+ Return the correct ensemble adapter for a supported estimator.
50
+
51
+ If weight_scheme is provided, validate that the selected adapter supports
52
+ this forest / weight_scheme combination.
53
+ """
54
+ if isinstance(estimator, _RF_ET_CLASSES):
55
+ adapter = RFETAdapter(estimator)
56
+
57
+ elif isinstance(estimator, _GBT_CLASSES):
58
+ adapter = GBTAdapter(estimator)
59
+
60
+ elif _LGBM_CLASSES and isinstance(estimator, _LGBM_CLASSES):
61
+ adapter = LightGBMAdapter(estimator)
62
+
63
+ elif _XGB_CLASSES and isinstance(estimator, _XGB_CLASSES):
64
+ adapter = XGBoostAdapter(estimator)
65
+
66
+ else:
67
+ supported = [
68
+ "RandomForestClassifier/Regressor",
69
+ "ExtraTreesClassifier/Regressor",
70
+ "GradientBoostingClassifier/Regressor",
71
+ ]
72
+
73
+ if _LGBM_CLASSES:
74
+ supported.append("LGBMClassifier/Regressor")
75
+
76
+ if _XGB_CLASSES:
77
+ supported.append("XGBClassifier/Regressor")
78
+
79
+ raise TypeError(
80
+ "Unsupported forest estimator. Expected one of: "
81
+ + ", ".join(supported)
82
+ + "."
83
+ )
84
+
85
+ if weight_scheme is not None:
86
+ adapter.validate_weight_scheme(weight_scheme)
87
+
88
+ return adapter
@@ -0,0 +1,92 @@
1
+ from sklearn.base import clone
2
+
3
+ class EnsembleAdapter:
4
+ """
5
+ Base adapter interface used to abstract away ensemble-specific internals.
6
+
7
+ Each adapter wraps a fitted estimator instance and exposes a
8
+ unified interface for:
9
+ - retrieving leaf indices
10
+ - retrieving per-tree node counts
11
+ - retrieving OOB masks / in-bag counts when available
12
+ - retrieving tree-specific weights when relevant (e.g. GBT)
13
+
14
+ Each adapter wraps an estimator instance and exposes a unified interface
15
+ for leaf-based forest kernel construction.
16
+
17
+
18
+ Notes
19
+ -----
20
+ The adapter does not own the estimator. It simply delegates to it.
21
+ """
22
+
23
+
24
+
25
+ supported_weight_schemes = {"uniform", "kerf"}
26
+
27
+ def __init__(self, estimator, weight_scheme=None):
28
+ self.estimator = estimator
29
+
30
+ if weight_scheme is not None:
31
+ self.validate_weight_scheme(weight_scheme)
32
+
33
+ def validate_weight_scheme(self, weight_scheme):
34
+ """
35
+ Validate whether this adapter supports the requested weight scheme.
36
+ """
37
+ if weight_scheme not in self.supported_weight_schemes:
38
+ raise ValueError(
39
+ f"{type(self).__name__} does not support "
40
+ f"weight_scheme='{weight_scheme}'. "
41
+ f"Supported schemes are {sorted(self.supported_weight_schemes)}."
42
+ )
43
+
44
+ return self
45
+
46
+ def fit(self, X, y, **fit_kwargs):
47
+ """
48
+ Clone and fit the wrapped estimator.
49
+
50
+ Additional keyword arguments are passed to estimator.fit(...),
51
+ e.g. sample_weight.
52
+ """
53
+ self.estimator = clone(self.estimator)
54
+ self.estimator.fit(X, y, **fit_kwargs)
55
+ return self
56
+
57
+ def get_leaf_matrix(self, X):
58
+ """
59
+ Return matrix of leaf ids of shape (N, T).
60
+ """
61
+ raise NotImplementedError
62
+
63
+ def get_n_nodes_per_tree(self):
64
+ """
65
+ Return number of nodes per tree, used to offset local node ids into
66
+ global ids.
67
+ """
68
+ raise NotImplementedError
69
+
70
+ def get_oob_mask(self, X_train=None):
71
+ """
72
+ Return OOB mask matrix of shape (N_train, T), where entry (i,t)=1 if
73
+ sample i is OOB for tree t.
74
+ """
75
+ raise NotImplementedError
76
+
77
+ def get_in_bag_counts(self, X_train=None):
78
+ """
79
+ Return in-bag multiplicity matrix of shape (N_train, T), where entry
80
+ (i,t) is the number of times sample i was drawn for tree t.
81
+ """
82
+ raise NotImplementedError
83
+
84
+ def get_tree_weights(self, X_ref):
85
+ """
86
+ Return per-tree weights when the proximity requires them.
87
+ Only relevant for some ensembles such as Gradient Boosting.
88
+ """
89
+ raise NotImplementedError
90
+
91
+ def __getattr__(self, name):
92
+ return getattr(self.estimator, name)
@@ -0,0 +1,134 @@
1
+ import numpy as np
2
+ from .base import EnsembleAdapter
3
+
4
+
5
+ class GBTAdapter(EnsembleAdapter):
6
+ """
7
+ Adapter for sklearn GradientBoosting estimators.
8
+ """
9
+
10
+ supported_weight_schemes = {"uniform", "kerf", "boosted"}
11
+
12
+ def _get_tree_list(self):
13
+ """
14
+ Flatten sklearn GBT estimators_ into a single list of trees.
15
+
16
+ - Regression: estimators_.shape = (T, 1)
17
+ - Binary classification: estimators_.shape = (T, 1)
18
+ - Multiclass classification: estimators_.shape = (T, K)
19
+ """
20
+ return [tree for tree in self.estimator.estimators_.ravel()]
21
+
22
+ def get_leaf_matrix(self, X):
23
+ """
24
+ Apply every tree in the flattened GBT ensemble and return a leaf matrix
25
+ of shape (N, T_total).
26
+ """
27
+ tree_list = self._get_tree_list()
28
+ return np.column_stack([tree.apply(X) for tree in tree_list]).astype(np.int32)
29
+
30
+ def _predict_tree_outputs(self, X_ref):
31
+ """
32
+ Helper to get shrunken tree outputs (learning_rate * tree_output).
33
+ Used to calculate variance for weights.
34
+ """
35
+ leaf_matrix = self.get_leaf_matrix(X_ref)
36
+ tree_list = self._get_tree_list()
37
+ lr = np.float32(self.estimator.learning_rate)
38
+
39
+ n_samples, n_trees = leaf_matrix.shape
40
+ outputs = np.zeros((n_samples, n_trees), dtype=np.float32)
41
+
42
+ for t, tree in enumerate(tree_list):
43
+ # tree.tree_.value has shape (n_nodes, 1, 1)
44
+ # We map the leaf indices to their corresponding values
45
+ leaf_values = tree.tree_.value.reshape(-1).astype(np.float32)
46
+ outputs[:, t] = lr * leaf_values[leaf_matrix[:, t]]
47
+
48
+ return outputs
49
+
50
+ def get_n_nodes_per_tree(self):
51
+ """
52
+ Return number of nodes per tree.
53
+ """
54
+ tree_list = self._get_tree_list()
55
+ return [tree.tree_.node_count for tree in tree_list]
56
+
57
+ def get_tree_weights(self, X_ref):
58
+ """
59
+ Compute normalized tree-specific weights for boosted-tree proximities.
60
+
61
+ Returns
62
+ -------
63
+ weights : np.ndarray of shape (T_total,), dtype np.float32
64
+ One nonnegative weight per tree in the flattened GradientBoosting
65
+ ensemble.
66
+
67
+ The entries are normalized to sum to one. Therefore, ``weights[t]``
68
+ gives the relative contribution of flattened tree ``t`` to the
69
+ boosted-tree proximity.
70
+
71
+ Here, ``T_total`` is the number of trees after flattening
72
+ ``estimator.estimators_``:
73
+
74
+ - regression: ``T_total = n_estimators``
75
+ - binary classification: ``T_total = n_estimators``
76
+ - multiclass classification:
77
+ ``T_total = n_estimators * n_classes``
78
+
79
+ Notes
80
+ -----
81
+ Gradient Boosting models are additive ensembles of the form
82
+
83
+ F(x) = sum_t h_t(x),
84
+
85
+ where ``h_t(x)`` denotes the prediction contribution of tree ``t`` for
86
+ sample ``x``. For sklearn GradientBoosting estimators,
87
+
88
+ h_t(x) = learning_rate * f_t(x),
89
+
90
+ where ``f_t(x)`` is the raw prediction of tree ``t``.
91
+
92
+ In this implementation, the tree contributions are obtained directly from
93
+ the fitted leaf values and the leaf assignments of ``X_ref``.
94
+
95
+ Following the boosted-tree proximity definition of Tan et al. (2020),
96
+ each tree is weighted according to the empirical variance of its
97
+ contribution over the reference set:
98
+
99
+ w_t ∝ Var({h_t(s) : s in X_ref}).
100
+
101
+ The intuition is that trees whose outputs vary more across the dataset
102
+ carry more geometric and predictive information, and should therefore
103
+ contribute more strongly to the proximity. Conversely, trees whose
104
+ predictions are nearly constant over ``X_ref`` contribute little to
105
+ distinguishing samples and receive smaller weights.
106
+
107
+ This differs from Random Forests, where trees are approximately
108
+ exchangeable and are therefore typically weighted uniformly. In boosting,
109
+ trees are built sequentially and can have very different importance,
110
+ making variance-based weighting more natural.
111
+
112
+ If all empirical variances are numerically zero, the method falls back to
113
+ uniform weights.
114
+
115
+ For multiclass GradientBoosting, sklearn stores one tree per class at each
116
+ boosting stage. The returned weights are therefore per flattened
117
+ class-specific tree, not per boosting stage.
118
+ """
119
+ # contribs shape: (n_samples, n_trees)
120
+ contribs = self._predict_tree_outputs(X_ref)
121
+
122
+ if contribs.shape[1] == 0:
123
+ raise RuntimeError("No trees found in fitted GradientBoosting model.")
124
+
125
+ # Uniform calculation using np.var (Empirical variance)
126
+ weights = np.var(contribs, axis=0).astype(np.float32)
127
+
128
+ total_weight = weights.sum()
129
+ if total_weight <= 1e-12:
130
+ weights[:] = 1.0 / len(weights)
131
+ else:
132
+ weights /= total_weight
133
+
134
+ return weights.astype(np.float32)
@@ -0,0 +1,178 @@
1
+ import numpy as np
2
+ from .base import EnsembleAdapter
3
+
4
+ class LightGBMAdapter(EnsembleAdapter):
5
+ """
6
+ Adapter for LightGBM sklearn-style estimators.
7
+
8
+ Notes
9
+ -----
10
+ LightGBM uses leaf-wise tree growth by default. This can produce more
11
+ specialized leaves than depth-wise/tree-level methods, which may reduce
12
+ the number of shared-leaf collisions and yield sparser forest kernels.
13
+ """
14
+
15
+ supported_weight_schemes = {"uniform", "kerf", "boosted"}
16
+
17
+ def _get_booster(self):
18
+ if not hasattr(self.estimator, "booster_"):
19
+ raise ValueError(
20
+ "LightGBM estimator must be fitted before using LightGBMAdapter."
21
+ )
22
+ return self.estimator.booster_
23
+
24
+ def get_leaf_matrix(self, X):
25
+ """
26
+ Apply every LightGBM tree and return a leaf matrix of shape
27
+ (n_samples, n_trees_total).
28
+ """
29
+ booster = self._get_booster()
30
+ leaf_matrix = booster.predict(X, pred_leaf=True)
31
+
32
+ leaf_matrix = np.asarray(leaf_matrix, dtype=np.int32)
33
+ if leaf_matrix.ndim == 1:
34
+ leaf_matrix = leaf_matrix.reshape(-1, 1)
35
+
36
+ return leaf_matrix
37
+
38
+ def _get_leaf_value_maps(self):
39
+ booster = self._get_booster()
40
+ tree_info = booster.dump_model()["tree_info"]
41
+
42
+ maps = []
43
+
44
+ def collect_leaves(node, out):
45
+ if "leaf_index" in node:
46
+ out[int(node["leaf_index"])] = float(node["leaf_value"])
47
+ return
48
+
49
+ if "left_child" in node:
50
+ collect_leaves(node["left_child"], out)
51
+
52
+ if "right_child" in node:
53
+ collect_leaves(node["right_child"], out)
54
+
55
+ for tree in tree_info:
56
+ out = {}
57
+ collect_leaves(tree["tree_structure"], out)
58
+ maps.append(out)
59
+
60
+ return maps
61
+
62
+ def _predict_tree_outputs(self, X_ref):
63
+ """
64
+ Return per-tree fitted contributions of shape
65
+ (n_samples, n_trees_total).
66
+
67
+ LightGBM leaf values from ``booster.dump_model()`` already include the
68
+ learning-rate shrinkage used by the fitted booster, so no additional
69
+ multiplication by ``learning_rate`` is applied here.
70
+ """
71
+ leaf_matrix = self.get_leaf_matrix(X_ref)
72
+ leaf_value_maps = self._get_leaf_value_maps()
73
+
74
+ n_samples, n_trees = leaf_matrix.shape
75
+ outputs = np.zeros((n_samples, n_trees), dtype=np.float32)
76
+
77
+ for t in range(n_trees):
78
+ leaf_map = leaf_value_maps[t]
79
+ # Use .get(idx, 0.0) to safely handle any empty/stub trees
80
+ outputs[:, t] = np.array(
81
+ [leaf_map.get(int(leaf_idx), 0.0) for leaf_idx in leaf_matrix[:, t]],
82
+ dtype=np.float32,
83
+ )
84
+
85
+ return outputs
86
+
87
+ def get_n_nodes_per_tree(self):
88
+ """
89
+ Return total node counts for each LightGBM tree using the model dump.
90
+ """
91
+ booster = self._get_booster()
92
+ tree_info = booster.dump_model()["tree_info"]
93
+
94
+ def count_nodes(node):
95
+ return (
96
+ 1
97
+ + sum(
98
+ count_nodes(child)
99
+ for child in (node.get("left_child"), node.get("right_child"))
100
+ if child is not None
101
+ )
102
+ )
103
+
104
+ return [
105
+ count_nodes(tree["tree_structure"])
106
+ for tree in tree_info
107
+ ]
108
+
109
+ def get_tree_weights(self, X_ref):
110
+ """
111
+ Compute normalized tree-specific weights for boosted-tree proximities.
112
+
113
+ Returns
114
+ -------
115
+ weights : np.ndarray of shape (n_trees_total,), dtype np.float32
116
+ One nonnegative weight per LightGBM tree.
117
+
118
+ The entries are normalized to sum to one. Therefore, ``weights[t]``
119
+ gives the relative contribution of tree ``t`` to the boosted-tree
120
+ proximity.
121
+
122
+ Here, ``n_trees_total`` is the number of trees returned by the fitted
123
+ LightGBM booster. For multiclass models, LightGBM stores one tree per
124
+ class at each boosting iteration, so
125
+
126
+ ``n_trees_total = n_estimators * n_classes``.
127
+
128
+ Notes
129
+ -----
130
+ Boosted trees are additive ensembles of the form
131
+
132
+ F(x) = sum_t h_t(x),
133
+
134
+ where ``h_t(x)`` denotes the contribution of tree ``t`` to the model score
135
+ for sample ``x``.
136
+
137
+ In this implementation, ``h_t(x)`` is obtained from the fitted LightGBM
138
+ leaf values reached by ``x``. These leaf values are read directly from the
139
+ dumped booster model and correspond to the per-tree contribution used by
140
+ the fitted LightGBM ensemble.
141
+
142
+ Following the boosted-tree proximity definition of Tan et al. (2020),
143
+ each tree is weighted according to the empirical variance of its
144
+ contribution over the reference set:
145
+
146
+ w_t ∝ Var({h_t(s) : s in X_ref}).
147
+
148
+ The intuition is that trees whose outputs vary more across the dataset
149
+ carry more geometric and predictive information, and should therefore
150
+ contribute more strongly to the proximity. Conversely, trees whose
151
+ predictions are nearly constant over ``X_ref`` contribute little to
152
+ distinguishing samples and receive smaller weights.
153
+
154
+ This differs from Random Forests, where trees are approximately
155
+ exchangeable and are therefore typically weighted uniformly. In boosting,
156
+ trees are built sequentially and can have very different importance,
157
+ making variance-based weighting more natural.
158
+
159
+ If all empirical variances are numerically zero, the method falls back to
160
+ uniform weights.
161
+
162
+ For multiclass LightGBM models, the returned weights are per flattened
163
+ class-specific tree, not per boosting stage.
164
+ """
165
+ contribs = self._predict_tree_outputs(X_ref)
166
+
167
+ if contribs.shape[1] == 0:
168
+ raise RuntimeError("No trees found in fitted LightGBM model.")
169
+
170
+ weights = np.var(contribs, axis=0).astype(np.float32)
171
+
172
+ total_weight = weights.sum()
173
+ if total_weight <= 1e-12:
174
+ weights[:] = 1.0 / len(weights)
175
+ else:
176
+ weights /= total_weight
177
+
178
+ return weights.astype(np.float32)
@@ -0,0 +1,81 @@
1
+ import numpy as np
2
+ from sklearn.ensemble._forest import _generate_unsampled_indices
3
+ from sklearn.ensemble._forest import _generate_sample_indices
4
+ from .base import EnsembleAdapter
5
+
6
+
7
+ class RFETAdapter(EnsembleAdapter):
8
+ """
9
+ Adapter for sklearn RandomForest / ExtraTrees ensembles.
10
+ """
11
+
12
+ supported_weight_schemes = {"uniform", "kerf", "oob", "gap"}
13
+
14
+ def validate_weight_scheme(self, weight_scheme):
15
+ super().validate_weight_scheme(weight_scheme)
16
+
17
+ if weight_scheme in {"oob", "gap"} and not getattr(self.estimator, "bootstrap", False):
18
+ raise ValueError(
19
+ f"weight_scheme='{weight_scheme}' requires bootstrap=True "
20
+ f"for {type(self.estimator).__name__}."
21
+ )
22
+
23
+ return self
24
+
25
+ def _extract_tree(self, estimator):
26
+ return estimator
27
+
28
+ def get_leaf_matrix(self, X):
29
+ """
30
+ Return matrix of leaf ids of shape (N, T).
31
+ """
32
+ return self.estimator.apply(X).astype(np.int32)
33
+
34
+ def get_n_nodes_per_tree(self):
35
+ """
36
+ Return number of nodes per tree.
37
+ """
38
+ return [self._extract_tree(est).tree_.node_count for est in self.estimator.estimators_]
39
+
40
+ def get_oob_mask(self, X_train=None):
41
+ """
42
+ Returns OOB mask matrix of shape (N_train, T), where entry (i,t)=1 if
43
+ sample i is OOB for tree t.
44
+ """
45
+ if not getattr(self.estimator, "bootstrap", False):
46
+ raise ValueError("get_oob_mask requires bootstrap=True.")
47
+ n_samples = X_train.shape[0]
48
+ n_trees = len(self.estimator.estimators_)
49
+ oob_mask = np.zeros((n_samples, n_trees), dtype=np.int8)
50
+
51
+ for t, tree in enumerate(self.estimator.estimators_):
52
+ unsampled = _generate_unsampled_indices(
53
+ tree.random_state,
54
+ n_samples,
55
+ n_samples
56
+ )
57
+ oob_mask[unsampled, t] = 1
58
+
59
+ return oob_mask
60
+
61
+ def get_in_bag_counts(self, X_train=None):
62
+ """
63
+ Returns in-bag multiplicity matrix of shape (N_train, T), where entry
64
+ (i,t) is the number of times sample i was drawn for tree t.
65
+ """
66
+ if not getattr(self.estimator, "bootstrap", False):
67
+ raise ValueError("get_in_bag_counts requires bootstrap=True.")
68
+ n_samples = X_train.shape[0]
69
+ n_trees = len(self.estimator.estimators_)
70
+ counts = np.zeros((n_samples, n_trees), dtype=np.int32)
71
+
72
+ for t, tree in enumerate(self.estimator.estimators_):
73
+ sampled = _generate_sample_indices(
74
+ tree.random_state,
75
+ n_samples,
76
+ n_samples
77
+ )
78
+ binc = np.bincount(sampled, minlength=n_samples)
79
+ counts[:, t] = binc
80
+
81
+ return counts.astype(np.float32)