forked from EpistasisLab/tpot
/
tests.py
1033 lines (689 loc) · 38.8 KB
/
tests.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
"""
Unit tests for TPOT.
"""
from tpot import TPOT
from tpot.export_utils import generate_import_code, replace_function_calls, unroll_nested_fuction_calls
from tpot.decorators import _gp_new_generation
import pandas as pd
import numpy as np
from collections import Counter
import warnings
import inspect
from sklearn.datasets import load_digits
from sklearn.cross_validation import train_test_split
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, ExtraTreesClassifier, GradientBoostingClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import LinearSVC
from sklearn.linear_model import LogisticRegression, PassiveAggressiveClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import BernoulliNB, GaussianNB, MultinomialNB
from sklearn.feature_selection import RFE, SelectPercentile, f_classif, SelectKBest, SelectFwe, VarianceThreshold
from deap import creator
from tqdm import tqdm
# Set up the MNIST data set for testing
mnist_data = load_digits()
training_features, testing_features, training_classes, testing_classes =\
train_test_split(mnist_data.data, mnist_data.target, random_state=42)
training_data = pd.DataFrame(training_features)
training_data['class'] = training_classes
training_data['group'] = 'training'
testing_data = pd.DataFrame(testing_features)
testing_data['class'] = 0
testing_data['group'] = 'testing'
training_testing_data = pd.concat([training_data, testing_data])
most_frequent_class = Counter(training_classes).most_common(1)[0][0]
training_testing_data['guess'] = most_frequent_class
for column in training_testing_data.columns.values:
if type(column) != str:
training_testing_data.rename(columns={column: str(column).zfill(5)}, inplace=True)
def test_init():
"""Ensure that the TPOT instantiator stores the TPOT variables properly"""
def dummy_scoring_func(foo, bar):
return
tpot_obj = TPOT(population_size=500, generations=1000, scoring_function=dummy_scoring_func,
mutation_rate=0.05, crossover_rate=0.9, verbosity=1, random_state=42,
disable_update_check=True)
assert tpot_obj.population_size == 500
assert tpot_obj.generations == 1000
assert tpot_obj.mutation_rate == 0.05
assert tpot_obj.crossover_rate == 0.9
assert tpot_obj.verbosity == 1
assert tpot_obj.update_checked is True
assert tpot_obj._optimized_pipeline is None
assert tpot_obj._training_classes is None
assert tpot_obj._training_features is None
assert tpot_obj.scoring_function == dummy_scoring_func
assert tpot_obj._pset
assert tpot_obj.non_feature_columns
def test_unroll_nested():
"""Ensure that export utils' unroll_nested_fuction_calls outputs pipeline_list as expected"""
tpot_obj = TPOT()
expected_list = [['result1', '_logistic_regression', 'input_df', '1.0', '0', 'True']]
pipeline = creator.Individual.\
from_string('_logistic_regression(input_df, 1.0, 0, True)', tpot_obj._pset)
pipeline_list = unroll_nested_fuction_calls(pipeline)
assert expected_list == pipeline_list
def test_unroll_nested_2():
"""Ensure that export utils' unroll_nested_fuction_calls outputs pipelines with nested function calls as expectd"""
tpot_obj = TPOT()
expected_list = [['result1', '_select_percentile', 'input_df', '40'], ['result2', '_extra_trees', 'result1', '32', '0.62', '0.45']]
pipeline = creator.Individual.\
from_string('_extra_trees(_select_percentile(input_df, 40), 32, 0.62, 0.45000000000000001)', tpot_obj._pset)
pipeline_list = unroll_nested_fuction_calls(pipeline)
assert expected_list == pipeline_list
def test_generate_import_code():
"""Ensure export utils' generate_import_code outputs as expected"""
reference_code = """\
import numpy as np
import pandas as pd
from sklearn.cross_validation import train_test_split
from sklearn.decomposition import RandomizedPCA
from sklearn.feature_selection import VarianceThreshold
from sklearn.linear_model import LogisticRegression
# NOTE: Make sure that the class is labeled 'class' in the data file
tpot_data = pd.read_csv('PATH/TO/DATA/FILE', sep='COLUMN_SEPARATOR')
training_indices, testing_indices = train_test_split(tpot_data.index, stratify = tpot_data['class'].values, train_size=0.75, test_size=0.25)
"""
pipeline = [['result1', '_variance_threshold', 'input_df', '100.0'],
['result2', '_pca', 'input_df', '66', '34'],
['result3', '_combine_dfs', 'result2', 'result1'],
['result4', '_logistic_regression', 'result3', '0.12030075187969924', '0', 'True']]
import_code = generate_import_code(pipeline)
assert reference_code == import_code
def test_generate_import_code_2():
"""Ensure export utils' generate_import_code outputs as expected when using multiple classes from the same module"""
reference_code = """\
import numpy as np
import pandas as pd
from sklearn.cross_validation import train_test_split
from sklearn.decomposition import FastICA, RandomizedPCA
from sklearn.linear_model import LogisticRegression
# NOTE: Make sure that the class is labeled 'class' in the data file
tpot_data = pd.read_csv('PATH/TO/DATA/FILE', sep='COLUMN_SEPARATOR')
training_indices, testing_indices = train_test_split(tpot_data.index, stratify = tpot_data['class'].values, train_size=0.75, test_size=0.25)
"""
pipeline = [['result1', '_fast_ica', 'input_df', '5', '0.1'],
['result2', '_pca', 'input_df', '66', '34'],
['result3', '_combine_dfs', 'result2', 'result1'],
['result4', '_logistic_regression', 'result3', '0.12030075187969924', '0', 'True']]
import_code = generate_import_code(pipeline)
assert reference_code == import_code
def test_replace_function_calls():
"""Ensure export utils' replace_function_calls outputs as expected"""
reference_code = """
result1 = tpot_data.copy()
# Use Scikit-learn's SelectKBest for feature selection
training_features = result1.loc[training_indices].drop('class', axis=1)
training_class_vals = result1.loc[training_indices, 'class'].values
if len(training_features.columns.values) == 0:
result1 = result1.copy()
else:
selector = SelectKBest(f_classif, k=min(26, len(training_features.columns)))
selector.fit(training_features.values, training_class_vals)
mask = selector.get_support(True)
mask_cols = list(training_features.iloc[:, mask].columns) + ['class']
result1 = result1[mask_cols]
# Perform classification with a decision tree classifier
dtc2 = DecisionTreeClassifier(min_weight_fraction_leaf=0.1)
dtc2.fit(result1.loc[training_indices].drop('class', axis=1).values, result1.loc[training_indices, 'class'].values)
result2 = result1.copy()
result2['dtc2-classification'] = dtc2.predict(result2.drop('class', axis=1).values)
"""
pipeline = [['result1', '_select_kbest', 'input_df', '26'],
['result2', '_decision_tree', 'result1', '0.1']]
exported_code = replace_function_calls(pipeline)
assert reference_code == exported_code
def test_replace_function_calls_2():
"""Ensure export utils' replace_function_calls generates no exceptions"""
tpot_obj = TPOT()
for prim in tpot_obj._pset.primitives[pd.DataFrame]:
simple_pipeline = ['result1']
simple_pipeline.append(prim.name)
for arg in prim.args:
simple_pipeline.append(tpot_obj._pset.terminals[arg][0].value)
replace_function_calls([simple_pipeline])
def test_get_params():
"""Ensure that get_params returns the exact dictionary of parameters used by TPOT"""
kwargs = {
'population_size': 500,
'generations': 1000,
'verbosity': 1
}
tpot_obj = TPOT(**kwargs)
# Get default parameters of TPOT and merge with our specified parameters
initializer = inspect.getargspec(TPOT.__init__)
default_kwargs = dict(zip(initializer.args[1:], initializer.defaults))
default_kwargs.update(kwargs)
assert tpot_obj.get_params() == default_kwargs
def test_decision_tree():
"""Ensure that the TPOT decision tree method outputs the same as the sklearn decision tree"""
tpot_obj = TPOT()
result = tpot_obj._decision_tree(training_testing_data, 0.1)
result = result[result['group'] == 'testing']
dtc = DecisionTreeClassifier(min_weight_fraction_leaf=0.1, random_state=42)
dtc.fit(training_features, training_classes)
assert np.array_equal(result['guess'].values, dtc.predict(testing_features))
def test_decision_tree_2():
"""Ensure that the TPOT decision tree method outputs the same as the sklearn decision tree when min_weight=0"""
tpot_obj = TPOT()
result = tpot_obj._decision_tree(training_testing_data, 0.)
result = result[result['group'] == 'testing']
dtc = DecisionTreeClassifier(min_weight_fraction_leaf=0., random_state=42)
dtc.fit(training_features, training_classes)
assert np.array_equal(result['guess'].values, dtc.predict(testing_features))
def test_decision_tree_3():
"""Ensure that the TPOT decision tree method outputs the same as the sklearn decision tree when min_weight>0.5"""
tpot_obj = TPOT()
result = tpot_obj._decision_tree(training_testing_data, 0.6)
result = result[result['group'] == 'testing']
dtc = DecisionTreeClassifier(min_weight_fraction_leaf=0.5, random_state=42)
dtc.fit(training_features, training_classes)
assert np.array_equal(result['guess'].values, dtc.predict(testing_features))
def test_random_forest():
"""Ensure that the TPOT random forest method outputs the same as the sklearn random forest when"""
tpot_obj = TPOT()
result = tpot_obj._random_forest(training_testing_data, 0.1)
result = result[result['group'] == 'testing']
rfc = RandomForestClassifier(n_estimators=500, min_weight_fraction_leaf=0.1, random_state=42, n_jobs=-1)
rfc.fit(training_features, training_classes)
assert np.array_equal(result['guess'].values, rfc.predict(testing_features))
def test_random_forest_2():
"""Ensure that the TPOT random forest method outputs the same as the sklearn random forest when min_weight>0.5"""
tpot_obj = TPOT()
result = tpot_obj._random_forest(training_testing_data, 0.6)
result = result[result['group'] == 'testing']
rfc = RandomForestClassifier(n_estimators=500, min_weight_fraction_leaf=0.5, random_state=42, n_jobs=-1)
rfc.fit(training_features, training_classes)
assert np.array_equal(result['guess'].values, rfc.predict(testing_features))
def test_logistic_regression():
"""Ensure that the TPOT logistic regression classifier outputs the same as the sklearn LogisticRegression"""
tpot_obj = TPOT()
result = tpot_obj._logistic_regression(training_testing_data, 5., 0, True)
result = result[result['group'] == 'testing']
lrc = LogisticRegression(C=5., penalty='l1', dual=False, random_state=42)
lrc.fit(training_features, training_classes)
assert np.array_equal(result['guess'].values, lrc.predict(testing_features))
def test_knnc():
"""Ensure that the TPOT k-nearest neighbor classifier outputs the same as the sklearn classifier"""
tpot_obj = TPOT()
result = tpot_obj._knnc(training_testing_data, 100, 0)
result = result[result['group'] == 'testing']
knnc = KNeighborsClassifier(n_neighbors=100, weights='uniform')
knnc.fit(training_features, training_classes)
assert np.array_equal(result['guess'].values, knnc.predict(testing_features))
def test_knnc_2():
"""Ensure that the TPOT k-nearest neighbor classifier outputs the same as the sklearn classifier when n_neighbor=0"""
tpot_obj = TPOT()
result = tpot_obj._knnc(training_testing_data, 0, 0)
result = result[result['group'] == 'testing']
knnc = KNeighborsClassifier(n_neighbors=2, weights='uniform')
knnc.fit(training_features, training_classes)
assert np.array_equal(result['guess'].values, knnc.predict(testing_features))
def test_train_model_and_predict():
"""Ensure that the TPOT train_model_and_predict returns the input dataframe when it has only 3 columns i.e. class, group, guess"""
tpot_obj = TPOT()
assert np.array_equal(training_testing_data.ix[:, -3:], tpot_obj._train_model_and_predict(training_testing_data.ix[:, -3:], LinearSVC, C=5., penalty='l1', dual=False))
def test_score():
"""Ensure that the TPOT score function raises a ValueError when no optimized pipeline exists"""
tpot_obj = TPOT()
try:
tpot_obj.score(testing_features, testing_classes)
assert False # Should be unreachable
except ValueError:
pass
def test_score_2():
"""Ensure that the TPOT score function outputs a known score for a fixed pipeline"""
tpot_obj = TPOT()
tpot_obj._training_classes = training_classes
tpot_obj._training_features = training_features
tpot_obj.pbar = tqdm(total=1, disable=True)
known_score = 0.981993770448 # Assumes use of the TPOT balanced_accuracy function
# Reify pipeline with known score
tpot_obj._optimized_pipeline = creator.Individual.\
from_string('_logistic_regression(input_df, 1.0, 0, True)', tpot_obj._pset)
# Get score from TPOT
score = tpot_obj.score(testing_features, testing_classes)
# http://stackoverflow.com/questions/5595425/
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
assert isclose(known_score, score)
def test_predict():
"""Ensure that the TPOT predict function raises a ValueError when no optimized pipeline exists"""
tpot_obj = TPOT()
try:
tpot_obj.predict(testing_features)
assert False # Should be unreachable
except ValueError:
pass
def test_predict_2():
"""Ensure that the TPOT predict function returns a DataFrame of shape (num_testing_rows,)"""
tpot_obj = TPOT()
tpot_obj._training_classes = training_classes
tpot_obj._training_features = training_features
tpot_obj._optimized_pipeline = creator.Individual.\
from_string('_logistic_regression(input_df, 1.0, 0, True)', tpot_obj._pset)
result = tpot_obj.predict(testing_features)
assert result.shape == (testing_features.shape[0],)
def test_export():
"""Ensure that the TPOT export function raises a ValueError when no optimized pipeline exists"""
tpot_obj = TPOT()
try:
tpot_obj.export('will_not_output')
assert False # Should be unreachable
except ValueError:
pass
def test_combine_dfs():
"""Check combine_dfs operator"""
tpot_obj = TPOT()
df1 = pd.DataFrame({'a': range(10),
'b': range(10, 20)})
df2 = pd.DataFrame({'b': range(10, 20),
'c': range(20, 30)})
combined_df = pd.DataFrame({'a': range(10),
'b': range(10, 20),
'c': range(20, 30)})
assert tpot_obj._combine_dfs(df1, df2).equals(combined_df)
def test_combine_dfs_2():
"""Check combine_dfs operator when the dataframes are equal"""
tpot_obj = TPOT()
df1 = pd.DataFrame({'a': range(10),
'b': range(10, 20)})
df2 = pd.DataFrame({'a': range(10),
'b': range(10, 20)})
combined_df = pd.DataFrame({'a': range(10),
'b': range(10, 20)})
assert tpot_obj._combine_dfs(df1, df2).equals(combined_df)
def test_rfe():
"""Ensure that the TPOT RFE outputs the input dataframe when no. of training features is 0"""
tpot_obj = TPOT()
assert np.array_equal(tpot_obj._rfe(training_testing_data.ix[:, -3:], 0, 0.1), training_testing_data.ix[:, -3:])
def test_rfe_2():
"""Ensure that the TPOT RFE outputs the same result as the sklearn rfe when num_features>no. of features in the dataframe """
tpot_obj = TPOT()
non_feature_columns = ['class', 'group', 'guess']
training_features = training_testing_data.loc[training_testing_data['group'] == 'training'].drop(non_feature_columns, axis=1)
estimator = LinearSVC()
rfe = RFE(estimator, 100, step=0.1)
rfe.fit(training_features, training_classes)
mask = rfe.get_support(True)
mask_cols = list(training_features.iloc[:, mask].columns) + non_feature_columns
assert np.array_equal(training_testing_data[mask_cols], tpot_obj._rfe(training_testing_data, 64, 0.1))
def test_select_percentile():
"""Ensure that the TPOT select percentile outputs the input dataframe when no. of training features is 0"""
tpot_obj = TPOT()
assert np.array_equal(tpot_obj._select_percentile(training_testing_data.ix[:, -3:], 0), training_testing_data.ix[:, -3:])
def test_select_percentile_2():
"""Ensure that the TPOT select percentile outputs the same result as sklearn Select Percentile when percentile < 0"""
tpot_obj = TPOT()
non_feature_columns = ['class', 'group', 'guess']
training_features = training_testing_data.loc[training_testing_data['group'] == 'training'].drop(non_feature_columns, axis=1)
training_class_vals = training_testing_data.loc[training_testing_data['group'] == 'training', 'class'].values
with warnings.catch_warnings():
warnings.simplefilter('ignore', category=UserWarning)
selector = SelectPercentile(f_classif, percentile=0)
selector.fit(training_features, training_class_vals)
mask = selector.get_support(True)
mask_cols = list(training_features.iloc[:, mask].columns) + non_feature_columns
assert np.array_equal(tpot_obj._select_percentile(training_testing_data, -1), training_testing_data[mask_cols])
def test_select_percentile_3():
"""Ensure that the TPOT select percentile outputs the same result as sklearn select percentile when percentile > 100"""
tpot_obj = TPOT()
non_feature_columns = ['class', 'group', 'guess']
training_features = training_testing_data.loc[training_testing_data['group'] == 'training'].drop(non_feature_columns, axis=1)
training_class_vals = training_testing_data.loc[training_testing_data['group'] == 'training', 'class'].values
with warnings.catch_warnings():
warnings.simplefilter('ignore', category=UserWarning)
selector = SelectPercentile(f_classif, percentile=100)
selector.fit(training_features, training_class_vals)
mask = selector.get_support(True)
mask_cols = list(training_features.iloc[:, mask].columns) + non_feature_columns
assert np.array_equal(tpot_obj._select_percentile(training_testing_data, 120), training_testing_data[mask_cols])
def test_select_percentile_4():
"""Ensure that the TPOT select percentile outputs the same result as sklearn select percentile when 0 < percentile < 100"""
tpot_obj = TPOT()
non_feature_columns = ['class', 'group', 'guess']
training_features = training_testing_data.loc[training_testing_data['group'] == 'training'].drop(non_feature_columns, axis=1)
training_class_vals = training_testing_data.loc[training_testing_data['group'] == 'training', 'class'].values
with warnings.catch_warnings():
warnings.simplefilter('ignore', category=UserWarning)
selector = SelectPercentile(f_classif, percentile=42)
selector.fit(training_features, training_class_vals)
mask = selector.get_support(True)
mask_cols = list(training_features.iloc[:, mask].columns) + non_feature_columns
assert np.array_equal(tpot_obj._select_percentile(training_testing_data, 42), training_testing_data[mask_cols])
def test_select_kbest():
"""Ensure that the TPOT select kbest outputs the input dataframe when no. of training features is 0"""
tpot_obj = TPOT()
assert np.array_equal(tpot_obj._select_kbest(training_testing_data.ix[:, -3:], 1), training_testing_data.ix[:, -3:])
def test_select_kbest_2():
"""Ensure that the TPOT select kbest outputs the same result as sklearn select kbest when k<0"""
tpot_obj = TPOT()
non_feature_columns = ['class', 'group', 'guess']
training_features = training_testing_data.loc[training_testing_data['group'] == 'training'].drop(non_feature_columns, axis=1)
training_class_vals = training_testing_data.loc[training_testing_data['group'] == 'training', 'class'].values
with warnings.catch_warnings():
warnings.simplefilter('ignore', category=UserWarning)
selector = SelectKBest(f_classif, k=1)
selector.fit(training_features, training_class_vals)
mask = selector.get_support(True)
mask_cols = list(training_features.iloc[:, mask].columns) + non_feature_columns
assert np.array_equal(tpot_obj._select_kbest(training_testing_data, -1), training_testing_data[mask_cols])
def test_select_kbest_3():
"""Ensure that the TPOT select kbest outputs the same result as sklearn select kbest when k> no. of features"""
tpot_obj = TPOT()
non_feature_columns = ['class', 'group', 'guess']
training_features = training_testing_data.loc[training_testing_data['group'] == 'training'].drop(non_feature_columns, axis=1)
training_class_vals = training_testing_data.loc[training_testing_data['group'] == 'training', 'class'].values
with warnings.catch_warnings():
warnings.simplefilter('ignore', category=UserWarning)
selector = SelectKBest(f_classif, k=64)
selector.fit(training_features, training_class_vals)
mask = selector.get_support(True)
mask_cols = list(training_features.iloc[:, mask].columns) + non_feature_columns
assert np.array_equal(tpot_obj._select_kbest(training_testing_data, 100), training_testing_data[mask_cols])
def test_select_kbest_4():
"""Ensure that the TPOT select kbest outputs the same result as sklearn select kbest when 0< k< features"""
tpot_obj = TPOT()
non_feature_columns = ['class', 'group', 'guess']
training_features = training_testing_data.loc[training_testing_data['group'] == 'training'].drop(non_feature_columns, axis=1)
training_class_vals = training_testing_data.loc[training_testing_data['group'] == 'training', 'class'].values
with warnings.catch_warnings():
warnings.simplefilter('ignore', category=UserWarning)
selector = SelectKBest(f_classif, k=42)
selector.fit(training_features, training_class_vals)
mask = selector.get_support(True)
mask_cols = list(training_features.iloc[:, mask].columns) + non_feature_columns
assert np.array_equal(tpot_obj._select_kbest(training_testing_data, 42), training_testing_data[mask_cols])
def test_select_fwe():
"""Ensure that the TPOT select fwe outputs the input dataframe when no. of training features is 0"""
tpot_obj = TPOT()
assert np.array_equal(tpot_obj._select_fwe(training_testing_data.ix[:, -3:], 0.005), training_testing_data.ix[:, -3:])
def test_select_fwe_2():
"""Ensure that the TPOT select fwe outputs the same result as sklearn fwe when alpha > 0.05"""
tpot_obj = TPOT()
non_feature_columns = ['class', 'group', 'guess']
training_features = training_testing_data.loc[training_testing_data['group'] == 'training'].drop(non_feature_columns, axis=1)
training_class_vals = training_testing_data.loc[training_testing_data['group'] == 'training', 'class'].values
with warnings.catch_warnings():
warnings.simplefilter('ignore', category=UserWarning)
selector = SelectFwe(f_classif, alpha=0.05)
selector.fit(training_features, training_class_vals)
mask = selector.get_support(True)
mask_cols = list(training_features.iloc[:, mask].columns) + non_feature_columns
assert np.array_equal(tpot_obj._select_fwe(training_testing_data, 1), training_testing_data[mask_cols])
def test_select_fwe_3():
"""Ensure that the TPOT select fwe outputs the same result as sklearn fwe when alpha < 0.001"""
tpot_obj = TPOT()
non_feature_columns = ['class', 'group', 'guess']
training_features = training_testing_data.loc[training_testing_data['group'] == 'training'].drop(non_feature_columns, axis=1)
training_class_vals = training_testing_data.loc[training_testing_data['group'] == 'training', 'class'].values
with warnings.catch_warnings():
warnings.simplefilter('ignore', category=UserWarning)
selector = SelectFwe(f_classif, alpha=0.001)
selector.fit(training_features, training_class_vals)
mask = selector.get_support(True)
mask_cols = list(training_features.iloc[:, mask].columns) + non_feature_columns
assert np.array_equal(tpot_obj._select_fwe(training_testing_data, 0.0001), training_testing_data[mask_cols])
def test_select_fwe_4():
"""Ensure that the TPOT select fwe outputs the same result as sklearn fwe when 0.001 < alpha < 0.05"""
tpot_obj = TPOT()
non_feature_columns = ['class', 'group', 'guess']
training_features = training_testing_data.loc[training_testing_data['group'] == 'training'].drop(non_feature_columns, axis=1)
training_class_vals = training_testing_data.loc[training_testing_data['group'] == 'training', 'class'].values
with warnings.catch_warnings():
warnings.simplefilter('ignore', category=UserWarning)
selector = SelectFwe(f_classif, alpha=0.042)
selector.fit(training_features, training_class_vals)
mask = selector.get_support(True)
mask_cols = list(training_features.iloc[:, mask].columns) + non_feature_columns
assert np.array_equal(tpot_obj._select_fwe(training_testing_data, 0.042), training_testing_data[mask_cols])
def test_variance_threshold():
"""Ensure that the tpot variance_threshold function behaves the same as the sklearn classifier"""
tpot_obj = TPOT()
non_feature_columns = ['class', 'group', 'guess']
training_features = training_testing_data.loc[training_testing_data['group'] == 'training'].drop(non_feature_columns, axis=1)
selector = VarianceThreshold(threshold=0)
selector.fit(training_features)
mask = selector.get_support(True)
mask_cols = list(training_features.iloc[:, mask].columns) + non_feature_columns
assert np.array_equal(tpot_obj._variance_threshold(training_testing_data, 0), training_testing_data[mask_cols])
def test_standard_scaler():
"""Ensure that the TPOT standard scaler outputs the input dataframe when no. of training features is 0"""
tpot_obj = TPOT()
assert np.array_equal(tpot_obj._standard_scaler(training_testing_data.ix[:, -3:]), training_testing_data.ix[:, -3:])
def test_robust_scaler():
"""Ensure that the TPOT robust scaler outputs the input dataframe when no. of training features is 0"""
tpot_obj = TPOT()
assert np.array_equal(tpot_obj._robust_scaler(training_testing_data.ix[:, -3:]), training_testing_data.ix[:, -3:])
def test_polynomial_features():
"""Ensure that the TPOT polynomial features outputs the input dataframe when no. of training features is 0"""
tpot_obj = TPOT()
assert np.array_equal(tpot_obj._polynomial_features(training_testing_data.ix[:, -3:]), training_testing_data.ix[:, -3:])
def test_min_max_scaler():
"""Ensure that the TPOT min max scaler outputs the input dataframe when no. of training features is 0"""
tpot_obj = TPOT()
assert np.array_equal(tpot_obj._min_max_scaler(training_testing_data.ix[:, -3:]), training_testing_data.ix[:, -3:])
def test_max_abs_scaler():
"""Ensure that the TPOT max abs scaler outputs the input dataframe when no. of training features is 0"""
tpot_obj = TPOT()
assert np.array_equal(tpot_obj._max_abs_scaler(training_testing_data.ix[:, -3:]), training_testing_data.ix[:, -3:])
def test_rbf():
"""Assert that the TPOT RBFSampler outputs the input dataframe when # of
training features is 0"""
tpot_obj = TPOT()
assert np.array_equal(tpot_obj._rbf(training_testing_data.ix[:, -3:], 0.1),
training_testing_data.ix[:, -3:])
def test_rbf_2():
"""Assert that RBF returns an object of the same type as the input dataframe
Also assert that the number of rows is identical between the input dataframe
and output dataframe.
"""
tpot_obj = TPOT()
input_df = training_testing_data
output_df = tpot_obj._rbf(input_df, 0.1)
assert type(input_df) == type(output_df)
(in_rows, in_cols) = input_df.shape
(out_rows, out_cols) = output_df.shape
assert in_rows == out_rows
def test_fast_ica():
"""Assert that the TPOT FastICA preprocessor outputs the input dataframe
when the number of training features is 0"""
tpot_obj = TPOT()
assert np.array_equal(tpot_obj._fast_ica(training_testing_data.ix[:, -3:], 1.0),
training_testing_data.ix[:, -3:])
def test_fast_ica_2():
"""Assert that FastICA returns the same object type as the input object type.
Also assert that the number of rows is identical between the input dataframe
and output dataframe.
"""
tpot_obj = TPOT()
input_df = training_testing_data
output_df = tpot_obj._fast_ica(input_df, 1.0)
assert type(input_df) == type(output_df)
(in_rows, in_cols) = input_df.shape
(out_rows, out_cols) = output_df.shape
assert in_rows == out_rows
def test_feat_agg():
"""Assert that the TPOT FeatureAgglomeration preprocessor outputs the input dataframe
when the number of training features is 0"""
tpot_obj = TPOT()
assert np.array_equal(tpot_obj._feat_agg(training_testing_data.ix[:, -3:], 5, 1, 1),
training_testing_data.ix[:, -3:])
def test_feat_agg_2():
"""Assert that FeatureAgglomeration returns the same object type as the input object type.
Also assert that the number of rows is identical between the input dataframe
and output dataframe.
"""
tpot_obj = TPOT()
input_df = training_testing_data
output_df = tpot_obj._feat_agg(input_df, 5, 1, 1)
assert type(input_df) == type(output_df)
(in_rows, in_cols) = input_df.shape
(out_rows, out_cols) = output_df.shape
assert in_rows == out_rows
def test_nystroem():
"""Assert that the TPOT Nystroem preprocessor outputs the input dataframe
when the number of training features is 0"""
tpot_obj = TPOT()
assert np.array_equal(tpot_obj._nystroem(training_testing_data.ix[:, -3:], 1, 0.1, 1),
training_testing_data.ix[:, -3:])
def test_nystroem_2():
"""Assert that Nystroem returns the same object type as the input object type.
Also assert that the number of rows is identical between the input dataframe
and output dataframe.
"""
tpot_obj = TPOT()
input_df = training_testing_data
output_df = tpot_obj._nystroem(input_df, 1, 0.1, 1)
assert type(input_df) == type(output_df)
(in_rows, in_cols) = input_df.shape
(out_rows, out_cols) = output_df.shape
assert in_rows == out_rows
def test_binarizer():
"""Ensure that the TPOT binarizer outputs the input dataframe when no. of training features is 0"""
tpot_obj = TPOT()
assert np.array_equal(tpot_obj._binarizer(training_testing_data.ix[:, -3:], 0), training_testing_data.ix[:, -3:])
def test_pca():
"""Ensure that the TPOT PCA outputs the input dataframe when no. of training features is 0"""
tpot_obj = TPOT()
assert np.array_equal(tpot_obj._pca(training_testing_data.ix[:, -3:], 1), training_testing_data.ix[:, -3:])
def test_zero_count():
"""Ensure that the TPOT _zero_count preprocessor outputs the input dataframe when no. of training features is 0"""
tpot_obj = TPOT()
assert np.array_equal(tpot_obj._zero_count(training_testing_data.ix[:, -3:]), training_testing_data.ix[:, -3:])
def test_zero_count_2():
"""Assert that the Zero Count preprocessor adds two columns to the dataframe"""
tpot_obj = TPOT()
input_df = training_testing_data
output_df = tpot_obj._zero_count(input_df)
assert type(input_df) == type(output_df)
(in_rows, in_cols) = input_df.shape
(out_rows, out_cols) = output_df.shape
assert in_rows == out_rows
assert in_cols == (out_cols - 2)
def test_ada_boost():
"""Ensure that the TPOT AdaBoostClassifier outputs the same as the sklearn AdaBoostClassifier"""
tpot_obj = TPOT()
result = tpot_obj._ada_boost(training_testing_data, 1.0)
result = result[result['group'] == 'testing']
adaboost = AdaBoostClassifier(n_estimators=500, random_state=42, learning_rate=1.0)
adaboost.fit(training_features, training_classes)
assert np.array_equal(result['guess'].values, adaboost.predict(testing_features))
def test_ada_boost_2():
"""Ensure that the TPOT AdaBoostClassifier outputs the same as the sklearn classifer when learning_rate == 0.0"""
tpot_obj = TPOT()
result = tpot_obj._ada_boost(training_testing_data, 0.0)
result = result[result['group'] == 'testing']
adaboost = AdaBoostClassifier(n_estimators=500, random_state=42, learning_rate=0.0001)
adaboost.fit(training_features, training_classes)
assert np.array_equal(result['guess'].values, adaboost.predict(testing_features))
def test_bernoulli_nb():
"""Ensure that the TPOT BernoulliNB outputs the same as the sklearn BernoulliNB"""
tpot_obj = TPOT()
result = tpot_obj._bernoulli_nb(training_testing_data, 1.0, 0.0)
result = result[result['group'] == 'testing']
bnb = BernoulliNB(alpha=1.0, binarize=0.0, fit_prior=True)
bnb.fit(training_features, training_classes)
assert np.array_equal(result['guess'].values, bnb.predict(testing_features))
def test_extra_trees():
"""Ensure that the TPOT ExtraTreesClassifier outputs the same as the sklearn ExtraTreesClassifier"""
tpot_obj = TPOT()
result = tpot_obj._extra_trees(training_testing_data, 0, 1., 0.1)
result = result[result['group'] == 'testing']
etc = ExtraTreesClassifier(n_estimators=500, random_state=42, max_features=1., min_weight_fraction_leaf=0.1, criterion='gini')
etc.fit(training_features, training_classes)
assert np.array_equal(result['guess'].values, etc.predict(testing_features))
def test_extra_trees_2():
"""Ensure that the TPOT ExtraTreesClassifier outputs the same as the sklearn version when max_features > 1"""
tpot_obj = TPOT()
result = tpot_obj._extra_trees(training_testing_data, 0, 2., 0.1)
result = result[result['group'] == 'testing']
etc = ExtraTreesClassifier(n_estimators=500, random_state=42, max_features=1., min_weight_fraction_leaf=0.1, criterion='gini')
etc.fit(training_features, training_classes)
assert np.array_equal(result['guess'].values, etc.predict(testing_features))
def test_extra_trees_3():
"""Ensure that the TPOT ExtraTreesClassifier outputs the same as the sklearn version when min_weight > 0.5"""
tpot_obj = TPOT()
result = tpot_obj._extra_trees(training_testing_data, 0, 1., 0.6)
result = result[result['group'] == 'testing']
etc = ExtraTreesClassifier(n_estimators=500, random_state=42, max_features=1., min_weight_fraction_leaf=0.5, criterion='gini')
etc.fit(training_features, training_classes)
assert np.array_equal(result['guess'].values, etc.predict(testing_features))
def test_gaussian_nb():
"""Ensure that the TPOT GaussianNB outputs the same as the sklearn GaussianNB"""
tpot_obj = TPOT()
result = tpot_obj._gaussian_nb(training_testing_data)
result = result[result['group'] == 'testing']
gnb = GaussianNB()
gnb.fit(training_features, training_classes)
assert np.array_equal(result['guess'].values, gnb.predict(testing_features))
def test_multinomial_nb():
"""Ensure that the TPOT MultinomialNB outputs the same as the sklearn MultinomialNB"""
tpot_obj = TPOT()
result = tpot_obj._multinomial_nb(training_testing_data, 1.0)
result = result[result['group'] == 'testing']
mnb = MultinomialNB(alpha=1.0, fit_prior=True)
mnb.fit(training_features, training_classes)
assert np.array_equal(result['guess'].values, mnb.predict(testing_features))
def test_linear_svc():
"""Ensure that the TPOT LinearSVC outputs the same as the sklearn LinearSVC"""
tpot_obj = TPOT()
result = tpot_obj._linear_svc(training_testing_data, 1.0, 0, True)
result = result[result['group'] == 'testing']
lsvc = LinearSVC(C=1.0, penalty='l1', dual=False, random_state=42)
lsvc.fit(training_features, training_classes)
assert np.array_equal(result['guess'].values, lsvc.predict(testing_features))
def test_linear_svc_2():
"""Ensure that the TPOT LinearSVC outputs the same as the sklearn LinearSVC when C == 0.0"""
tpot_obj = TPOT()
result = tpot_obj._linear_svc(training_testing_data, 0.0, 0, True)
result = result[result['group'] == 'testing']
lsvc = LinearSVC(C=0.0001, penalty='l1', dual=False, random_state=42)
lsvc.fit(training_features, training_classes)
assert np.array_equal(result['guess'].values, lsvc.predict(testing_features))
def test_passive_aggressive():
"""Ensure that the TPOT PassiveAggressiveClassifier outputs the same as the sklearn PassiveAggressiveClassifier"""
tpot_obj = TPOT()
result = tpot_obj._passive_aggressive(training_testing_data, 1.0, 0)
result = result[result['group'] == 'testing']
pagg = PassiveAggressiveClassifier(C=1.0, loss='hinge', fit_intercept=True, random_state=42)
pagg.fit(training_features, training_classes)
assert np.array_equal(result['guess'].values, pagg.predict(testing_features))
def test_passive_aggressive_2():
"""Ensure that the TPOT PassiveAggressiveClassifier outputs the same as the sklearn classifier when C == 0.0"""
tpot_obj = TPOT()
result = tpot_obj._passive_aggressive(training_testing_data, 0.0, 0)
result = result[result['group'] == 'testing']
pagg = PassiveAggressiveClassifier(C=0.0001, loss='hinge', fit_intercept=True, random_state=42)
pagg.fit(training_features, training_classes)
assert np.array_equal(result['guess'].values, pagg.predict(testing_features))
def test_gradient_boosting():
"""Ensure that the TPOT GradientBoostingClassifier outputs the same as the sklearn classifier"""
tpot_obj = TPOT()
result = tpot_obj._gradient_boosting(training_testing_data, 1.0, 1.0, 0.1)
result = result[result['group'] == 'testing']
gbc = GradientBoostingClassifier(learning_rate=1.0, max_features=1.0,
min_weight_fraction_leaf=0.1, n_estimators=500, random_state=42)
gbc.fit(training_features, training_classes)