-
Notifications
You must be signed in to change notification settings - Fork 247
/
boosting_overfit.py
283 lines (241 loc) · 11.9 KB
/
boosting_overfit.py
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# ----------------------------------------------------------------------------
# Copyright (C) 2021-2023 Deepchecks (https://www.deepchecks.com)
#
# This file is part of Deepchecks.
# Deepchecks is distributed under the terms of the GNU Affero General
# Public License (version 3 or later).
# You should have received a copy of the GNU Affero General Public License
# along with Deepchecks. If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------
#
"""Boosting overfit check module."""
from copy import deepcopy
from typing import TYPE_CHECKING, Callable, Tuple, Union
import numpy as np
import plotly.graph_objects as go
from sklearn.pipeline import Pipeline
from deepchecks.core import CheckResult, ConditionCategory, ConditionResult
from deepchecks.core.errors import DeepchecksValueError, ModelValidationError
from deepchecks.tabular import Context, TrainTestCheck
from deepchecks.utils.docref import doclink
from deepchecks.utils.model import get_model_of_pipeline
from deepchecks.utils.strings import format_percent
if TYPE_CHECKING:
from deepchecks.core.checks import CheckConfig
__all__ = ['BoostingOverfit']
class PartialBoostingModel:
"""Wrapper for boosting models which limits the number of estimators being used in the prediction."""
_UNSUPPORTED_MODEL_ERROR = \
'Check is relevant for Boosting models of type {supported_models}, but received model of type {model_type}'
_NO_MODEL_ERROR = \
'Check is relevant only when receiving the model, but predictions/probabilities were received instead. ' \
'In order to use this check, please pass the model to the run() method.'
_SUPPORTED_CLASSIFICATION_MODELS = (
'AdaBoostClassifier',
'GradientBoostingClassifier',
'LGBMClassifier',
'XGBClassifier',
'CatBoostClassifier'
)
_SUPPORTED_REGRESSION_MODELS = (
'AdaBoostRegressor',
'GradientBoostingRegressor',
'LGBMRegressor',
'XGBRegressor',
'CatBoostRegressor'
)
_SUPPORTED_MODELS = _SUPPORTED_CLASSIFICATION_MODELS + _SUPPORTED_REGRESSION_MODELS
def __init__(self, model, step):
"""Construct wrapper for model with `predict` and `predict_proba` methods.
Parameters
----------
model
boosting model to wrap.
step
Number of iterations/estimators to limit the model on predictions.
"""
self.model_class = get_model_of_pipeline(model).__class__.__name__
self.step = step
if self.model_class in ['AdaBoostClassifier', 'GradientBoostingClassifier', 'AdaBoostRegressor',
'GradientBoostingRegressor']:
self.model = deepcopy(model)
if isinstance(model, Pipeline):
internal_estimator = get_model_of_pipeline(self.model)
internal_estimator.estimators_ = internal_estimator.estimators_[:self.step]
else:
self.model.estimators_ = self.model.estimators_[:self.step]
else:
self.model = model
@classmethod
def _raise_not_supported_model_error(cls, model_class):
if model_class != '_DummyModel':
raise ModelValidationError(cls._UNSUPPORTED_MODEL_ERROR.format(
supported_models=cls._SUPPORTED_MODELS,
model_type=model_class
))
else:
raise ModelValidationError(cls._NO_MODEL_ERROR)
def predict_proba(self, x):
if self.model_class in ['AdaBoostClassifier', 'GradientBoostingClassifier']:
return self.model.predict_proba(x)
elif self.model_class == 'LGBMClassifier':
return self.model.predict_proba(x, num_iteration=self.step)
elif self.model_class == 'XGBClassifier':
return self.model.predict_proba(x, iteration_range=(0, self.step))
elif self.model_class == 'CatBoostClassifier':
return self.model.predict_proba(x, ntree_end=self.step)
else:
self._raise_not_supported_model_error(self.model_class)
def predict(self, x):
if self.model_class in ['AdaBoostClassifier', 'GradientBoostingClassifier', 'AdaBoostRegressor',
'GradientBoostingRegressor']:
return self.model.predict(x)
elif self.model_class in ['LGBMClassifier', 'LGBMRegressor']:
return self.model.predict(x, num_iteration=self.step)
elif self.model_class in ['XGBClassifier', 'XGBRegressor']:
return self.model.predict(x, iteration_range=(0, self.step))
elif self.model_class in ['CatBoostClassifier', 'CatBoostRegressor']:
return self.model.predict(x, ntree_end=self.step)
else:
self._raise_not_supported_model_error(self.model_class)
@classmethod
def n_estimators(cls, model):
model = get_model_of_pipeline(model)
model_class = model.__class__.__name__
if model_class in ['AdaBoostClassifier', 'GradientBoostingClassifier', 'AdaBoostRegressor',
'GradientBoostingRegressor']:
return len(model.estimators_)
elif model_class in ['LGBMClassifier', 'LGBMRegressor']:
return model.n_estimators
elif model_class in ['XGBClassifier', 'XGBRegressor']:
return model.n_estimators
elif model_class in ['CatBoostClassifier', 'CatBoostRegressor']:
return model.tree_count_
else:
cls._raise_not_supported_model_error(model_class=model_class)
class BoostingOverfit(TrainTestCheck):
"""Check for overfit caused by using too many iterations in a gradient boosted model.
The check runs a pre-defined number of steps, and in each step it limits the boosting model to use up to X
estimators (number of estimators is monotonic increasing). It plots the given score calculated for each step for
both the train dataset and the test dataset.
Parameters
----------
scorer : Union[Callable, str] , default: None
Scorer used to verify the model, either function or sklearn scorer name.
scorer_name : str , default: None
Name to be displayed in the plot on y-axis. must be used together with 'scorer'
num_steps : int , default: 20
Number of splits of the model iterations to check.
n_samples : int , default: 1_000_000
number of samples to use for this check.
random_state : int, default: 42
random seed for all check internals.
"""
def __init__(
self,
alternative_scorer: Tuple[str, Union[str, Callable]] = None,
num_steps: int = 20,
n_samples: int = 1_000_000,
random_state: int = 42,
**kwargs
):
super().__init__(**kwargs)
self.alternative_scorer = dict([alternative_scorer]) if alternative_scorer else None
self.num_steps = num_steps
self.n_samples = n_samples
self.random_state = random_state
if not isinstance(self.num_steps, int) or self.num_steps < 2:
raise DeepchecksValueError('num_steps must be an integer larger than 1')
def run_logic(self, context: Context) -> CheckResult:
"""Run check.
Returns
-------
CheckResult
The score value on the test dataset.
"""
train_dataset = context.train.sample(self.n_samples, random_state=self.random_state)
test_dataset = context.test.sample(self.n_samples, random_state=self.random_state)
model = context.model
# Get default scorer
scorer = context.get_single_scorer(self.alternative_scorer)
# Get number of estimators on model
num_estimators = PartialBoostingModel.n_estimators(model)
estimator_steps = _calculate_steps(self.num_steps, num_estimators)
train_scores = []
test_scores = []
for step in estimator_steps:
train_scores.append(_partial_score(scorer, train_dataset, model, step))
test_scores.append(_partial_score(scorer, test_dataset, model, step))
result = {'test': test_scores, 'train': train_scores}
if context.with_display:
fig = go.Figure()
fig.add_trace(go.Scatter(x=estimator_steps, y=np.array(train_scores),
mode='lines+markers',
name='Training score'))
fig.add_trace(go.Scatter(x=estimator_steps, y=np.array(test_scores),
mode='lines+markers',
name='Test score'))
fig.update_layout(
title_text=f'{scorer.name} score compared to number of boosting iteration',
height=500
)
fig.update_xaxes(title='Number of boosting iterations')
fig.update_yaxes(title=scorer.name)
display_text = f"""<span>
The check limits the boosting model to using up to N estimators each time, and plotting the
{scorer.name} calculated for each subset of estimators for both the train dataset and the test dataset.
</span>"""
display = [display_text, fig]
else:
display = None
return CheckResult(result, display=display, header='Boosting Overfit')
def add_condition_test_score_percent_decline_less_than(self, threshold: float = 0.05):
"""Add condition.
Percent of decline between the maximal score achieved in any boosting iteration and the score achieved in the
last iteration ("regular" model score) is not above given threshold.
Parameters
----------
threshold : float , default: 0.05
Maximum percentage decline allowed (value 0 and above)
"""
def condition(result: dict):
max_score = max(result['test'])
last_score = result['test'][-1]
pct_diff = (max_score - last_score) / abs(max_score)
details = f'Found score decline of {format_percent(-pct_diff)}'
category = ConditionCategory.PASS if pct_diff < threshold else ConditionCategory.FAIL
return ConditionResult(category, details)
name = f'Test score over iterations is less than {format_percent(threshold)} from the best score'
return self.add_condition(name, condition)
def config(self, include_version: bool = True, include_defaults: bool = True) -> 'CheckConfig':
"""Return check instance config."""
if self.alternative_scorer is not None:
for k, v in self.alternative_scorer.items():
if not isinstance(v, str):
reference = doclink(
'supported-metrics-by-string',
template='For a list of built-in scorers please refer to {link}. '
)
raise ValueError(
'Only built-in scorers are allowed when serializing check instances. '
f'{reference}Scorer name: {k}'
)
return super().config(include_version, include_defaults=include_defaults)
def _partial_score(scorer, dataset, model, step):
partial_model = PartialBoostingModel(model, step)
return scorer(partial_model, dataset)
def _calculate_steps(num_steps, num_estimators):
"""Calculate steps (integers between 1 to num_estimators) to work on."""
if num_steps >= num_estimators:
return list(range(1, num_estimators + 1))
if num_steps <= 5:
steps_percents = np.linspace(0, 1.0, num_steps + 1)[1:]
steps_numbers = np.ceil(steps_percents * num_estimators)
steps_set = {int(s) for s in steps_numbers}
else:
steps_percents = np.linspace(5 / num_estimators, 1.0, num_steps - 4)[1:]
steps_numbers = np.ceil(steps_percents * num_estimators)
steps_set = {int(s) for s in steps_numbers}
# We want to forcefully take the first 5 estimators, since they have the largest affect on the model performance
steps_set.update({1, 2, 3, 4, 5})
return sorted(steps_set)