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
|
- from copy import deepcopy
- from typing import List
- import numpy as np
- from sklearn import datasets
- from sklearn.base import BaseEstimator
- from sklearn.metrics import r2_score
- from sklearn.model_selection import cross_val_score
- from sklearn.model_selection import train_test_split
- from sklearn.tree import DecisionTreeRegressor
- from imodels.util import checks
- class HSFIGS:
- def __init__(self, estimator_: BaseEstimator, reg_param: float = 1, shrinkage_scheme_: str = 'node_based'):
- """HSTree (Tree with hierarchical shrinkage applied).
- Hierarchical shinkage is an extremely fast post-hoc regularization method which works on any decision tree (or tree-based ensemble, such as Random Forest).
- It does not modify the tree structure, and instead regularizes the tree by shrinking the prediction over each node towards the sample means of its ancestors (using a single regularization parameter).
- Experiments over a wide variety of datasets show that hierarchical shrinkage substantially increases the predictive performance of individual decision trees and decision-tree ensembles.
- https://arxiv.org/abs/2202.00858
- Params
- ------
- estimator_: sklearn tree or tree ensemble model (e.g. RandomForest or GradientBoosting)
- reg_param: float
- Higher is more regularization (can be arbitrarily large, should not be < 0)
- shrinkage_scheme: str
- Experimental: Used to experiment with different forms of shrinkage. options are:
- (i) node_based shrinks based on number of samples in parent node
- (ii) leaf_based only shrinks leaf nodes based on number of leaf samples
- (iii) constant shrinks every node by a constant lambda
- """
- super().__init__()
- self.reg_param = reg_param
- # print('est', estimator_)
- self.estimator_ = estimator_
- self.shrinkage_scheme_ = shrinkage_scheme_
- self._init_prediction_task()
- if checks.check_is_fitted(self.estimator_):
- self._shrink()
- def __init__prediction_task(self):
- self.prediction_task = 'regression'
- def get_params(self, deep=True):
- if deep:
- return deepcopy({'reg_param': self.reg_param, 'estimator_': self.estimator_,
- # 'prediction_task': self.prediction_task,
- 'shrinkage_scheme_': self.shrinkage_scheme_})
- return {'reg_param': self.reg_param, 'estimator_': self.estimator_,
- # 'prediction_task': self.prediction_task,
- 'shrinkage_scheme_': self.shrinkage_scheme_}
- def fit(self, *args, **kwargs):
- self.estimator_.fit(*args, **kwargs)
- self._shrink()
- def _shrink(self, reg_param):
- for tree in self.trees_:
- tree.shrink(reg_param)
- def predict(self, *args, **kwargs):
- return self.estimator_.predict(*args, **kwargs)
- def predict_proba(self, *args, **kwargs):
- if hasattr(self.estimator_, 'predict_proba'):
- return self.estimator_.predict_proba(*args, **kwargs)
- else:
- return NotImplemented
- def score(self, *args, **kwargs):
- if hasattr(self.estimator_, 'score'):
- return self.estimator_.score(*args, **kwargs)
- else:
- return NotImplemented
- class HSFIGSRegressor(HSFIGS):
- def _init_prediction_task(self):
- self.prediction_task = 'regression'
- class HSFIGSClassifier(HSFIGS):
- def _init_prediction_task(self):
- self.prediction_task = 'classification'
- class HSFIGSClassifierCV(HSFIGSClassifier):
- def __init__(self, estimator_: BaseEstimator,
- reg_param_list: List[float] = [0.1, 1, 10, 50, 100, 500], shrinkage_scheme_: str = 'node_based',
- cv: int = 3, scoring=None, *args, **kwargs):
- """Note: args, kwargs are not used but left so that imodels-experiments can still pass redundant args.
- Cross-validation is used to select the best regularization parameter for hierarchical shrinkage.
- """
- super().__init__(estimator_, reg_param=None)
- self.reg_param_list = np.array(reg_param_list)
- self.cv = cv
- self.scoring = scoring
- self.shrinkage_scheme_ = shrinkage_scheme_
- # print('estimator', self.estimator_,
- # 'checks.check_is_fitted(estimator)', checks.check_is_fitted(self.estimator_))
- # if checks.check_is_fitted(self.estimator_):
- # raise Warning('Passed an already fitted estimator,'
- # 'but shrinking not applied until fit method is called.')
- def fit(self, X, y, *args, **kwargs):
- self.scores_ = []
- for reg_param in self.reg_param_list:
- est = HSFIGSClassifier(deepcopy(self.estimator_), reg_param)
- cv_scores = cross_val_score(est, X, y, cv=self.cv, scoring=self.scoring)
- self.scores_.append(np.mean(cv_scores))
- self.reg_param = self.reg_param_list[np.argmax(self.scores_)]
- super().fit(X=X, y=y)
- class HSFIGSRegressorCV(HSFIGSRegressor):
- def __init__(self, estimator_: BaseEstimator,
- reg_param_list: List[float] = [0.1, 1, 10, 50, 100, 500],
- shrinkage_scheme_: str = 'node_based',
- cv: int = 3, scoring=None, *args, **kwargs):
- """Note: args, kwargs are not used but left so that imodels-experiments can still pass redundant args.
- Cross-validation is used to select the best regularization parameter for hierarchical shrinkage.
- """
- super().__init__(estimator_, reg_param=None)
- self.reg_param_list = np.array(reg_param_list)
- self.cv = cv
- self.scoring = scoring
- self.shrinkage_scheme_ = shrinkage_scheme_
- # print('estimator', self.estimator_,
- # 'checks.check_is_fitted(estimator)', checks.check_is_fitted(self.estimator_))
- # if checks.check_is_fitted(self.estimator_):
- # raise Warning('Passed an already fitted estimator,'
- # 'but shrinking not applied until fit method is called.')
- def fit(self, X, y):
- self.scores_ = []
- for reg_param in self.reg_param_list:
- est = HSFIGSRegressor(deepcopy(self.estimator_), reg_param)
- cv_scores = cross_val_score(est, X, y, cv=self.cv, scoring=self.scoring)
- self.scores_.append(np.mean(cv_scores))
- self.reg_param = self.reg_param_list[np.argmax(self.scores_)]
- super().fit(X=X, y=y)
- if __name__ == '__main__':
- np.random.seed(15)
- # X, y = datasets.fetch_california_housing(return_X_y=True) # regression
- # X, y = datasets.load_breast_cancer(return_X_y=True) # binary classification
- X, y = datasets.load_diabetes(return_X_y=True) # regression
- # X = np.random.randn(500, 10)
- # y = (X[:, 0] > 0).astype(float) + (X[:, 1] > 1).astype(float)
- X_train, X_test, y_train, y_test = train_test_split(
- X, y, test_size=0.33, random_state=10
- )
- print('X.shape', X.shape)
- print('ys', np.unique(y_train))
- # m = HSTree(estimator_=DecisionTreeClassifier(), reg_param=0.1)
- # m = DecisionTreeClassifier(max_leaf_nodes = 20,random_state=1, max_features=None)
- m = DecisionTreeRegressor(random_state=42, max_leaf_nodes=20)
- # print('best alpha', m.reg_param)
- m.fit(X_train, y_train)
- # m.predict_proba(X_train) # just run this
- print('score', r2_score(y_test, m.predict(X_test)))
- print('running again....')
- # x = DecisionTreeRegressor(random_state = 42, ccp_alpha = 0.3)
- # x.fit(X_train,y_train)
- # m = HSTree(estimator_=DecisionTreeRegressor(random_state=42, max_features=None), reg_param=10)
- # m = HSTree(estimator_=DecisionTreeClassifier(random_state=42, max_features=None), reg_param=0)
- m = HSFIGSClassifierCV(estimator_=DecisionTreeRegressor(max_leaf_nodes=10, random_state=1),
- shrinkage_scheme_='node_based',
- reg_param_list=[0.1, 1, 2, 5, 10, 25, 50, 100, 500])
- # m = ShrunkTreeCV(estimator_=DecisionTreeClassifier())
- # m = HSTreeClassifier(estimator_ = GradientBoostingClassifier(random_state = 10),reg_param = 5)
- m.fit(X_train, y_train)
- print('best alpha', m.reg_param)
- # m.predict_proba(X_train) # just run this
- # print('score', m.score(X_test, y_test))
- print('score', r2_score(y_test, m.predict(X_test)))
|