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

cart_ccp.py 8.6 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
188
189
190
191
192
193
194
195
196
197
  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.model_selection import cross_val_score, train_test_split
  7. from sklearn.tree import DecisionTreeClassifier
  8. from imodels.tree.hierarchical_shrinkage import HSTreeRegressor, HSTreeClassifier
  9. from imodels.util.tree import compute_tree_complexity
  10. class DecisionTreeCCPClassifier(DecisionTreeClassifier):
  11. def __init__(self, estimator_: BaseEstimator, desired_complexity: int = 1, complexity_measure='max_rules', *args,
  12. **kwargs):
  13. self.desired_complexity = desired_complexity
  14. # print('est', estimator_)
  15. self.estimator_ = estimator_
  16. self.complexity_measure = complexity_measure
  17. def _get_alpha(self, X, y, sample_weight=None, *args, **kwargs):
  18. path = self.estimator_.cost_complexity_pruning_path(X, y)
  19. ccp_alphas, impurities = path.ccp_alphas, path.impurities
  20. complexities = {}
  21. low = 0
  22. high = len(ccp_alphas) - 1
  23. cur = 0
  24. while low <= high:
  25. cur = (high + low) // 2
  26. est_params = self.estimator_.get_params()
  27. est_params['ccp_alpha'] = ccp_alphas[cur]
  28. copied_estimator = deepcopy(self.estimator_).set_params(**est_params)
  29. copied_estimator.fit(X, y)
  30. if self._get_complexity(copied_estimator, self.complexity_measure) < self.desired_complexity:
  31. high = cur - 1
  32. elif self._get_complexity(copied_estimator, self.complexity_measure) > self.desired_complexity:
  33. low = cur + 1
  34. else:
  35. break
  36. self.alpha = ccp_alphas[cur]
  37. # for alpha in ccp_alphas:
  38. # est_params = self.estimator_.get_params()
  39. # est_params['ccp_alpha'] = alpha
  40. # copied_estimator = deepcopy(self.estimator_).set_params(**est_params)
  41. # copied_estimator.fit(X, y)
  42. # complexities[alpha] = self._get_complexity(copied_estimator,self.complexity_measure)
  43. # closest_alpha, closest_leaves = min(complexities.items(), key=lambda x: abs(self.desired_complexity - x[1]))
  44. # self.alpha = closest_alpha
  45. def fit(self, X, y, sample_weight=None, *args, **kwargs):
  46. params_for_fitting = self.estimator_.get_params()
  47. self._get_alpha(X, y, sample_weight, *args, **kwargs)
  48. params_for_fitting['ccp_alpha'] = self.alpha
  49. self.estimator_.set_params(**params_for_fitting)
  50. self.estimator_.fit(X, y, *args, **kwargs)
  51. def _get_complexity(self, BaseEstimator, complexity_measure):
  52. return compute_tree_complexity(BaseEstimator.tree_, complexity_measure)
  53. def predict_proba(self, *args, **kwargs):
  54. if hasattr(self.estimator_, 'predict_proba'):
  55. return self.estimator_.predict_proba(*args, **kwargs)
  56. else:
  57. return NotImplemented
  58. def predict(self, X, *args, **kwargs):
  59. return self.estimator_.predict(X, *args, **kwargs)
  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 DecisionTreeCCPRegressor(BaseEstimator):
  66. def __init__(self, estimator_: BaseEstimator, desired_complexity: int = 1, complexity_measure='max_rules', *args,
  67. **kwargs):
  68. self.desired_complexity = desired_complexity
  69. # print('est', estimator_)
  70. self.estimator_ = estimator_
  71. self.alpha = 0.0
  72. self.complexity_measure = complexity_measure
  73. def _get_alpha(self, X, y, sample_weight=None):
  74. path = self.estimator_.cost_complexity_pruning_path(X, y)
  75. ccp_alphas, impurities = path.ccp_alphas, path.impurities
  76. complexities = {}
  77. low = 0
  78. high = len(ccp_alphas) - 1
  79. cur = 0
  80. while low <= high:
  81. cur = (high + low) // 2
  82. est_params = self.estimator_.get_params()
  83. est_params['ccp_alpha'] = ccp_alphas[cur]
  84. copied_estimator = deepcopy(self.estimator_).set_params(**est_params)
  85. copied_estimator.fit(X, y)
  86. if self._get_complexity(copied_estimator, self.complexity_measure) < self.desired_complexity:
  87. high = cur - 1
  88. elif self._get_complexity(copied_estimator, self.complexity_measure) > self.desired_complexity:
  89. low = cur + 1
  90. else:
  91. break
  92. self.alpha = ccp_alphas[cur]
  93. # path = self.estimator_.cost_complexity_pruning_path(X,y)
  94. # ccp_alphas, impurities = path.ccp_alphas, path.impurities
  95. # complexities = {}
  96. # for alpha in ccp_alphas:
  97. # est_params = self.estimator_.get_params()
  98. # est_params['ccp_alpha'] = alpha
  99. # copied_estimator = deepcopy(self.estimator_).set_params(**est_params)
  100. # copied_estimator.fit(X, y)
  101. # complexities[alpha] = self._get_complexity(copied_estimator,self.complexity_measure)
  102. # closest_alpha, closest_leaves = min(complexities.items(), key=lambda x: abs(self.desired_complexity - x[1]))
  103. # self.alpha = closest_alpha
  104. def fit(self, X, y, sample_weight=None):
  105. params_for_fitting = self.estimator_.get_params()
  106. self._get_alpha(X, y, sample_weight)
  107. params_for_fitting['ccp_alpha'] = self.alpha
  108. self.estimator_.set_params(**params_for_fitting)
  109. self.estimator_.fit(X, y)
  110. def _get_complexity(self, BaseEstimator, complexity_measure):
  111. return compute_tree_complexity(BaseEstimator.tree_, self.complexity_measure)
  112. def predict(self, X, *args, **kwargs):
  113. return self.estimator_.predict(X, *args, **kwargs)
  114. def score(self, *args, **kwargs):
  115. if hasattr(self.estimator_, 'score'):
  116. return self.estimator_.score(*args, **kwargs)
  117. else:
  118. return NotImplemented
  119. class HSDecisionTreeCCPRegressorCV(HSTreeRegressor):
  120. def __init__(self, estimator_: BaseEstimator, reg_param_list: List[float] = [0.1, 1, 10, 50, 100, 500],
  121. desired_complexity: int = 1, cv: int = 3, scoring=None, *args, **kwargs):
  122. super().__init__(estimator_=estimator_, reg_param=None)
  123. self.reg_param_list = np.array(reg_param_list)
  124. self.cv = cv
  125. self.scoring = scoring
  126. self.desired_complexity = desired_complexity
  127. def fit(self, X, y, sample_weight=None, *args, **kwargs):
  128. m = DecisionTreeCCPRegressor(self.estimator_, desired_complexity=self.desired_complexity)
  129. m.fit(X, y, sample_weight, *args, **kwargs)
  130. self.scores_ = []
  131. for reg_param in self.reg_param_list:
  132. est = HSTreeRegressor(deepcopy(m.estimator_), reg_param)
  133. cv_scores = cross_val_score(est, X, y, cv=self.cv, scoring=self.scoring)
  134. self.scores_.append(np.mean(cv_scores))
  135. self.reg_param = self.reg_param_list[np.argmax(self.scores_)]
  136. super().fit(X=X, y=y)
  137. class HSDecisionTreeCCPClassifierCV(HSTreeClassifier):
  138. def __init__(self, estimator_: BaseEstimator, reg_param_list: List[float] = [0.1, 1, 10, 50, 100, 500],
  139. desired_complexity: int = 1, cv: int = 3, scoring=None, *args, **kwargs):
  140. super().__init__(estimator_=estimator_, reg_param=None)
  141. self.reg_param_list = np.array(reg_param_list)
  142. self.cv = cv
  143. self.scoring = scoring
  144. self.desired_complexity = desired_complexity
  145. def fit(self, X, y, sample_weight=None, *args, **kwargs):
  146. m = DecisionTreeCCPClassifier(self.estimator_, desired_complexity=self.desired_complexity)
  147. m.fit(X, y, sample_weight, *args, **kwargs)
  148. self.scores_ = []
  149. for reg_param in self.reg_param_list:
  150. est = HSTreeClassifier(deepcopy(m.estimator_), reg_param)
  151. cv_scores = cross_val_score(est, X, y, cv=self.cv, scoring=self.scoring)
  152. self.scores_.append(np.mean(cv_scores))
  153. self.reg_param = self.reg_param_list[np.argmax(self.scores_)]
  154. super().fit(X=X, y=y)
  155. if __name__ == '__main__':
  156. m = DecisionTreeCCPClassifier(estimator_=DecisionTreeClassifier(random_state=1), desired_complexity=10,
  157. complexity_measure='max_leaf_nodes')
  158. # X,y = make_friedman1() #For regression
  159. X, y = datasets.load_breast_cancer(return_X_y=True)
  160. X_train, X_test, y_train, y_test = train_test_split(
  161. X, y, test_size=0.33, random_state=42)
  162. m.fit(X_train, y_train)
  163. m.predict(X_test)
  164. print(m.score(X_test, y_test))
  165. m = HSDecisionTreeCCPClassifierCV(estimator_=DecisionTreeClassifier(random_state=1), desired_complexity=10,
  166. reg_param_list=[0.0, 0.1, 1.0, 5.0, 10.0, 25.0, 50.0, 100.0])
  167. m.fit(X_train, y_train)
  168. print(m.score(X_test, y_test))
Tip!

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

Comments

Loading...