File: test_owgradientboosting.py

package info (click to toggle)
orange3 3.40.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 15,908 kB
  • sloc: python: 162,745; ansic: 622; makefile: 322; sh: 93; cpp: 77
file content (376 lines) | stat: -rw-r--r-- 16,638 bytes parent folder | download | duplicates (2)
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
import json
import unittest
import sys
from typing import Type
from unittest.mock import patch, Mock

from Orange.classification import GBClassifier

try:
    from Orange.classification import XGBClassifier, XGBRFClassifier
except ImportError:
    XGBClassifier = XGBRFClassifier = None
try:
    from Orange.classification import CatGBClassifier
except ImportError:
    CatGBClassifier = None
from Orange.data import Table
from Orange.modelling import GBLearner
from Orange.preprocess.score import Scorer
from Orange.regression import GBRegressor

try:
    from Orange.regression import XGBRegressor, XGBRFRegressor
except ImportError:
    XGBRegressor = XGBRFRegressor = None
try:
    from Orange.regression import CatGBRegressor
except ImportError:
    CatGBRegressor = None
from Orange.widgets.model.owgradientboosting import OWGradientBoosting, \
    LearnerItemModel, GBLearnerEditor, XGBLearnerEditor, XGBRFLearnerEditor, \
    CatGBLearnerEditor, BaseEditor
from Orange.widgets.settings import SettingProvider
from Orange.widgets.tests.base import WidgetTest, ParameterMapping, \
    WidgetLearnerTestMixin, datasets, simulate, GuiTest
from Orange.widgets.widget import OWWidget


def get_tree_train_params(model):
    ln = json.loads(model.skl_model.get_booster().save_config())["learner"]
    try:
        return ln["gradient_booster"]["tree_train_param"]
    except KeyError:
        return ln["gradient_booster"]["updater"]["grow_colmaker"]["train_param"]


def create_parent(editor_class):
    class DummyWidget(OWWidget):
        name = "Mock"
        settings_changed = Mock()
        editor = SettingProvider(editor_class)

    return DummyWidget()


class TestLearnerItemModel(GuiTest):
    def test_model(self):
        classifiers = [GBClassifier, XGBClassifier,
                       XGBRFClassifier, CatGBClassifier]
        widget = create_parent(CatGBLearnerEditor)
        model = LearnerItemModel(widget)
        n_items = 4
        self.assertEqual(model.rowCount(), n_items)
        for i in range(n_items):
            self.assertEqual(model.item(i).isEnabled(),
                             classifiers[i] is not None)

    @patch("Orange.widgets.model.owgradientboosting.LearnerItemModel.LEARNERS",
           [(GBLearner, "", ""),
            (None, "Gradient Boosting (catboost)", "catboost")])
    def test_missing_lib(self):
        widget = create_parent(CatGBLearnerEditor)
        model = LearnerItemModel(widget)
        self.assertEqual(model.rowCount(), 2)
        self.assertTrue(model.item(0).isEnabled())
        self.assertFalse(model.item(1).isEnabled())


class BaseEditorTest(GuiTest):
    EditorClass: Type[BaseEditor] = None

    def setUp(self):
        super().setUp()
        editor_class = self.EditorClass
        self.widget = create_parent(editor_class)
        self.editor = editor_class(self.widget)  # pylint: disable=not-callable

    def tearDown(self) -> None:
        self.widget.deleteLater()
        super().tearDown()


class TestGBLearnerEditor(BaseEditorTest):
    EditorClass = GBLearnerEditor

    def test_arguments(self):
        args = {"n_estimators": 100, "learning_rate": 0.1, "max_depth": 3,
                "random_state": 0, "subsample": 1, "min_samples_split": 2}
        self.assertDictEqual(self.editor.get_arguments(), args)

    def test_learner_parameters(self):
        params = (("Method", "Gradient Boosting (scikit-learn)"),
                  ("Number of trees", 100),
                  ("Learning rate", 0.1),
                  ("Replicable training", "Yes"),
                  ("Maximum tree depth", 3),
                  ("Fraction of training instances", 1),
                  ("Stop splitting nodes with maximum instances", 2))
        self.assertTupleEqual(self.editor.get_learner_parameters(), params)

    def test_default_parameters_cls(self):
        data = Table("heart_disease")
        booster = GBClassifier()
        model = booster(data)
        params = model.skl_model.get_params()
        self.assertEqual(params["n_estimators"], self.editor.n_estimators)
        self.assertEqual(params["learning_rate"], self.editor.learning_rate)
        self.assertEqual(params["max_depth"], self.editor.max_depth)
        self.assertEqual(params["subsample"], self.editor.subsample)
        self.assertEqual(params["min_samples_split"],
                         self.editor.min_samples_split)
        self.assertTrue(self.editor.random_state)  # different than default
        self.assertIsNone(params["random_state"])

    def test_default_parameters_reg(self):
        data = Table("housing")
        booster = GBRegressor()
        model = booster(data)
        params = model.skl_model.get_params()
        self.assertEqual(params["n_estimators"], self.editor.n_estimators)
        self.assertEqual(params["learning_rate"], self.editor.learning_rate)
        self.assertEqual(params["max_depth"], self.editor.max_depth)
        self.assertEqual(params["subsample"], self.editor.subsample)
        self.assertEqual(params["min_samples_split"],
                         self.editor.min_samples_split)
        self.assertTrue(self.editor.random_state)  # different than default
        self.assertIsNone(params["random_state"])


class TestXGBLearnerEditor(BaseEditorTest):
    EditorClass = XGBLearnerEditor

    def test_arguments(self):
        args = {"n_estimators": 100, "learning_rate": 0.3, "max_depth": 6,
                "reg_lambda": 1, "colsample_bytree": 1, "colsample_bylevel": 1,
                "colsample_bynode": 1, "subsample": 1, "random_state": 0}
        self.assertDictEqual(self.editor.get_arguments(), args)

    @unittest.skipIf(XGBClassifier is None, "Missing 'xgboost' package")
    def test_learner_parameters(self):
        params = (("Method", "Extreme Gradient Boosting (xgboost)"),
                  ("Number of trees", 100),
                  ("Learning rate", 0.3),
                  ("Replicable training", "Yes"),
                  ("Maximum tree depth", 6),
                  ("Regularization strength", 1),
                  ("Fraction of training instances", 1),
                  ("Fraction of features for each tree", 1),
                  ("Fraction of features for each level", 1),
                  ("Fraction of features for each split", 1))
        self.assertTupleEqual(self.editor.get_learner_parameters(), params)

    @unittest.skipIf(XGBClassifier is None, "Missing 'xgboost' package")
    def test_default_parameters_cls(self):
        data = Table("heart_disease")
        booster = XGBClassifier()
        model = booster(data)
        params = model.skl_model.get_params()
        tp = get_tree_train_params(model)
        self.assertEqual(params["n_estimators"], self.editor.n_estimators)
        self.assertEqual(
            round(float(tp["learning_rate"]), 1), self.editor.learning_rate
        )
        self.assertEqual(int(tp["max_depth"]), self.editor.max_depth)
        self.assertEqual(float(tp["reg_lambda"]), self.editor.lambda_)
        self.assertEqual(int(tp["subsample"]), self.editor.subsample)
        self.assertEqual(int(tp["colsample_bytree"]), self.editor.colsample_bytree)
        self.assertEqual(int(tp["colsample_bylevel"]), self.editor.colsample_bylevel)
        self.assertEqual(int(tp["colsample_bynode"]), self.editor.colsample_bynode)

    @unittest.skipIf(XGBRegressor is None, "Missing 'xgboost' package")
    def test_default_parameters_reg(self):
        data = Table("housing")
        booster = XGBRegressor()
        model = booster(data)
        params = model.skl_model.get_params()
        tp = get_tree_train_params(model)
        self.assertEqual(params["n_estimators"], self.editor.n_estimators)
        self.assertEqual(
            round(float(tp["learning_rate"]), 1), self.editor.learning_rate
        )
        self.assertEqual(int(tp["max_depth"]), self.editor.max_depth)
        self.assertEqual(float(tp["reg_lambda"]), self.editor.lambda_)
        self.assertEqual(int(tp["subsample"]), self.editor.subsample)
        self.assertEqual(int(tp["colsample_bytree"]), self.editor.colsample_bytree)
        self.assertEqual(int(tp["colsample_bylevel"]), self.editor.colsample_bylevel)
        self.assertEqual(int(tp["colsample_bynode"]), self.editor.colsample_bynode)


class TestXGBRFLearnerEditor(BaseEditorTest):
    EditorClass = XGBRFLearnerEditor

    def test_arguments(self):
        args = {"n_estimators": 100, "learning_rate": 0.3, "max_depth": 6,
                "reg_lambda": 1, "colsample_bytree": 1, "colsample_bylevel": 1,
                "colsample_bynode": 1, "subsample": 1, "random_state": 0}
        self.assertDictEqual(self.editor.get_arguments(), args)

    @unittest.skipIf(XGBRFClassifier is None, "Missing 'xgboost' package")
    def test_learner_parameters(self):
        params = (("Method",
                   "Extreme Gradient Boosting Random Forest (xgboost)"),
                  ("Number of trees", 100),
                  ("Learning rate", 0.3),
                  ("Replicable training", "Yes"),
                  ("Maximum tree depth", 6),
                  ("Regularization strength", 1),
                  ("Fraction of training instances", 1),
                  ("Fraction of features for each tree", 1),
                  ("Fraction of features for each level", 1),
                  ("Fraction of features for each split", 1))
        self.assertTupleEqual(self.editor.get_learner_parameters(), params)

    @unittest.skipIf(XGBRFClassifier is None, "Missing 'xgboost' package")
    def test_default_parameters_cls(self):
        data = Table("heart_disease")
        booster = XGBRFClassifier()
        model = booster(data)
        params = model.skl_model.get_params()
        tp = get_tree_train_params(model)
        self.assertEqual(params["n_estimators"], self.editor.n_estimators)
        self.assertEqual(
            round(float(tp["learning_rate"]), 1), self.editor.learning_rate
        )
        self.assertEqual(int(tp["max_depth"]), self.editor.max_depth)
        self.assertEqual(float(tp["reg_lambda"]), self.editor.lambda_)
        self.assertEqual(int(tp["subsample"]), self.editor.subsample)
        self.assertEqual(int(tp["colsample_bytree"]), self.editor.colsample_bytree)
        self.assertEqual(int(tp["colsample_bylevel"]), self.editor.colsample_bylevel)
        self.assertEqual(int(tp["colsample_bynode"]), self.editor.colsample_bynode)

    @unittest.skipIf(XGBRFRegressor is None, "Missing 'xgboost' package")
    def test_default_parameters_reg(self):
        data = Table("housing")
        booster = XGBRFRegressor()
        model = booster(data)
        params = model.skl_model.get_params()
        tp = get_tree_train_params(model)
        self.assertEqual(params["n_estimators"], self.editor.n_estimators)
        self.assertEqual(
            round(float(tp["learning_rate"]), 1), self.editor.learning_rate
        )
        self.assertEqual(int(tp["max_depth"]), self.editor.max_depth)
        self.assertEqual(float(tp["reg_lambda"]), self.editor.lambda_)
        self.assertEqual(int(tp["subsample"]), self.editor.subsample)
        self.assertEqual(int(tp["colsample_bytree"]), self.editor.colsample_bytree)
        self.assertEqual(int(tp["colsample_bylevel"]), self.editor.colsample_bylevel)
        self.assertEqual(int(tp["colsample_bynode"]), self.editor.colsample_bynode)


class TestCatGBLearnerEditor(BaseEditorTest):
    EditorClass = CatGBLearnerEditor

    def test_arguments(self):
        args = {"n_estimators": 100, "learning_rate": 0.3, "max_depth": 6,
                "reg_lambda": 3, "colsample_bylevel": 1, "random_state": 0}
        self.assertDictEqual(self.editor.get_arguments(), args)

    @unittest.skipIf(CatGBClassifier is None, "Missing 'catboost' package")
    def test_learner_parameters(self):
        params = (("Method", "Gradient Boosting (catboost)"),
                  ("Number of trees", 100),
                  ("Learning rate", 0.3),
                  ("Replicable training", "Yes"),
                  ("Maximum tree depth", 6),
                  ("Regularization strength", 3),
                  ("Fraction of features for each tree", 1))
        self.assertTupleEqual(self.editor.get_learner_parameters(), params)

    @unittest.skipIf(CatGBClassifier is None, "Missing 'catboost' package")
    def test_default_parameters_cls(self):
        data = Table("heart_disease")
        booster = CatGBClassifier()
        model = booster(data)
        params = model.cat_model.get_all_params()
        self.assertEqual(self.editor.n_estimators, 100)
        self.assertEqual(params["iterations"], 1000)
        self.assertEqual(params["depth"], self.editor.max_depth)
        self.assertEqual(params["l2_leaf_reg"], self.editor.lambda_)
        self.assertEqual(params["rsm"], self.editor.colsample_bylevel)
        self.assertEqual(self.editor.learning_rate, 0.3)
        # params["learning_rate"] is automatically defined so don't test it

    @unittest.skipIf(CatGBRegressor is None, "Missing 'catboost' package")
    def test_default_parameters_reg(self):
        data = Table("housing")
        booster = CatGBRegressor()
        model = booster(data)
        params = model.cat_model.get_all_params()
        self.assertEqual(self.editor.n_estimators, 100)
        self.assertEqual(params["iterations"], 1000)
        self.assertEqual(params["depth"], self.editor.max_depth)
        self.assertEqual(params["l2_leaf_reg"], self.editor.lambda_)
        self.assertEqual(params["rsm"], self.editor.colsample_bylevel)
        self.assertEqual(self.editor.learning_rate, 0.3)
        # params["learning_rate"] is automatically defined so don't test it

class TestOWGradientBoosting(WidgetTest, WidgetLearnerTestMixin):
    def setUp(self):
        self.widget = self.create_widget(OWGradientBoosting,
                                         stored_settings={"auto_apply": False})
        self.init()

        controls = self.widget.editor.controls
        self.parameters = [
            ParameterMapping("n_estimators", controls.n_estimators, [500, 10]),
            ParameterMapping("learning_rate", controls.learning_rate),
            ParameterMapping("max_depth", controls.max_depth),
            ParameterMapping("min_samples_split", controls.min_samples_split),
        ]

    def test_scorer(self):
        self.assertIsInstance(
            self.get_output(self.widget.Outputs.learner), Scorer
        )

    def test_datasets(self):
        for ds in datasets.datasets():
            self.send_signal(self.widget.Inputs.data, ds)

    @unittest.skipIf(XGBClassifier is None, "Missing 'xgboost' package")
    def test_xgb_params(self):
        simulate.combobox_activate_index(self.widget.controls.method_index, 1)
        editor = self.widget.editor
        controls = editor.controls
        reg_slider = controls.lambda_index

        self.parameters = [
            ParameterMapping("n_estimators", controls.n_estimators, [500, 10]),
            ParameterMapping("learning_rate", controls.learning_rate),
            ParameterMapping("max_depth", controls.max_depth),
            ParameterMapping("reg_lambda", reg_slider,
                             values=[editor.LAMBDAS[0], editor.LAMBDAS[-1]],
                             getter=lambda: editor.LAMBDAS[reg_slider.value()],
                             setter=lambda val: reg_slider.setValue(
                                 editor.LAMBDAS.index(val))),
        ]
        self.test_parameters()

    def test_methods(self):
        self.send_signal(self.widget.Inputs.data, self.data)
        method_cb = self.widget.controls.method_index
        for i, (cls, _, _) in enumerate(LearnerItemModel.LEARNERS):
            if cls is None:
                continue
            simulate.combobox_activate_index(method_cb, i)
            self.click_apply()
            self.assertIsInstance(self.widget.learner, cls)

    def test_missing_lib(self):
        modules = {k: v for k, v in sys.modules.items()
                   if "orange" not in k.lower()}  # retain built-ins
        modules["xgboost"] = None
        modules["catboost"] = None
        # pylint: disable=reimported,redefined-outer-name
        # pylint: disable=import-outside-toplevel
        with patch.dict(sys.modules, modules, clear=True):
            from Orange.widgets.model.owgradientboosting import \
                OWGradientBoosting
            widget = self.create_widget(OWGradientBoosting,
                                        stored_settings={"method_index": 3})
            self.assertEqual(widget.method_index, 0)


if __name__ == "__main__":
    unittest.main()