Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

figs_shrinkage.py 8.2 KB

You have to be logged in to leave a comment. Sign In
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
  1. from copy import deepcopy
  2. from typing import List
  3. import numpy as np
  4. from sklearn import datasets
  5. from sklearn.base import BaseEstimator
  6. from sklearn.metrics import r2_score
  7. from sklearn.model_selection import cross_val_score
  8. from sklearn.model_selection import train_test_split
  9. from sklearn.tree import DecisionTreeRegressor
  10. from imodels.util import checks
  11. class HSFIGS:
  12. def __init__(self, estimator_: BaseEstimator, reg_param: float = 1, shrinkage_scheme_: str = 'node_based'):
  13. """HSTree (Tree with hierarchical shrinkage applied).
  14. Hierarchical shinkage is an extremely fast post-hoc regularization method which works on any decision tree (or tree-based ensemble, such as Random Forest).
  15. 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).
  16. Experiments over a wide variety of datasets show that hierarchical shrinkage substantially increases the predictive performance of individual decision trees and decision-tree ensembles.
  17. https://arxiv.org/abs/2202.00858
  18. Params
  19. ------
  20. estimator_: sklearn tree or tree ensemble model (e.g. RandomForest or GradientBoosting)
  21. reg_param: float
  22. Higher is more regularization (can be arbitrarily large, should not be < 0)
  23. shrinkage_scheme: str
  24. Experimental: Used to experiment with different forms of shrinkage. options are:
  25. (i) node_based shrinks based on number of samples in parent node
  26. (ii) leaf_based only shrinks leaf nodes based on number of leaf samples
  27. (iii) constant shrinks every node by a constant lambda
  28. """
  29. super().__init__()
  30. self.reg_param = reg_param
  31. # print('est', estimator_)
  32. self.estimator_ = estimator_
  33. self.shrinkage_scheme_ = shrinkage_scheme_
  34. self._init_prediction_task()
  35. if checks.check_is_fitted(self.estimator_):
  36. self._shrink()
  37. def __init__prediction_task(self):
  38. self.prediction_task = 'regression'
  39. def get_params(self, deep=True):
  40. if deep:
  41. return deepcopy({'reg_param': self.reg_param, 'estimator_': self.estimator_,
  42. # 'prediction_task': self.prediction_task,
  43. 'shrinkage_scheme_': self.shrinkage_scheme_})
  44. return {'reg_param': self.reg_param, 'estimator_': self.estimator_,
  45. # 'prediction_task': self.prediction_task,
  46. 'shrinkage_scheme_': self.shrinkage_scheme_}
  47. def fit(self, *args, **kwargs):
  48. self.estimator_.fit(*args, **kwargs)
  49. self._shrink()
  50. def _shrink(self, reg_param):
  51. for tree in self.trees_:
  52. tree.shrink(reg_param)
  53. def predict(self, *args, **kwargs):
  54. return self.estimator_.predict(*args, **kwargs)
  55. def predict_proba(self, *args, **kwargs):
  56. if hasattr(self.estimator_, 'predict_proba'):
  57. return self.estimator_.predict_proba(*args, **kwargs)
  58. else:
  59. return NotImplemented
  60. def score(self, *args, **kwargs):
  61. if hasattr(self.estimator_, 'score'):
  62. return self.estimator_.score(*args, **kwargs)
  63. else:
  64. return NotImplemented
  65. class HSFIGSRegressor(HSFIGS):
  66. def _init_prediction_task(self):
  67. self.prediction_task = 'regression'
  68. class HSFIGSClassifier(HSFIGS):
  69. def _init_prediction_task(self):
  70. self.prediction_task = 'classification'
  71. class HSFIGSClassifierCV(HSFIGSClassifier):
  72. def __init__(self, estimator_: BaseEstimator,
  73. reg_param_list: List[float] = [0.1, 1, 10, 50, 100, 500], shrinkage_scheme_: str = 'node_based',
  74. cv: int = 3, scoring=None, *args, **kwargs):
  75. """Note: args, kwargs are not used but left so that imodels-experiments can still pass redundant args.
  76. Cross-validation is used to select the best regularization parameter for hierarchical shrinkage.
  77. """
  78. super().__init__(estimator_, reg_param=None)
  79. self.reg_param_list = np.array(reg_param_list)
  80. self.cv = cv
  81. self.scoring = scoring
  82. self.shrinkage_scheme_ = shrinkage_scheme_
  83. # print('estimator', self.estimator_,
  84. # 'checks.check_is_fitted(estimator)', checks.check_is_fitted(self.estimator_))
  85. # if checks.check_is_fitted(self.estimator_):
  86. # raise Warning('Passed an already fitted estimator,'
  87. # 'but shrinking not applied until fit method is called.')
  88. def fit(self, X, y, *args, **kwargs):
  89. self.scores_ = []
  90. for reg_param in self.reg_param_list:
  91. est = HSFIGSClassifier(deepcopy(self.estimator_), reg_param)
  92. cv_scores = cross_val_score(est, X, y, cv=self.cv, scoring=self.scoring)
  93. self.scores_.append(np.mean(cv_scores))
  94. self.reg_param = self.reg_param_list[np.argmax(self.scores_)]
  95. super().fit(X=X, y=y)
  96. class HSFIGSRegressorCV(HSFIGSRegressor):
  97. def __init__(self, estimator_: BaseEstimator,
  98. reg_param_list: List[float] = [0.1, 1, 10, 50, 100, 500],
  99. shrinkage_scheme_: str = 'node_based',
  100. cv: int = 3, scoring=None, *args, **kwargs):
  101. """Note: args, kwargs are not used but left so that imodels-experiments can still pass redundant args.
  102. Cross-validation is used to select the best regularization parameter for hierarchical shrinkage.
  103. """
  104. super().__init__(estimator_, reg_param=None)
  105. self.reg_param_list = np.array(reg_param_list)
  106. self.cv = cv
  107. self.scoring = scoring
  108. self.shrinkage_scheme_ = shrinkage_scheme_
  109. # print('estimator', self.estimator_,
  110. # 'checks.check_is_fitted(estimator)', checks.check_is_fitted(self.estimator_))
  111. # if checks.check_is_fitted(self.estimator_):
  112. # raise Warning('Passed an already fitted estimator,'
  113. # 'but shrinking not applied until fit method is called.')
  114. def fit(self, X, y):
  115. self.scores_ = []
  116. for reg_param in self.reg_param_list:
  117. est = HSFIGSRegressor(deepcopy(self.estimator_), reg_param)
  118. cv_scores = cross_val_score(est, X, y, cv=self.cv, scoring=self.scoring)
  119. self.scores_.append(np.mean(cv_scores))
  120. self.reg_param = self.reg_param_list[np.argmax(self.scores_)]
  121. super().fit(X=X, y=y)
  122. if __name__ == '__main__':
  123. np.random.seed(15)
  124. # X, y = datasets.fetch_california_housing(return_X_y=True) # regression
  125. # X, y = datasets.load_breast_cancer(return_X_y=True) # binary classification
  126. X, y = datasets.load_diabetes(return_X_y=True) # regression
  127. # X = np.random.randn(500, 10)
  128. # y = (X[:, 0] > 0).astype(float) + (X[:, 1] > 1).astype(float)
  129. X_train, X_test, y_train, y_test = train_test_split(
  130. X, y, test_size=0.33, random_state=10
  131. )
  132. print('X.shape', X.shape)
  133. print('ys', np.unique(y_train))
  134. # m = HSTree(estimator_=DecisionTreeClassifier(), reg_param=0.1)
  135. # m = DecisionTreeClassifier(max_leaf_nodes = 20,random_state=1, max_features=None)
  136. m = DecisionTreeRegressor(random_state=42, max_leaf_nodes=20)
  137. # print('best alpha', m.reg_param)
  138. m.fit(X_train, y_train)
  139. # m.predict_proba(X_train) # just run this
  140. print('score', r2_score(y_test, m.predict(X_test)))
  141. print('running again....')
  142. # x = DecisionTreeRegressor(random_state = 42, ccp_alpha = 0.3)
  143. # x.fit(X_train,y_train)
  144. # m = HSTree(estimator_=DecisionTreeRegressor(random_state=42, max_features=None), reg_param=10)
  145. # m = HSTree(estimator_=DecisionTreeClassifier(random_state=42, max_features=None), reg_param=0)
  146. m = HSFIGSClassifierCV(estimator_=DecisionTreeRegressor(max_leaf_nodes=10, random_state=1),
  147. shrinkage_scheme_='node_based',
  148. reg_param_list=[0.1, 1, 2, 5, 10, 25, 50, 100, 500])
  149. # m = ShrunkTreeCV(estimator_=DecisionTreeClassifier())
  150. # m = HSTreeClassifier(estimator_ = GradientBoostingClassifier(random_state = 10),reg_param = 5)
  151. m.fit(X_train, y_train)
  152. print('best alpha', m.reg_param)
  153. # m.predict_proba(X_train) # just run this
  154. # print('score', m.score(X_test, y_test))
  155. print('score', r2_score(y_test, m.predict(X_test)))
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...