-
Notifications
You must be signed in to change notification settings - Fork 5
/
analysis.py
executable file
·1633 lines (1349 loc) · 61.3 KB
/
analysis.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
#!/usr/bin/env python3
"""
Analyze the results
./analysis.py | tee significance_tests.txt
"""
import os
import sys
import yaml
import pathlib
import collections
import numpy as np
import matplotlib.pyplot as plt
from absl import app
from absl import flags
from scipy import stats
from matplotlib.ticker import MaxNLocator
from pool import run_job_pool
from pickle_data import load_pickle, save_pickle
FLAGS = flags.FLAGS
flags.DEFINE_integer("jobs", 0, "Number of jobs to use for processing files (0 == number of cores)")
flags.DEFINE_bool("paper", False, "Whether to make paper-version plots (e.g. .pdf not .png), outputs to result_plots_paper")
flags.DEFINE_enum("metric", "accuracy", ["accuracy"], "Which metric to plot")
flags.DEFINE_enum("xaxis", "domains", ["uid", "weight", "domains"], "What to use as the x axis")
flags.DEFINE_bool("error_bars_over_runs_not_users", True, "How to compute error bars")
# Use nice names for the plots/tables
nice_method_names = {
"none": "No Adaptation",
"upper": "Train on Target",
"codats": "CoDATS",
"can": "CAN",
# No pseudo labeling - Random sampling
"calda_xs_r": "CALDA-XS,R",
"calda_in_r": "CALDA-In,R",
"calda_any_r": "CALDA-Any,R",
# No pseudo labeling - Hard sampling
"calda_xs_h": "CALDA-XS,H",
"calda_in_h": "CALDA-In,H",
"calda_any_h": "CALDA-Any,H",
# Pseudo labeling - Random sampling
"calda_xs_r_p": "CALDA-XS,R,P",
"calda_in_r_p": "CALDA-In,R,P",
"calda_any_r_p": "CALDA-Any,R,P",
# Pseudo labeling - Hard sampling
"calda_xs_h_p": "CALDA-XS,H,P",
"calda_in_h_p": "CALDA-In,H,P",
"calda_any_h_p": "CALDA-Any,H,P",
# Weak supervision
"codats_ws": "CoDATS-WS",
"calda_xs_h_ws": "CALDA-XS,H,WS",
"calda_any_r_ws": "CALDA-Any,R,WS",
# Domain generalization
"codats_dg": "CoDATS-DG",
"sleep_dg": "Sleep-DG",
"aflac_dg": "AFLAC-DG",
"caldg_xs_h": "CALDG-XS,H",
"caldg_any_r": "CALDG-Any,R",
# No adversary
"calda_xs_h_noadv": "CALDA-XS,H,NoAdv",
"calda_any_r_noadv": "CALDA-Any,R,NoAdv",
}
method_lines = {
# Approximate bounds
"none": "-.",
"upper": "-.",
# Prior work
"codats": "--",
}
nice_metric_names = {
"accuracy": "Accuracy (%)",
"f1score_macro": "F1 Score (Macro)",
}
dataset_replacements = [
("ucihar", "UCI HAR"),
("ucihhar", "UCI HHAR"),
("wisdm_ar", "WISDM AR"),
("wisdm_at", "WISDM AT"),
("ninapro_db5_like_myo_noshift", "NinaPro Myo"),
("myo", "Myo EMG"),
# Synthetic datasets
("normal_n12_l3_inter0_intra1_5,0,0,0_sine", "Synth InterT 0"),
("normal_n12_l3_inter1_intra1_5,0,0,0_sine", "Synth InterT 5"),
("normal_n12_l3_inter2_intra1_5,0,0,0_sine", "Synth InterT 10"),
("normal_n12_l3_inter0_intra1_0,0.5,0,0_sine", "Synth InterR 0"),
("normal_n12_l3_inter1_intra1_0,0.5,0,0_sine", "Synth InterR 0.5"),
("normal_n12_l3_inter2_intra1_0,0.5,0,0_sine", "Synth InterR 1.0"),
("normal_n12_l3_inter1_intra0_0,0,5,0_sine", "Synth IntraT 0"),
("normal_n12_l3_inter1_intra1_0,0,5,0_sine", "Synth IntraT 5"),
("normal_n12_l3_inter1_intra2_0,0,5,0_sine", "Synth IntraT 10"),
("normal_n12_l3_inter1_intra0_0,0,0,0.5_sine", "Synth IntraR 0"),
("normal_n12_l3_inter1_intra1_0,0,0,0.5_sine", "Synth IntraR 0.5"),
("normal_n12_l3_inter1_intra2_0,0,0,0.5_sine", "Synth IntraR 1.0"),
]
# Name of problem based on:
# (source_modality_subset, target_modality_subset, shared_modalities)
# Note: (x,) required for single elements to make sure these are tuples
problem_names = {
(None, None, (0, 1)): "Closed", # if subset is left as default
((0, 1), (0, 1), (0, 1)): "Closed", # if subset is specified
((0,), (0, 1), (0,)): "Open 1",
((1,), (1, 0), (0,)): "Open 2",
((0, 1), (0,), (0,)): "Partial 1",
((1, 0), (1,), (0,)): "Partial 2",
((0,), (0,), (0,)): "Single-Modality",
}
def get_tuning_files(dir_name, prefixes):
""" Get all the hyperparameter evaluation result files """
files = []
matching = []
for prefix in prefixes:
matching += pathlib.Path(dir_name).glob(prefix+".yaml")
for m in matching:
name = m.stem.replace(prefix, "")
file = str(m)
files.append((name, file))
return files
def compute_average(name, data, metric, domain, train_or_valid):
results = []
for d in data:
# Make sure this value exists in the evaluation results .yaml file
assert "results" in d, \
"No results in: " + str(d) + " for " + name
name_of_value = metric+"_task/"+domain+"/"+train_or_valid
assert name_of_value in d["results"], \
"No metric value " + name_of_value + " in: " + str(d["results"]) \
+ " for " + name
result = d["results"][name_of_value]
results.append(result)
# There should be 1 or 3 of each; if not, warn
length = len(results)
if length != 1 and length != 3:
print("Warning: number of runs ", length, "(not 1 or 3) for", name,
file=sys.stderr)
# ddof=0 is the numpy default, ddof=1 is Pandas' default
results = np.array(results, dtype=np.float32)
return results.mean(), results.std(ddof=0), results
def get_method(method, target):
"""
method="upper" doesn't actually exist since it uses method="none", but
our upper bound is method="none" without any target domains, so set
appropriately.
"""
if method == "none" and target == "":
method = "upper"
return method
def _all_stats(name, filename, source_feature_subset, target_feature_subset,
pickle=True):
# For speed, if we already loaded this and generated the pickle file,
# load that instead
if pickle:
pickle_filename = "{}.pickle".format(filename)
results = load_pickle(pickle_filename)
if results is not None:
return results
with open(filename) as f:
# See: https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation
data = yaml.load(f, Loader=yaml.SafeLoader)
# Get some of the config
uid = None
dataset = None
method = None
sources = None
target = None
source_modality_subset = None
target_modality_subset = None
shared_modalities = None
similarity_weight = None
has_results = False
if len(data) == 0:
print("Warning: no data in file", filename)
return {}
for d in data:
config = d["config"]
assert uid is None or config["uid"] == uid, \
"runs disagree on uid: " \
+ config["uid"] + " vs. " + str(uid)
uid = config["uid"]
assert dataset is None or config["dataset"] == dataset, \
"runs disagree on dataset: " \
+ config["dataset"] + " vs. " + str(dataset)
dataset = config["dataset"]
assert sources is None or config["sources"] == sources, \
"runs disagree on sources: " \
+ config["sources"] + " vs. " + str(sources)
sources = config["sources"]
assert target is None or config["target"] == target, \
"runs disagree on target: " \
+ config["target"] + " vs. " + str(target)
target = config["target"]
new_method = get_method(config["method"], target)
assert method is None or new_method == method, \
"runs disagree on method: " + new_method + " vs. " + str(method)
method = new_method
assert source_modality_subset is None or \
config["source_modality_subset"] == source_modality_subset, \
"runs disagree on source_modality_subset: " \
+ config["source_modality_subset"] + " vs. " + str(source_modality_subset)
source_modality_subset = config["source_modality_subset"]
assert target_modality_subset is None or \
config["target_modality_subset"] == target_modality_subset, \
"runs disagree on target_modality_subset: " \
+ config["target_modality_subset"] + " vs. " + str(target_modality_subset)
target_modality_subset = config["target_modality_subset"]
assert shared_modalities is None or \
config["shared_modalities"] == shared_modalities, \
"runs disagree on shared_modalities: " \
+ config["shared_modalities"] + " vs. " + str(shared_modalities)
shared_modalities = config["shared_modalities"]
assert similarity_weight is None or \
config["similarity_weight"] == similarity_weight, \
"runs disagree on similarity_weight: " \
+ config["similarity_weight"] + " vs. " + str(similarity_weight)
similarity_weight = config["similarity_weight"]
# Skip if not the right source/target features
current_source_feature_subset = config["source_feature_subset"]
current_target_feature_subset = config["target_feature_subset"]
if source_feature_subset is not None \
and source_feature_subset != current_source_feature_subset:
return {}
if target_feature_subset is not None \
and target_feature_subset != current_target_feature_subset:
return {}
if d["results"] != {}:
has_results = True
# Convert to lists of integers
if source_modality_subset == "":
source_modality_subset = None
else:
source_modality_subset = [int(x) for x in source_modality_subset.split(",")]
if target_modality_subset == "":
target_modality_subset = None
else:
target_modality_subset = [int(x) for x in target_modality_subset.split(",")]
shared_modalities = [int(x) for x in shared_modalities.split(",")]
# Also replace u0, etc. with just "0"
uid = int(uid.replace("u", ""))
# Identify problem based on modality subsets and shared modalities
# Note: convert list to tuple so it's hashable in dictionary
problem_name = problem_names[(
tuple(source_modality_subset) if source_modality_subset is not None else None,
tuple(target_modality_subset) if target_modality_subset is not None else None,
tuple(shared_modalities)
)]
results = {
"name": name,
"problem": problem_name,
"dataset": dataset,
"method": method,
"sources": sources,
"target": target,
"similarity_weight": similarity_weight,
"uid": uid,
# Full data if we need it
"data": data,
}
# For upper bound, there's no target, so instead use the "source" value
# as the "target" value
if method == "upper":
source_or_target = "source"
else:
source_or_target = "target"
# results["results_source_train"] = compute_average(name, data, FLAGS.metric, "source", "training")
# results["results_source_test"] = compute_average(name, data, FLAGS.metric, "source", "validation")
# results["results_target_train"] = compute_average(name, data, FLAGS.metric, "target", "training")
# Would error if we tried computing average with no data
if not has_results:
return {}
results["results_target_test"] = compute_average(name, data, FLAGS.metric, source_or_target, "validation")
# Cache results
if pickle:
save_pickle(pickle_filename, results)
return results
def all_stats(files, source_feature_subset, target_feature_subset,
show_progress=True):
""" Process all files, but since we may have many, many thousands, do it
with multiple cores by default """
if FLAGS.jobs == 1:
results = []
for name, filename in files:
results.append(_all_stats(name, filename,
source_feature_subset, target_feature_subset))
else:
commands = []
for name, filename in files:
commands.append((name, filename, source_feature_subset,
target_feature_subset))
jobs = FLAGS.jobs if FLAGS.jobs != 0 else None
results = run_job_pool(_all_stats, commands, cores=jobs,
show_progress=show_progress)
# Remove empty dictionaries (the "no data" cases)
results = [r for r in results if r != {}]
# Sort by name
results.sort(key=lambda x: x["name"])
return results
def get_results(run_suffixes, variant_match, source_feature_subset,
target_feature_subset, tune, folder="results", additional_match="*",
show_progress=True):
""" Get the right result files and load them """
prefixes = [
"results_"+run_suffix+"_"+variant_match+"-"+additional_match
for run_suffix in run_suffixes
]
files = get_tuning_files(folder, prefixes)
results = all_stats(files, source_feature_subset, target_feature_subset,
show_progress=show_progress)
# If there's multiple runs with different weights, we want to pick the
# result from the one with the best validation results, i.e. a grid search
# for hyperparameter tuning that variable
if tune:
results_grouped = collections.defaultdict(lambda: [])
for result in results:
results_grouped[(
result["problem"],
result["dataset"],
result["method"],
result["uid"],
# uid handles the unique sources/targets
#result["sources"],
#result["target"],
# We don't include this since we want to group by this
#result["similarity_weight"]
)].append(result)
tuned_results = []
for name, result in results_grouped.items():
if len(result) > 1:
# Find the one that had the highest max_accuracy, i.e. on the
# validation data performed the best
max_validation_accuracies = []
for r in result:
if len(r["data"]) > 1:
print("Warning: found multiple runs for a single weight? using first")
max_validation_accuracies.append(r["data"][0]["max_accuracy"])
max_accuracy = max(max_validation_accuracies)
index = max_validation_accuracies.index(max_accuracy)
# We'll use the results from that one
tuned_results.append(result[index])
else:
tuned_results.append(result[0])
return tuned_results
else:
return results
def gen_jitter(length, amount=0.04):
""" "Dodge" the points slightly on the x axis, so that they don't overlap """
x = []
value = -(amount/length)/2
for i in range(length):
x.append(value)
value += amount
return np.array(x, dtype=np.float32)
def export_legend(legend, dir_name=".", filename="key.pdf", expand=[-5, -5, 5, 5]):
""" See: https://stackoverflow.com/a/47749903 """
fig = legend.figure
fig.canvas.draw()
bbox = legend.get_window_extent()
bbox = bbox.from_extents(*(bbox.extents + np.array(expand)))
bbox = bbox.transformed(fig.dpi_scale_trans.inverted())
fig.savefig(os.path.join(dir_name, filename), dpi="figure", bbox_inches=bbox)
def make_replacements(s, replacements):
""" Make a bunch of replacements in a string """
if s is None:
return s
for before, after in replacements:
s = s.replace(before, after)
return s
def pretty_dataset_name(dataset_name):
""" Make dataset name look good for plots """
return make_replacements(dataset_name, dataset_replacements)
def average_over_n(results, error_bars_over_runs_not_users=False):
""" Average over multiple runs (values of n, the number of source domains)
- Recompute mean/stdev for those that have multiple entries
- Get rid of the n-specific dictionary
i.e. we go from:
results[dataset_name][method][n] = [
(n, mean, std), ...
]
to
averaged_results[dataset_name][method] = [
(n, mean, std), ...
]
"""
# averaged_results[dataset_name][method] = []
averaged_results = collections.defaultdict(
lambda: collections.defaultdict(list)
)
for dataset_name, v1 in results.items():
for method_name, v2 in v1.items():
new_values = []
for n, values in v2.items():
# Average over the multiple values here and recompute
# the standard deviation
if len(values) > 1:
values = np.array(values, dtype=np.float32)
if error_bars_over_runs_not_users:
# Average the errors of the per-user standard deviation
# over the multiple runs. This is instead of computing
# standard deviation over all runs with both varying
# target domain (user) and multiple runs -- which has
# an "error" conflating two separate aspects.
#
# Note: this applies only if we're averaging over users...
new_values.append((values[0, 0], values[:, 1].mean(),
values[:, 2].mean()))
else:
# All the 0th elements should be the same n
# Then recompute the mean/stdev from the accuracy values
# in 1th column
new_values.append((values[0, 0], values[:, 1].mean(),
values[:, 1].std(ddof=0)))
elif len(values) == 1:
# Leave as is if there's only one
values = np.array(values, dtype=np.float32)
new_values.append((values[0, 0], values[0, 1],
values[0, 2]))
else:
raise NotImplementedError("must be several or one run")
# Sort on n
new_values.sort(key=lambda x: x[0])
averaged_results[dataset_name][method_name] = \
np.array(new_values, dtype=np.float32)
return averaged_results
def process_results(results, average_over_users, ssda, upper_bound_offset,
tune, average_over_runs_per_user=True):
""" Get results - get the test mean/std results indexed by:
if not average, not ssda (i.e. msda):
results[dataset_name + " " + target][method]
if not average, ssda:
results[(dataset_name, source(s), target)][method]
if average, not ssda (i.e. msda):
results[dataset_name][method]
if average, ssda:
results[dataset_name][method]
Note: for example, dataset_name="ucihar", sources="1", target="2", and
method="dann".
"""
# results[dataset_name][method][n] = []
# Note: at the end we average over the "n" dictionary
processed_results = collections.defaultdict(
lambda: collections.defaultdict(
lambda: collections.defaultdict(list)
)
)
for result in results:
method_name = result["method"]
dataset_name = result["dataset"]
dataset_name = pretty_dataset_name(dataset_name)
# For single-source domain adaptation, we create a table for each
# source -> target pair, so we need index by that.
if (ssda and not average_over_users) or (not average_over_users and not average_over_runs_per_user):
dataset_name = (dataset_name, result["sources"], result["target"])
else:
if method_name == "upper":
dataset_name = (dataset_name, result["sources"])
else:
dataset_name = (dataset_name, result["target"])
# What we want the x axis to be...
if FLAGS.xaxis == "weight":
n = result["similarity_weight"]
elif FLAGS.xaxis == "uid":
if upper_bound_offset is not None and result["method"] == "upper":
n = result["uid"] + upper_bound_offset
else:
n = result["uid"]
elif FLAGS.xaxis == "domains":
n = len(result["sources"].split(",")) # number of source domains
else:
raise NotImplementedError("xaxis value needs to be weight or uid")
# We care about the target domain (note for the upper bound, we
# replaced the "target" value with "source" in _all_stats())
mean, std, all_values = result["results_target_test"]
processed_results[dataset_name][method_name][n].append(
(n, mean, std))
# Keep sorted by n
processed_results[dataset_name][method_name][n].sort(key=lambda x: x[0])
# Get rid of the n dictionary and average over the multiple values (should
# only be >1 if average_over_users==True)
processed_results = average_over_n(processed_results)
# How we compute error bars -- only applies if we're averaging over users
if average_over_users and FLAGS.error_bars_over_runs_not_users:
# Currently it's indexed by: results[(dataset_name, user)][method]
# Now we want to average over users for each dataset to get:
# results[dataset_name][method]
#
# We can easily do this (and reuse existing code) by converting to
# results[dataset_name][method][n] = [
# (n,mean,std) for user 1,
# (n,mean,std) for user 2, etc.
# ] and averaging over the users with average_over_n, but now setting
# error_bars_over_runs_not_users=True so we average the error over users
# rather than recomputing overall all users/runs.
new_processed_results = collections.defaultdict(
lambda: collections.defaultdict(
lambda: collections.defaultdict(list)
)
)
# Convert to results[(dataset_name,n)][method][user]
for (dataset_name, user), values1 in processed_results.items():
for method, values2 in values1.items():
# Actually, values2 is a numpy array, so we need to save
# [values3] to make sure average_over_n has a 2d array (not 1d)
for values3 in values2:
n = values3[0]
# we want all the user data in one array so that
# average_over_n will average over that
new_processed_results[dataset_name][method][n].append(values3)
# Average over users
processed_results = average_over_n(new_processed_results,
error_bars_over_runs_not_users=True)
return processed_results
def dictionary_sorted_keys(d):
keys = list(d.keys())
keys.sort()
return keys
def generate_plots(results, prefixes, save_plot=True, show_title=False,
legend_separate=True, suffix="pdf", dir_name="result_plots",
error_bars=True, figsize=(5, 3), skip=[], yrange=None,
integer_axis=False, ncol=1, jitter_amount=0.01,
x_is_percentage=False, y_is_percentage=True, title_suffix=""):
# See: https://matplotlib.org/3.1.1/api/markers_api.html
markers = ["o", "v", "^", "<", ">", "s", "p", "*", "D", "P", "X", "h",
"1", "2", "3", "4", "+", "x", "d", "H", "|", "_"] * 2
hollow = [False] * len(markers)
# e.g. if "baselines" and "modats1", then "baselines,modats1" will be the
# prefix
prefix = ",".join(prefixes)
# Do this sorted by name for a consistent ordering
for dataset_name in dictionary_sorted_keys(results):
dataset_values = results[dataset_name]
methods = dictionary_sorted_keys(dataset_values)
# Get data in order of the sorted methods
data = [dataset_values[m] for m in methods]
# Find min/max x values for scaling the jittering appropriately
max_x = -np.inf
min_x = np.inf
for i in range(len(data)):
method_data = np.array(data[i])
x = method_data[:, 0]
max_x = max(max(x), max_x)
min_x = min(min(x), min_x)
x_range = max_x - min_x
# "dodge" points so they don't overlap
jitter = gen_jitter(len(data), amount=jitter_amount*x_range)
fig, ax = plt.subplots(1, 1, figsize=figsize, dpi=100)
if yrange is not None:
ax.set_ylim(yrange)
# Only integers on x axis
# https://stackoverflow.com/a/38096332
if integer_axis:
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
for i in range(len(data)):
method_data = np.array(data[i])
x = method_data[:, 0] + jitter[i]
y = method_data[:, 1]
std = method_data[:, 2]
if x_is_percentage:
x *= 100
if y_is_percentage:
y *= 100
std *= 100
if methods[i] in skip:
continue
if methods[i] in nice_method_names:
method_name = nice_method_names[methods[i]]
else:
method_name = methods[i]
if methods[i] in method_lines:
line_type = method_lines[methods[i]]
else:
line_type = "-"
if hollow[i]:
mfc = "None"
else:
mfc = None
if error_bars:
p = plt.errorbar(x, y, yerr=std, label=method_name,
fmt=markers[i]+line_type, alpha=0.8, markerfacecolor=mfc)
else:
p = plt.plot(x, y, markers[i]+line_type, label=method_name,
alpha=0.8, markerfacecolor=mfc)
# Make a horizontal line at the upper bound since it doesn't matter
# what "n" is for this method (ignores the sources, only trains
# on target)
if methods[i] == "upper" and FLAGS.xaxis != "uid":
# xmin=1 since the upper bound is 1 source in a sense
assert method_lines[methods[i]] == "-.", \
"change linestyles in hlines to match that of method_lines[\"upper\"]"
ax.hlines(y=y, xmin=1, xmax=max_x, colors=p[0].get_color(),
linestyles="dashdot")
if show_title:
plt.title("Dataset: " + dataset_name + title_suffix)
if FLAGS.xaxis == "domains":
ax.set_xlabel("Number of source domains")
else:
ax.set_xlabel(FLAGS.xaxis)
ax.set_ylabel("Target Domain " + nice_metric_names[FLAGS.metric])
if legend_separate:
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
legend = plt.legend(loc="center left", bbox_to_anchor=(1, 0.5), ncol=ncol)
export_legend(legend, dir_name, filename=prefix+"_key."+suffix)
legend.remove()
else:
# Put legend outside the graph http://stackoverflow.com/a/4701285
# Shrink current axis by 20%
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
plt.legend(loc="center left", bbox_to_anchor=(1, 0.5), ncol=ncol)
if save_plot:
save_dataset_name = dataset_name.replace(" ", "_")
filename = prefix + "_" + save_dataset_name + "_" \
+ FLAGS.metric + "."+suffix
plt.savefig(os.path.join(dir_name, filename),
bbox_inches='tight')
plt.close()
if not save_plot:
plt.show()
def get_float(value):
""" Get float mean value (the part before plus/minus) from DDD.D $\pm$ DDD.D """
float_value = None
if len(value) > 0:
parts = value.split(" $\pm$ ")
if len(parts) == 1 or len(parts) == 2:
if "underline{" in parts[0]:
parts[0] = parts[0].replace("\\underline{", "")
parts[1] = parts[1].replace("?", "")
elif "textbf{" in parts[0]:
parts[0] = parts[0].replace("\\textbf{", "")
parts[1] = parts[1].replace("?", "")
float_value = float(parts[0])
return float_value
def replace_highest_better(values, references, better_text="textbf"):
""" Replace DDD.D $\pm$ DDD.D with \textbf{...} if higher than some column(s) """
# Get reference values first
reference_values = []
for i, v in enumerate(references):
reference_values.append(get_float(v))
# Modify if better than (or equal to) all reference values
if len(reference_values) > 0:
new_values = []
for i, v in enumerate(values):
float_value = get_float(v)
if float_value is not None and float_value >= max(reference_values):
new_values.append("\\" + better_text + "{"+v+"}")
else:
new_values.append(v)
return new_values
else:
return values
def replace_highest_best(values, best_text="textbf"):
""" Replace highest DDD.D $\pm$ DDD.D with \textbf{...} """
max_index = []
max_value = None
for i, v in enumerate(values):
float_value = get_float(v)
if float_value is not None:
if max_value is None or float_value > max_value:
max_value = float_value
max_index = [i]
elif float_value == max_value:
max_index.append(i)
if max_index is not None:
new_values = []
for i, v in enumerate(values):
if i in max_index:
new_values.append("\\" + best_text + "{"+v+"}")
else:
new_values.append(v)
return new_values
else:
return values
def write_table(output_filename, table, replace_best=None, best_bold=False,
replace_better=None, replace_better_ref=None, better_bold=False):
"""
Write Latex table to file,
- underline highest row if replace_best=(row_start, row_end) inclusive
- bold rows replace_better if better than all in replace_better_ref
"""
best_command = "textbf" if best_bold else "underline"
better_command = "textbf" if better_bold else "underline"
with open(output_filename, "w") as f:
max_columns = max([len(row) for row in table])
f.write("\\begin{tabular}{" + "c"*max_columns + "}\n")
for row in table:
# \hline's
if len(row) == 1:
f.write(row[0]+"\n")
continue
# Identify best between columns if desired
if replace_best is not None:
try:
row_start, row_end = replace_best
row[row_start:row_end+1] = replace_highest_best(
row[row_start:row_end+1], best_command)
except ValueError:
# If it's the header... ignore the error
pass
if replace_better is not None:
try:
row_start, row_end = replace_better
row_start_ref, row_end_ref = replace_better_ref
references = row[row_start_ref:row_end_ref+1]
row[row_start:row_end+1] = replace_highest_better(
row[row_start:row_end+1], references, better_command)
except ValueError:
# If it's the header... ignore the error
pass
for i, column in enumerate(row):
f.write(column+" ")
if i == len(row)-1:
f.write("\\\\\n")
else:
f.write("& ")
f.write("\\end{tabular}\n")
def generate_table(results, prefixes, output_filename, x_is_percentage=False,
y_is_percentage=True, skip=[], list_of_methods=None, list_of_datasets=None,
only_average=False, best_bold=False, better_bold=True,
skip_best=False, skip_better=False, average=True, average_datasets=False):
# indexed[dataset_name][n][method] = ""
indexed = collections.defaultdict(
lambda: collections.defaultdict(
lambda: collections.defaultdict(str)
)
)
# indexed_averaged_over_n[dataset_name][method] = []
# Note: exclude Train on Target since it's one value for all n -- would be
# the same averaged
indexed_averaged_over_n = collections.defaultdict(
lambda: collections.defaultdict(list)
)
# Since Train on Target is one per dataset, do this separately
# indexed_train_on_target[dataset_name] = ""
indexed_train_on_target = collections.defaultdict(str)
# indexed_average_over_datasets[method] = []
indexed_average_over_datasets = collections.defaultdict(list)
# If list of datasets isn't provided, then get the list of all of them,
# sorted for consistency
if list_of_datasets is None:
list_of_datasets = dictionary_sorted_keys(results)
for dataset_name in list_of_datasets:
dataset_values = results[dataset_name]
dataset_name = pretty_dataset_name(dataset_name)
methods = dictionary_sorted_keys(dataset_values)
# Get data in order of the sorted methods
data = [dataset_values[m] for m in methods]
for i in range(len(data)):
method_data = np.array(data[i])
x = method_data[:, 0]
y = method_data[:, 1]
std = method_data[:, 2]
if x_is_percentage:
x *= 100
if y_is_percentage:
y *= 100
std *= 100
if methods[i] in skip:
continue
if methods[i] in nice_method_names:
method_name = nice_method_names[methods[i]]
else:
method_name = methods[i]
if method_name == "Train on Target":
for j, n in enumerate(x):
assert j == 0 and n == 1, \
"should only be one Train on Target"
val = "{:.1f} $\\pm$ {:.1f}".format(y[j], std[j])
indexed_train_on_target[dataset_name] = val
indexed_average_over_datasets[method_name].append([y[j], std[j]])
else:
for j, n in enumerate(x):
val = "{:.1f} $\\pm$ {:.1f}".format(y[j], std[j])
indexed[dataset_name][str(int(n))][method_name] = val
indexed_averaged_over_n[dataset_name][method_name].append(
[y[j], std[j]])
indexed_average_over_datasets[method_name].append([y[j], std[j]])
#
# Create Latex table
#
if list_of_methods is None:
columns = ["No Adaptation", "CoDATS", "CALDA-Any,R", "CALDA-XS,H", "Train on Target"]
else:
columns = list_of_methods
prepend_columns = ["Dataset"]
if not only_average:
prepend_columns += ["$n$"]
fancy_columns = ["\\textit{"+c+"}" if "CALDA" in c else c for c in columns]
# Create table
table = []
table.append(["\\toprule"])
table.append(prepend_columns + fancy_columns)
table.append(["\\midrule"])
# Which datasets we want to include
dataset_names = [
dataset_name for dataset_name in indexed.keys()
if (list_of_datasets is None or dataset_name in list_of_datasets)
]
for i, dataset_name in enumerate(dataset_names):
values1 = indexed[dataset_name]
if not only_average:
# Row for each value of n
for n, values2 in values1.items():
thisrow = [dataset_name, n]
for method_name in columns:
if method_name == "Train on Target":
thisrow.append(indexed_train_on_target[dataset_name])
else:
if method_name in values2: