-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtest_classifier.py
388 lines (319 loc) · 12.6 KB
/
test_classifier.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
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
377
378
379
380
381
382
383
384
385
386
387
388
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from safeds.data.tabular.containers import Table, TaggedTable
from safeds.exceptions import (
DatasetContainsTargetError,
DatasetMissesFeaturesError,
LearningError,
ModelNotFittedError,
PredictionError,
UntaggedTableError,
)
from safeds.ml.classical.classification import (
AdaBoost,
Classifier,
DecisionTree,
GradientBoosting,
KNearestNeighbors,
LogisticRegression,
RandomForest,
SupportVectorMachine,
)
if TYPE_CHECKING:
from _pytest.fixtures import FixtureRequest
from sklearn.base import ClassifierMixin
def classifiers() -> list[Classifier]:
"""
Return the list of classifiers to test.
After you implemented a new classifier, add it to this list to ensure its `fit` and `predict` method work as
expected. Place tests of methods that are specific to your classifier in a separate test file.
Returns
-------
classifiers : list[Classifier]
The list of classifiers to test.
"""
return [
AdaBoost(),
DecisionTree(),
GradientBoosting(),
KNearestNeighbors(2),
LogisticRegression(),
RandomForest(),
SupportVectorMachine(),
]
@pytest.fixture()
def valid_data() -> TaggedTable:
return Table(
{
"id": [1, 4],
"feat1": [2, 5],
"feat2": [3, 6],
"target": [0, 1],
},
).tag_columns(target_name="target", feature_names=["feat1", "feat2"])
@pytest.fixture()
def invalid_data() -> TaggedTable:
return Table(
{
"id": [1, 4],
"feat1": ["a", 5],
"feat2": [3, 6],
"target": [0, 1],
},
).tag_columns(target_name="target", feature_names=["feat1", "feat2"])
@pytest.mark.parametrize("classifier", classifiers(), ids=lambda x: x.__class__.__name__)
class TestFit:
def test_should_succeed_on_valid_data(self, classifier: Classifier, valid_data: TaggedTable) -> None:
classifier.fit(valid_data)
assert True # This asserts that the fit method succeeds
def test_should_not_change_input_classifier(self, classifier: Classifier, valid_data: TaggedTable) -> None:
classifier.fit(valid_data)
assert not classifier.is_fitted()
def test_should_not_change_input_table(self, classifier: Classifier, request: FixtureRequest) -> None:
valid_data = request.getfixturevalue("valid_data")
valid_data_copy = request.getfixturevalue("valid_data")
classifier.fit(valid_data)
assert valid_data == valid_data_copy
def test_should_raise_on_invalid_data(self, classifier: Classifier, invalid_data: TaggedTable) -> None:
with pytest.raises(LearningError):
classifier.fit(invalid_data)
@pytest.mark.parametrize(
"table",
[
Table(
{
"a": [1.0, 0.0, 0.0, 0.0],
"b": [0.0, 1.0, 1.0, 0.0],
"c": [0.0, 0.0, 0.0, 1.0],
},
),
],
ids=["untagged_table"],
)
def test_should_raise_if_table_is_not_tagged(self, classifier: Classifier, table: Table) -> None:
with pytest.raises(UntaggedTableError):
classifier.fit(table) # type: ignore[arg-type]
@pytest.mark.parametrize("classifier", classifiers(), ids=lambda x: x.__class__.__name__)
class TestPredict:
def test_should_include_features_of_input_table(self, classifier: Classifier, valid_data: TaggedTable) -> None:
fitted_classifier = classifier.fit(valid_data)
prediction = fitted_classifier.predict(valid_data.features)
assert prediction.features == valid_data.features
def test_should_include_complete_input_table(self, classifier: Classifier, valid_data: TaggedTable) -> None:
fitted_regressor = classifier.fit(valid_data)
prediction = fitted_regressor.predict(valid_data.remove_columns(["target"]))
assert prediction.remove_columns(["target"]) == valid_data.remove_columns(["target"])
def test_should_set_correct_target_name(self, classifier: Classifier, valid_data: TaggedTable) -> None:
fitted_classifier = classifier.fit(valid_data)
prediction = fitted_classifier.predict(valid_data.features)
assert prediction.target.name == "target"
def test_should_not_change_input_table(self, classifier: Classifier, request: FixtureRequest) -> None:
valid_data = request.getfixturevalue("valid_data")
valid_data_copy = request.getfixturevalue("valid_data")
fitted_classifier = classifier.fit(valid_data)
fitted_classifier.predict(valid_data.features)
assert valid_data == valid_data_copy
def test_should_raise_if_not_fitted(self, classifier: Classifier, valid_data: TaggedTable) -> None:
with pytest.raises(ModelNotFittedError):
classifier.predict(valid_data.features)
def test_should_raise_if_dataset_contains_target(self, classifier: Classifier, valid_data: TaggedTable) -> None:
fitted_classifier = classifier.fit(valid_data)
with pytest.raises(DatasetContainsTargetError, match="target"):
fitted_classifier.predict(valid_data)
def test_should_raise_if_dataset_misses_features(self, classifier: Classifier, valid_data: TaggedTable) -> None:
fitted_classifier = classifier.fit(valid_data)
with pytest.raises(DatasetMissesFeaturesError, match="[feat1, feat2]"):
fitted_classifier.predict(valid_data.remove_columns(["feat1", "feat2", "target"]))
def test_should_raise_on_invalid_data(
self,
classifier: Classifier,
valid_data: TaggedTable,
invalid_data: TaggedTable,
) -> None:
fitted_classifier = classifier.fit(valid_data)
with pytest.raises(PredictionError):
fitted_classifier.predict(invalid_data.features)
@pytest.mark.parametrize("classifier", classifiers(), ids=lambda x: x.__class__.__name__)
class TestIsFitted:
def test_should_return_false_before_fitting(self, classifier: Classifier) -> None:
assert not classifier.is_fitted()
def test_should_return_true_after_fitting(self, classifier: Classifier, valid_data: TaggedTable) -> None:
fitted_classifier = classifier.fit(valid_data)
assert fitted_classifier.is_fitted()
class DummyClassifier(Classifier):
"""
Dummy classifier to test metrics.
Metrics methods expect a `TaggedTable` as input with two columns:
- `predicted`: The predicted targets.
- `expected`: The correct targets.
`target_name` must be set to `"expected"`.
"""
def fit(self, training_set: TaggedTable) -> DummyClassifier: # noqa: ARG002
return self
def predict(self, dataset: Table) -> TaggedTable:
# Needed until https://github.com/Safe-DS/Stdlib/issues/75 is fixed
predicted = dataset.get_column("predicted")
feature = predicted.rename("feature")
dataset = Table.from_columns([feature, predicted])
return dataset.tag_columns(target_name="predicted")
def is_fitted(self) -> bool:
return True
def _get_sklearn_classifier(self) -> ClassifierMixin:
pass
class TestAccuracy:
def test_with_same_type(self) -> None:
table = Table(
{
"predicted": [1, 2, 3, 4],
"expected": [1, 2, 3, 3],
},
).tag_columns(target_name="expected")
assert DummyClassifier().accuracy(table) == 0.75
def test_with_different_types(self) -> None:
table = Table(
{
"predicted": ["1", "2", "3", "4"],
"expected": [1, 2, 3, 3],
},
).tag_columns(target_name="expected")
assert DummyClassifier().accuracy(table) == 0.0
@pytest.mark.parametrize(
"table",
[
Table(
{
"a": [1.0, 0.0, 0.0, 0.0],
"b": [0.0, 1.0, 1.0, 0.0],
"c": [0.0, 0.0, 0.0, 1.0],
},
),
],
ids=["untagged_table"],
)
def test_should_raise_if_table_is_not_tagged(self, table: Table) -> None:
with pytest.raises(UntaggedTableError):
DummyClassifier().accuracy(table) # type: ignore[arg-type]
class TestPrecision:
def test_should_compare_result(self) -> None:
table = Table(
{
"predicted": [1, 1, 0, 2],
"expected": [1, 0, 1, 2],
},
).tag_columns(target_name="expected")
assert DummyClassifier().precision(table, 1) == 0.5
def test_should_compare_result_with_different_types(self) -> None:
table = Table(
{
"predicted": [1, "1", "0", "2"],
"expected": [1, 0, 1, 2],
},
).tag_columns(target_name="expected")
assert DummyClassifier().precision(table, 1) == 1.0
def test_should_return_1_if_never_expected_to_be_positive(self) -> None:
table = Table(
{
"predicted": ["lol", "1", "0", "2"],
"expected": [1, 0, 1, 2],
},
).tag_columns(target_name="expected")
assert DummyClassifier().precision(table, 1) == 1.0
@pytest.mark.parametrize(
"table",
[
Table(
{
"a": [1.0, 0.0, 0.0, 0.0],
"b": [0.0, 1.0, 1.0, 0.0],
"c": [0.0, 0.0, 0.0, 1.0],
},
),
],
ids=["untagged_table"],
)
def test_should_raise_if_table_is_not_tagged(self, table: Table) -> None:
with pytest.raises(UntaggedTableError):
DummyClassifier().precision(table) # type: ignore[arg-type]
class TestRecall:
def test_should_compare_result(self) -> None:
table = Table(
{
"predicted": [1, 1, 0, 2],
"expected": [1, 0, 1, 2],
},
).tag_columns(target_name="expected")
assert DummyClassifier().recall(table, 1) == 0.5
def test_should_compare_result_with_different_types(self) -> None:
table = Table(
{
"predicted": [1, "1", "0", "2"],
"expected": [1, 0, 1, 2],
},
).tag_columns(target_name="expected")
assert DummyClassifier().recall(table, 1) == 0.5
def test_should_return_1_if_never_expected_to_be_positive(self) -> None:
table = Table(
{
"predicted": ["lol", "1", "0", "2"],
"expected": [2, 0, 5, 2],
},
).tag_columns(target_name="expected")
assert DummyClassifier().recall(table, 1) == 1.0
@pytest.mark.parametrize(
"table",
[
Table(
{
"a": [1.0, 0.0, 0.0, 0.0],
"b": [0.0, 1.0, 1.0, 0.0],
"c": [0.0, 0.0, 0.0, 1.0],
},
),
],
ids=["untagged_table"],
)
def test_should_raise_if_table_is_not_tagged(self, table: Table) -> None:
with pytest.raises(UntaggedTableError):
DummyClassifier().recall(table) # type: ignore[arg-type]
class TestF1Score:
def test_should_compare_result(self) -> None:
table = Table(
{
"predicted": [1, 1, 0, 2],
"expected": [1, 0, 1, 2],
},
).tag_columns(target_name="expected")
assert DummyClassifier().f1_score(table, 1) == 0.5
def test_should_compare_result_with_different_types(self) -> None:
table = Table(
{
"predicted": [1, "1", "0", "2"],
"expected": [1, 0, 1, 2],
},
).tag_columns(target_name="expected")
assert DummyClassifier().f1_score(table, 1) == pytest.approx(0.6666667)
def test_should_return_1_if_never_expected_or_predicted_to_be_positive(self) -> None:
table = Table(
{
"predicted": ["lol", "1", "0", "2"],
"expected": [2, 0, 2, 2],
},
).tag_columns(target_name="expected")
assert DummyClassifier().f1_score(table, 1) == 1.0
@pytest.mark.parametrize(
"table",
[
Table(
{
"a": [1.0, 0.0, 0.0, 0.0],
"b": [0.0, 1.0, 1.0, 0.0],
"c": [0.0, 0.0, 0.0, 1.0],
},
),
],
ids=["untagged_table"],
)
def test_should_raise_if_table_is_not_tagged(self, table: Table) -> None:
with pytest.raises(UntaggedTableError):
DummyClassifier().f1_score(table) # type: ignore[arg-type]