-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathtest_commandline_utils.py
1905 lines (1605 loc) · 78.1 KB
/
test_commandline_utils.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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# License: BSD 3 clause
"""
Module for running unit tests related to command line utilities.
:author: Nitin Madnani (nmadnani@ets.org)
:author: Dan Blanchard (dblanchard@ets.org)
"""
import ast
import copy
import itertools
import logging
import sys
import unittest
from collections import defaultdict
from io import StringIO
from itertools import chain, combinations, product
from unittest.mock import create_autospec, patch
import numpy as np
import pandas as pd
import scipy as sp
from numpy import concatenate
from numpy.testing import assert_allclose, assert_array_almost_equal, assert_array_equal
from pandas.testing import assert_frame_equal
from sklearn.feature_extraction import FeatureHasher
from sklearn.linear_model import SGDClassifier, SGDRegressor
import skll
import skll.utils.commandline.compute_eval_from_predictions as cefp
import skll.utils.commandline.filter_features as ff
import skll.utils.commandline.generate_predictions as gp
import skll.utils.commandline.join_features as jf
import skll.utils.commandline.plot_learning_curves as plc
import skll.utils.commandline.print_model_weights as pmw
import skll.utils.commandline.run_experiment as rex
import skll.utils.commandline.skll_convert as sk
import skll.utils.commandline.summarize_results as sr
from skll.data import FeatureSet, LibSVMReader, LibSVMWriter, NDJWriter, safe_float
from skll.data.readers import EXT_TO_READER
from skll.data.writers import EXT_TO_WRITER
from skll.experiments import generate_learning_curve_plots, run_configuration
from skll.experiments.output import _write_summary_file
from skll.learner import Learner
from skll.utils.commandline.compute_eval_from_predictions import (
get_prediction_from_probabilities,
)
from skll.utils.testing import (
make_classification_data,
make_regression_data,
other_dir,
output_dir,
test_dir,
train_dir,
unlink,
)
class TestCommandlineUtils(unittest.TestCase):
"""Test class for commandline utility tests."""
@classmethod
def setUpClass(cls):
"""Create necessary directories for testing."""
for dir_path in [train_dir, test_dir, output_dir, other_dir / "features"]:
dir_path.mkdir(exist_ok=True)
@classmethod
def tearDownClass(cls):
"""Clean up after tests."""
for path in [
test_dir / "test_generate_predictions.jsonlines",
test_dir / "test_single_file_subset.jsonlines",
other_dir / "summary_file",
other_dir / "test_filter_features_input.arff",
output_dir / "test_generate_predictions.tsv",
output_dir / "train_test_single_file.log",
]:
unlink(path)
for filepath in chain(
output_dir.glob("test_print_model_weights.model*"),
output_dir.glob("test_generate_predictions.model*"),
output_dir.glob("pos_label_predict*"),
output_dir.glob("test_generate_predictions_console.model*"),
other_dir.glob("test_skll_convert*"),
other_dir.glob("test_join_features*"),
other_dir.glob("test_filter_features_labels*"),
other_dir.glob("features/features*"),
):
unlink(filepath)
def test_compute_eval_from_predictions(self):
"""Test compute_eval_from_predictions function console script."""
pred_path = other_dir / "test_compute_eval_from_predictions_predictions.tsv"
input_path = other_dir / "test_compute_eval_from_predictions.jsonlines"
# we need to capture stdout since that's what main() writes to
compute_eval_from_predictions_cmd = [
str(input_path),
str(pred_path),
"pearson",
"unweighted_kappa",
]
old_stdout = sys.stdout
old_stderr = sys.stderr
sys.stdout = mystdout = StringIO()
sys.stderr = mystderr = StringIO()
try:
cefp.main(compute_eval_from_predictions_cmd)
score_rows = mystdout.getvalue().strip().split("\n")
print(mystderr.getvalue())
finally:
sys.stdout = old_stdout
sys.stderr = old_stderr
scores = {}
for score_row in score_rows:
score, metric_name, pred_path = score_row.split("\t")
scores[metric_name] = float(score)
self.assertAlmostEqual(scores["pearson"], 0.6197797868009122)
self.assertAlmostEqual(scores["unweighted_kappa"], 0.2)
def test_warning_when_prediction_method_and_no_probabilities(self):
"""
Test for presence of warning.
Test compute_eval_from_predictions logs for a warning if a prediction method
is provided but the predictions file doesn't contain probabilities.
"""
log_capture_string = StringIO()
ch = logging.StreamHandler(log_capture_string)
ch.setLevel(logging.WARNING)
logger = logging.getLogger("skll.utils.commandline.compute_eval_from_predictions")
logger.addHandler(ch)
pred_path = other_dir / "test_compute_eval_from_predictions_predictions.tsv"
input_path = other_dir / "test_compute_eval_from_predictions.jsonlines"
# we need to capture stdout since that's what main() writes to
compute_eval_from_predictions_cmd = [
str(input_path),
str(pred_path),
"pearson",
"unweighted_kappa",
"--method",
"highest",
]
with patch("sys.stdout", new=StringIO()) as fake_out, patch(
"sys.stderr", new=StringIO()
) as fake_err:
cefp.main(compute_eval_from_predictions_cmd)
_ = fake_out.getvalue().strip().split("\n")
err = fake_err.getvalue()
print(err)
expected_log_msg = (
"A prediction method was provided, but the predictions file doesn't "
"contain probabilities. Ignoring prediction method 'highest'."
)
log_output = log_capture_string.getvalue().strip()
self.assertTrue(expected_log_msg in log_output)
def test_compute_eval_from_predictions_with_probs(self):
"""
Test `compute_eval_from_predictions` function console script.
This test uses probabilities in the predictions file.
"""
pred_path = other_dir / "test_compute_eval_from_predictions_probs_predictions.tsv"
input_path = other_dir / "test_compute_eval_from_predictions_probs.jsonlines"
# we need to capture stdout since that's what main() writes to
compute_eval_from_predictions_cmd = [
str(input_path),
str(pred_path),
"pearson",
"unweighted_kappa",
]
old_stdout = sys.stdout
old_stderr = sys.stderr
sys.stdout = mystdout = StringIO()
sys.stderr = mystderr = StringIO()
try:
cefp.main(compute_eval_from_predictions_cmd)
score_rows = mystdout.getvalue().strip().split("\n")
print(mystderr.getvalue())
finally:
sys.stdout = old_stdout
sys.stderr = old_stderr
scores = {}
for score_row in score_rows:
score, metric_name, pred_path = score_row.split("\t")
scores[metric_name] = float(score)
self.assertAlmostEqual(scores["pearson"], 0.6197797868009122)
self.assertAlmostEqual(scores["unweighted_kappa"], 0.2)
#
# Test expected value predictions method
#
compute_eval_from_predictions_cmd = [
str(input_path),
str(pred_path),
"explained_variance",
"r2",
"--method",
"expected_value",
]
old_stdout = sys.stdout
old_stderr = sys.stderr
sys.stdout = mystdout = StringIO()
sys.stderr = mystderr = StringIO()
try:
cefp.main(compute_eval_from_predictions_cmd)
score_rows = mystdout.getvalue().strip().split("\n")
print(mystderr.getvalue())
finally:
sys.stdout = old_stdout
sys.stderr = old_stderr
scores = {}
for score_row in score_rows:
score, metric_name, pred_path = score_row.split("\t")
scores[metric_name] = float(score)
self.assertAlmostEqual(scores["r2"], 0.19999999999999996)
self.assertAlmostEqual(scores["explained_variance"], 0.23809523809523792)
def test_compute_eval_from_predictions_breaks_with_expval_and_nonnumeric_classes(self):
"""
Make sure `compute_eval_from_predictions` raises ValueError for non-numeric classes.
This is when predictions are calculated via expected_value and the classes
are non numeric.
"""
pred_path = (
other_dir / "test_compute_eval_from_predictions_nonnumeric_classes_predictions.tsv"
)
input_path = other_dir / "test_compute_eval_from_predictions_nonnumeric_classes.jsonlines"
compute_eval_from_predictions_cmd = [
str(input_path),
str(pred_path),
"explained_variance",
"r2",
"--method",
"expected_value",
]
with self.assertRaises(ValueError):
cefp.main(compute_eval_from_predictions_cmd)
def test_conflicting_prediction_and_example_ids(self):
"""
Make sure `compute_eval_from_predictions` raises ValueError for mismatched IDs.
This is when predictions and examples don't have the same id set in
`compute_eval_from_predictions`.
"""
pred_path = other_dir / "test_compute_eval_from_predictions_probs_predictions.tsv"
input_path = other_dir / "test_compute_eval_from_predictions_different_ids.jsonlines"
compute_eval_from_predictions_cmd = [str(input_path), str(pred_path), "pearson"]
with self.assertRaises(ValueError):
cefp.main(compute_eval_from_predictions_cmd)
def test_compute_eval_from_predictions_random_choice(self):
"""Test that random selection of classes with the same probabilities works."""
classes = ["A", "B", "C", "D"]
probs = ["0.25", "0.25", "0.25", "0.25"]
prediction_method = "highest"
pred = get_prediction_from_probabilities(classes, probs, prediction_method)
self.assertEqual(pred, "C")
def _run_generate_predictions_and_capture_output(self, generate_cmd, output_file):
if output_file == "stdout":
# we need to capture stdout since that's what main() writes to
old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()
try:
gp.main(generate_cmd)
out = mystdout.getvalue()
output_lines = out.strip().split("\n")
finally:
sys.stdout = old_stdout
else:
unlink(output_file)
gp.main(generate_cmd)
with open(output_file) as outputfh:
output_lines = [line.strip() for line in outputfh.readlines()]
return output_lines
def check_generate_predictions(
self,
use_regression=False,
string_labels=False,
num_labels=2,
use_probability=False,
use_pos_label=False,
test_on_subset=False,
use_threshold=False,
predict_labels=False,
use_stdout=False,
multiple_input_files=False,
):
# create some simple classification feature sets for training and testing
if string_labels:
string_label_list = ["a", "b"] if num_labels == 2 else ["a", "b", "c", "d"]
else:
string_label_list = None
# generate the train and test featuresets
if use_regression:
pos_label = None
train_fs, test_fs, _ = make_regression_data(num_examples=100, num_features=5)
else:
train_fs, test_fs = make_classification_data(
num_examples=100,
num_features=5,
num_labels=num_labels,
string_label_list=string_label_list,
)
# get the sorted list of unique class labels
class_labels = np.unique(train_fs.labels).tolist()
# if we are using `pos_label`, then randomly pick a label
# as its value even for multi-class since we want to check that
# it properly gets ignored; we also instantiate variables in the
# binary case that contain the positive and negative class labels
# since we need those to process our expected predictions we
# are matching against
prng = np.random.RandomState(123456789)
if use_pos_label:
pos_label = prng.choice(class_labels, size=1)[0]
if num_labels == 2:
positive_class_label = pos_label
negative_class_label = [
label for label in class_labels if label != positive_class_label
][0]
class_labels = [negative_class_label, positive_class_label]
else:
pos_label = None
if num_labels == 2:
positive_class_label = class_labels[-1]
negative_class_label = [
label for label in class_labels if label != positive_class_label
][0]
# if we are asked to use only a subset, then filter out
# one of the features if we are not using feature hashing,
# do nothing if we are using feature hashing
if test_on_subset:
if use_regression:
test_fs.filter(features=["f1", "f2", "f3", "f4"])
else:
test_fs.filter(features=["f01", "f02", "f03", "f04"])
# write out the test set to disk so we can use it as a file
test_file = test_dir / "test_generate_predictions.jsonlines"
NDJWriter.for_path(test_file, test_fs).write()
# we need probabilities if we are using thresholds or label inference
enable_probability = any([use_probability, use_threshold, predict_labels])
# create a SKLL learner that is an SGDClassifier or an SGDRegressor,
# train it, and then save it to disk for use as a file
learner_name = "SGDRegressor" if use_regression else "SGDClassifier"
learner = Learner(learner_name, probability=enable_probability, pos_label=pos_label)
learner.train(train_fs, grid_search=False)
model_file = output_dir / "test_generate_predictions.model"
learner.save(model_file)
# now train equivalent sklearn estimators that we will use
# to get the expected predictions
if use_regression:
model = SGDRegressor(max_iter=1000, random_state=123456789, tol=1e-3)
else:
model = SGDClassifier(loss="log_loss", max_iter=1000, random_state=123456789, tol=1e-3)
model.fit(train_fs.features, train_fs.labels)
# get the predictions from this sklearn model on the test set
if test_on_subset:
xtest = learner.feat_vectorizer.transform(
test_fs.vectorizer.inverse_transform(test_fs.features)
)
else:
xtest = test_fs.features
if not (use_regression or predict_labels) and (use_threshold or use_probability):
predictions = model.predict_proba(xtest)
# since we are directly passing in the string labels to
# sklearn, it would sort the labels internally which
# may not match our expectation of having the positive
# class label probability last when doing binary
# classification so let's re-sort the sklearn predictions
sklearn_classes = model.classes_.tolist()
if num_labels == 2 and not np.all(model.classes_ == class_labels):
positive_class_index = sklearn_classes.index(positive_class_label)
negative_class_index = 1 - positive_class_index
predictions[:, [0, 1]] = predictions[
:, [negative_class_index, positive_class_index]
]
else:
predictions = model.predict(xtest)
# now start constructing the `generate_predictions` command
generate_cmd = ["-q"]
# if we asked for thresholded predictions
if use_threshold and not use_regression:
# append the threshold to the command
threshold = 0.6
generate_cmd.append("-t 0.6")
# threshold the expected predictions; note that
# since we have already reordered sklearn predictions
# we can just look at the second index to get the
# positive class probability
predictions = np.where(
predictions[:, 1] >= threshold, positive_class_label, negative_class_label
)
# if we asked to predict most likely labels
elif predict_labels and not use_regression:
# append the option to the command
generate_cmd.append("-p")
# are we using an output file or the console?
if not use_stdout:
output_file = output_dir / "test_generate_predictions.tsv"
generate_cmd.extend(["--output", str(output_file)])
else:
output_file = "stdout"
# append the model file to the command
generate_cmd.append(str(model_file))
# if we are using multiple input files, repeat the input file
# and, correspondingly, concatenate the expected predictions
if multiple_input_files:
predictions = concatenate([predictions, predictions])
generate_cmd.extend([str(test_file), str(test_file)])
else:
generate_cmd.append(str(test_file))
# run the constructed command and capture its output
gp_output_lines = self._run_generate_predictions_and_capture_output(
generate_cmd, output_file
)
# check the header first
generated_header = gp_output_lines[0].strip().split("\t")
if use_regression or not enable_probability or use_threshold or predict_labels:
expected_header = ["id", "prediction"]
else:
if num_labels == 2:
expected_header = ["id"] + [str(negative_class_label), str(positive_class_label)]
else:
expected_header = ["id"] + [str(x) for x in class_labels]
self.assertEqual(generated_header, expected_header)
# now check the ids, and predictions
for gp_line, expected_id, expected_prediction in zip(
gp_output_lines[1:], test_fs.ids, predictions
):
generated_fields = gp_line.strip().split("\t")
# comparing most likely labels
if len(generated_fields) == 2:
generated_id, generated_prediction = generated_fields[0], generated_fields[1]
self.assertEqual(generated_id, expected_id)
self.assertEqual(safe_float(generated_prediction), expected_prediction)
# comparing probabilities
else:
generated_id = generated_fields[0]
generated_prediction = list(map(safe_float, generated_fields[1:]))
self.assertEqual(generated_id, expected_id)
assert_array_almost_equal(generated_prediction, expected_prediction)
def test_generate_predictions(self):
for (
use_regression,
string_labels,
num_labels,
use_probability,
use_pos_label,
test_on_subset,
use_threshold,
predict_labels,
use_stdout,
multiple_input_files,
) in product(
[True, False],
[True, False],
[2, 4],
[True, False],
[True, False],
[True, False],
[True, False],
[True, False],
[True, False],
[True, False],
):
# skip testing conditions that will raise exceptions
# in `generate_predictions`
if (
use_threshold
and num_labels != 2
or use_threshold
and predict_labels
or use_regression
and string_labels
):
continue
yield (
self.check_generate_predictions,
use_regression,
string_labels,
num_labels,
use_probability,
use_pos_label,
test_on_subset,
use_threshold,
predict_labels,
use_stdout,
multiple_input_files,
)
def test_generate_predictions_console_bad_input_ext(self):
log_capture_string = StringIO()
ch = logging.StreamHandler(log_capture_string)
ch.setLevel(logging.ERROR)
logger = logging.getLogger("skll.utils.commandline.generate_predictions")
logger.addHandler(ch)
# create some simple classification data without feature hashing
train_fs, test_fs = make_classification_data(num_examples=1000, num_features=5)
# create a learner that uses an SGD classifier
learner = Learner("SGDClassifier")
# train the learner with grid search
learner.train(train_fs, grid_search=False)
# get the predictions on the test featureset
_ = learner.predict(test_fs)
# save the learner to a file
model_file = output_dir / "test_generate_predictions_console.model"
learner.save(model_file)
# now call main() from generate_predictions.py
generate_cmd = [str(model_file), "fake_input_file.txt"]
_ = self._run_generate_predictions_and_capture_output(generate_cmd, "stdout")
expected_log_msg = (
"Input file must be in either .arff, .csv, .jsonlines, .libsvm, .ndj, "
"or .tsv format. Skipping file fake_input_file.txt"
)
log_output = log_capture_string.getvalue().strip()
self.assertTrue(expected_log_msg in log_output)
def test_generate_predictions_threshold_not_trained_with_probability(self):
# create some simple classification data without feature hashing
train_fs, test_fs = make_classification_data(
num_examples=1000, num_features=5, num_labels=2
)
# save the test feature set to an NDJ file
input_file = test_dir / "test_generate_predictions.jsonlines"
writer = NDJWriter(input_file, test_fs)
writer.write()
# create a learner that uses an SGD classifier
learner = Learner("SGDClassifier")
# train the learner with grid search
learner.train(train_fs, grid_search=False)
# save the learner to a file
model_file = output_dir / "test_generate_predictions_console.model"
learner.save(model_file)
# now call main() from generate_predictions.py
generate_cmd = [str(model_file), str(input_file)]
generate_cmd.append("-t 0.6")
with self.assertRaises(ValueError):
gp.main(generate_cmd)
def test_generate_predictions_threshold_multi_class(self):
# create some simple classification data without feature hashing
train_fs, test_fs = make_classification_data(
num_examples=1000, num_features=5, num_labels=4
)
# save the test feature set to an NDJ file
input_file = test_dir / "test_generate_predictions.jsonlines"
writer = NDJWriter(input_file, test_fs)
writer.write()
# create a learner that uses an SGD classifier
learner = Learner("LogisticRegression", probability=True)
# train the learner with grid search
learner.train(train_fs, grid_search=False)
# save the learner to a file
model_file = output_dir / "test_generate_predictions_console.model"
learner.save(model_file)
# now call main() from generate_predictions.py
generate_cmd = [str(model_file), str(input_file)]
generate_cmd.append("-t 0.6")
with self.assertRaises(ValueError):
gp.main(generate_cmd)
def test_generate_predictions_threshold_non_probabilistic(self):
# create some simple classification data without feature hashing
train_fs, test_fs = make_classification_data(
num_examples=1000, num_features=5, num_labels=2
)
# save the test feature set to an NDJ file
input_file = test_dir / "test_generate_predictions.jsonlines"
writer = NDJWriter(input_file, test_fs)
writer.write()
# create a learner that uses an SGD classifier
learner = Learner("LinearSVC", probability=True)
# train the learner with grid search
learner.train(train_fs, grid_search=False)
# save the learner to a file
model_file = output_dir / "test_generate_predictions_console.model"
learner.save(model_file)
# now call main() from generate_predictions.py
generate_cmd = [str(model_file), str(input_file)]
generate_cmd.append("-t 0.6")
with self.assertRaises(ValueError):
gp.main(generate_cmd)
def test_generate_predictions_predict_labels_not_trained_with_probability(self):
# create some simple classification data without feature hashing
train_fs, test_fs = make_classification_data(
num_examples=1000, num_features=5, num_labels=2
)
# save the test feature set to an NDJ file
input_file = test_dir / "test_generate_predictions.jsonlines"
writer = NDJWriter(input_file, test_fs)
writer.write()
# create a learner that uses an SGD classifier
learner = Learner("SGDClassifier")
# train the learner with grid search
learner.train(train_fs, grid_search=False)
# save the learner to a file
model_file = output_dir / "test_generate_predictions_console.model"
learner.save(model_file)
# now call main() from generate_predictions.py
generate_cmd = [str(model_file), str(input_file)]
generate_cmd.append("-p")
with self.assertRaises(ValueError):
gp.main(generate_cmd)
def test_generate_predictions_predict_labels_non_probabilistic(self):
# create some simple classification data without feature hashing
train_fs, test_fs = make_classification_data(
num_examples=1000, num_features=5, num_labels=4
)
# save the test feature set to an NDJ file
input_file = test_dir / "test_generate_predictions.jsonlines"
writer = NDJWriter(input_file, test_fs)
writer.write()
# create a learner that uses an SGD classifier
learner = Learner("LinearSVC", probability=True)
# train the learner with grid search
learner.train(train_fs, grid_search=False)
# save the learner to a file
model_file = output_dir / "test_generate_predictions_console.model"
learner.save(model_file)
# now call main() from generate_predictions.py
generate_cmd = [str(model_file), str(input_file)]
generate_cmd.append("-p")
with self.assertRaises(ValueError):
gp.main(generate_cmd)
def test_mutually_exclusive_generate_predictions_args(self):
# create some simple classification data without feature hashing
train_fs, test_fs = make_classification_data(num_examples=1000, num_features=5)
threshold = 0.6
# save the test feature set to an NDJ file
input_file = test_dir / "test_generate_predictions.jsonlines"
writer = NDJWriter(input_file, test_fs)
writer.write()
# create a learner that uses an SGD classifier
learner = Learner("SGDClassifier")
# train the learner with grid search
learner.train(train_fs, grid_search=False)
# save the learner to a file
model_file = output_dir / "test_generate_predictions_console.model"
learner.save(model_file)
# now call main() from generate_predictions.py
generate_cmd = [f"-t {threshold}", "-p"]
generate_cmd.extend([str(model_file), str(input_file)])
with self.assertRaises(SystemExit):
gp.main(generate_cmd)
def check_skll_convert(self, from_suffix, to_suffix, id_type):
# create some simple classification data
orig_fs, _ = make_classification_data(
train_test_ratio=1.0, one_string_feature=True, id_type=id_type
)
# now write out this feature set in the given suffix
from_suffix_file = other_dir / f"test_skll_convert_{id_type}_ids_in{from_suffix}"
to_suffix_file = other_dir / f"test_skll_convert_{id_type}_ids_out{to_suffix}"
writer = EXT_TO_WRITER[from_suffix](from_suffix_file, orig_fs, quiet=True)
writer.write()
# now run skll convert to convert the featureset into the other format
skll_convert_cmd = [str(from_suffix_file), str(to_suffix_file), "--quiet"]
# we need to capture stderr to make sure we don't miss any errors
old_stderr = sys.stderr
sys.stderr = mystderr = StringIO()
try:
sk.main(skll_convert_cmd)
print(mystderr.getvalue())
finally:
sys.stderr = old_stderr
# now read the converted file and appropriately set `ids_to_floats`
# depending on the ID types that we generated earlier
ids_to_floats = True if id_type in ["float", "integer"] else False
reader = EXT_TO_READER[to_suffix](to_suffix_file, ids_to_floats=ids_to_floats, quiet=True)
converted_fs = reader.read()
# TODO : For now, we are converting feature arrays to dense, and then back to sparse.
# The reason for this is that scikit-learn DictVectorizers now retain any
# explicit zeros that are in files (e.g., in CSVs and TSVs). There's an issue
# open on scikit-learn: https://github.com/scikit-learn/scikit-learn/issues/14718
orig_fs.features = sp.sparse.csr_matrix(orig_fs.features.toarray())
converted_fs.features = sp.sparse.csr_matrix(converted_fs.features.toarray())
self.assertEqual(orig_fs, converted_fs)
def test_skll_convert(self):
for from_suffix, to_suffix in itertools.permutations(
[".arff", ".csv", ".jsonlines", ".libsvm", ".tsv"], 2
):
yield self.check_skll_convert, from_suffix, to_suffix, "string"
yield self.check_skll_convert, from_suffix, to_suffix, "integer_string"
yield self.check_skll_convert, from_suffix, to_suffix, "float"
yield self.check_skll_convert, from_suffix, to_suffix, "integer"
def test_skll_convert_libsvm_map(self):
"""Test to check whether the --reuse_libsvm_map option works for skll_convert."""
# create some simple classification data
orig_fs, _ = make_classification_data(train_test_ratio=1.0, one_string_feature=True)
# now write out this feature set as a libsvm file
orig_libsvm_file = other_dir / "test_skll_convert_libsvm_map.libsvm"
writer = LibSVMWriter(orig_libsvm_file, orig_fs, quiet=True)
writer.write()
# now make a copy of the dataset
swapped_fs = copy.deepcopy(orig_fs)
# now modify this new featureset to swap the first two columns
del swapped_fs.vectorizer.vocabulary_["f01"]
del swapped_fs.vectorizer.vocabulary_["f02"]
swapped_fs.vectorizer.vocabulary_["f01"] = 1
swapped_fs.vectorizer.vocabulary_["f02"] = 0
tmp = swapped_fs.features[:, 0]
swapped_fs.features[:, 0] = swapped_fs.features[:, 1]
swapped_fs.features[:, 1] = tmp
# now run skll_convert to convert this into a libsvm file
# but using the mapping specified in the first libsvm file
converted_libsvm_file = other_dir / "test_skll_convert_libsvm_map2.libsvm"
# now call skll convert's main function
skll_convert_cmd = [
"--reuse_libsvm_map",
str(orig_libsvm_file),
"--quiet",
str(orig_libsvm_file),
str(converted_libsvm_file),
]
old_stderr = sys.stderr
sys.stderr = mystderr = StringIO()
try:
sk.main(skll_convert_cmd)
print(mystderr.getvalue())
finally:
sys.stderr = old_stderr
# now read the converted libsvm file into a featureset
reader = LibSVMReader(converted_libsvm_file, quiet=True)
converted_fs = reader.read()
# now ensure that this new featureset and the original
# featureset are the same
self.assertEqual(orig_fs, converted_fs)
def test_skll_convert_no_labels_with_label_col(self):
"""Check that --no_labels/--label_col cannot both be specified for skll_convert."""
skll_convert_cmd = ["--no_labels", "--label_col", "t", "foo.tsv", "foo.libsvm"]
with self.assertRaises(SystemExit):
sk.main(argv=skll_convert_cmd)
def check_print_model_weights(self, task="classification", sort_by_labels=False): # noqa: C901
# create some simple classification or regression data
if task in ["classification", "classification_no_intercept"]:
train_fs, _ = make_classification_data(train_test_ratio=0.8)
elif task == "classification_with_hashing":
train_fs, _ = make_classification_data(
train_test_ratio=0.8, use_feature_hashing=True, feature_bins=10
)
elif task in ["multiclass_classification", "multiclass_classification_svc"]:
train_fs, _ = make_classification_data(train_test_ratio=0.8, num_labels=3)
elif task in [
"multiclass_classification_with_hashing",
"multiclass_classification_svc_with_hashing",
]:
train_fs, _ = make_classification_data(
train_test_ratio=0.8, num_labels=3, use_feature_hashing=True, feature_bins=10
)
elif task in [
"regression_with_hashing",
"regression_linearsvr_with_hashing",
"regression_svr_linear_with_hashing",
"regression_svr_linear_with_scaling_and_hashing",
]:
train_fs, _, _ = make_regression_data(
num_features=4, train_test_ratio=0.8, use_feature_hashing=True, feature_bins=2
)
else:
train_fs, _, _ = make_regression_data(num_features=4, train_test_ratio=0.8)
# now train the appropriate model
if task in [
"classification",
"classification_with_hashing",
"multiclass_classification",
"multiclass_classification_with_hashing",
]:
learner = Learner("LogisticRegression")
learner.train(train_fs, grid_search=True, grid_objective="f1_score_micro")
elif task in [
"multiclass_classification_svc",
"multiclass_classification_svc_with_hashing",
]:
learner = Learner("SVC", model_kwargs={"kernel": "linear"})
learner.train(train_fs, grid_search=True, grid_objective="f1_score_micro")
elif task == "classification_no_intercept":
learner = Learner("LogisticRegression")
learner.train(
train_fs,
grid_search=True,
grid_objective="f1_score_micro",
param_grid=[{"fit_intercept": [False]}],
)
elif task in ["regression", "regression_with_hashing"]:
learner = Learner("LinearRegression")
learner.train(train_fs, grid_search=True, grid_objective="pearson")
elif task in ["regression_linearsvr", "regression_linearsvr_with_hashing"]:
learner = Learner("LinearSVR")
learner.train(train_fs, grid_search=True, grid_objective="pearson")
elif task in ["regression_svr_linear", "regression_svr_linear_with_hashing"]:
learner = Learner("SVR", model_kwargs={"kernel": "linear"})
learner.train(train_fs, grid_search=True, grid_objective="pearson")
else:
learner = Learner("SVR", model_kwargs={"kernel": "linear"}, feature_scaling="both")
learner.train(train_fs, grid_search=True, grid_objective="pearson")
# now save the model to disk
model_file = output_dir / "test_print_model_weights.model"
learner.save(model_file)
# now call print_model_weights main() and capture the output
if sort_by_labels:
print_model_weights_cmd = [str(model_file), "--sort_by_labels"]
else:
print_model_weights_cmd = [str(model_file)]
old_stderr = sys.stderr
old_stdout = sys.stdout
sys.stderr = mystderr = StringIO()
sys.stdout = mystdout = StringIO()
try:
pmw.main(print_model_weights_cmd)
out = mystdout.getvalue()
print(mystderr.getvalue())
finally:
sys.stderr = old_stderr
sys.stdout = old_stdout
# now parse the output of the print_model_weight command
# and get the intercept and the feature values
if task in ["classification", "classification_with_hashing"]:
lines_to_parse = [l for l in out.split("\n")[1:] if l] # noqa: E741
intercept = safe_float(lines_to_parse[0].split("\t")[0])
feature_values = []
for ltp in lines_to_parse[1:]:
weight, _, feature_name = ltp.split("\t")
feature_values.append((feature_name, safe_float(weight)))
feature_values = [t[1] for t in sorted(feature_values)]
self.assertAlmostEqual(intercept, learner.model.intercept_[0])
assert_allclose(learner.model.coef_[0], feature_values)
elif task in ["multiclass_classification", "multiclass_classification_with_hashing"]:
# for multiple classes we get an intercept for each class
# as well as a list of weights for each class
lines_to_parse = [l for l in out.split("\n")[1:] if l] # noqa: E741
intercept = []
for intercept_string in lines_to_parse[0:3]:
intercept.append(safe_float(intercept_string.split("\t")[0]))
feature_values = [[], [], []]
for ltp in lines_to_parse[3:]:
weight, label, feature_name = ltp.split("\t")
feature_values[int(label)].append((feature_name, safe_float(weight)))
if sort_by_labels:
# making sure that the weights are sorted by label
# get the labels
labels_list = [line.split("\t")[1] for line in lines_to_parse[3:]]
# first test that the labels are sorted
assert labels_list == sorted(labels_list)
# then test that weights are sorted descending by absolute value
# for each label
for features_and_weights in feature_values:
feature_weights = [t[1] for t in features_and_weights]
assert feature_weights == sorted(feature_weights, key=lambda x: -abs(x))
for index, weights in enumerate(feature_values):
feature_values[index] = [t[1] for t in sorted(weights)]
for index, weights in enumerate(learner.model.coef_):
assert_array_almost_equal(weights, feature_values[index])
assert_array_almost_equal(intercept, learner.model.intercept_)
elif task in [
"multiclass_classification_svc",
"multiclass_classification_svc_with_hashing",
]:
# for multiple classes with the SVC with a linear kernel,
# we get an intercept for each class pair combination
# as well as a list of weights for each class pair
# combination
# save the computed intercept values in a dictionary
# with the class oair label as the key
lines_to_parse = [l for l in out.split("\n")[1:] if l] # noqa: E741
parsed_intercepts_dict = {}
for intercept_string in lines_to_parse[0:3]:
fields = intercept_string.split("\t")
parsed_intercepts_dict[fields[1]] = safe_float(fields[0])
# save the computed feature weights in a dictionary
# with the class pair label as the key and the value
# being a list; each feature weight for this class pair
# is stored at the index of the feature name as given
# by the feature vectorizer vocabulary dictionary
parsed_weights_dict = {}
for ltp in lines_to_parse[3:]:
(weight, class_pair, feature) = ltp.split("\t")
if class_pair not in parsed_weights_dict: