-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
2004 lines (1655 loc) · 69.4 KB
/
Copy pathutils.py
File metadata and controls
2004 lines (1655 loc) · 69.4 KB
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
import os
import json
import numpy as np
from typing import List, Dict, Tuple, Union
from sklearn.metrics import precision_recall_fscore_support, accuracy_score
import matplotlib.pyplot as plt
from collections import defaultdict, Counter
from sklearn.decomposition import PCA
from scipy import stats
from sklearn.manifold import TSNE
import random
from sklearn.preprocessing import MultiLabelBinarizer
import pandas as pd
import argparse
import re
from rouge_score import rouge_scorer, scoring
from pathlib import Path
from data import load_data
def extract_metric_values(json_path: str, metric_name: str = 'accuracy') -> Dict[str, List[float]]:
"""
Extract metric values for all budgets from a single method's JSON file.
Args:
json_path: Path to the JSON file.
metric_name: Name of the metric to extract.
Returns:
Dict mapping budget (float) to list of values across seeds.
"""
with open(json_path, 'r') as f:
data = json.load(f)
metrics_by_budget = {}
for seed_data in data:
first_method = list(seed_data.keys())[0]
for budget, metrics in seed_data[first_method].items():
budget_float = float(budget)
if budget_float not in metrics_by_budget:
metrics_by_budget[budget_float] = []
if metric_name in metrics:
metrics_by_budget[budget_float].append(metrics[metric_name])
return metrics_by_budget
def statistical_comparison_methods(
folder_path: str,
metric_names: List[str] = ['accuracy', 'precision', 'recall', 'f1'],
methods_to_ignore: List[str] = []
) -> pd.DataFrame:
"""
Perform pairwise statistical comparisons between all methods and Random baseline.
Uses t-tests, Mann-Whitney U tests, and computes Cohen's d effect sizes.
Applies Bonferroni correction for multiple comparisons.
Args:
folder_path: Path to folder containing JSON result files.
metric_names: List of metrics to compare.
methods_to_ignore: Method names to exclude from analysis.
Returns:
DataFrame with columns: method1, method2, metric, budget, means, stds,
p-values, effect sizes, and significance flags.
"""
mapping = get_mapping()
inverse_mapping = {v: k for k, v in mapping.items()}
# Load all methods
methods_data = {}
for json_file in os.listdir(folder_path):
if not json_file.endswith('.json'):
continue
method_name = decode_filename(json_file.replace('.json', ''), inverse_mapping)
if method_name in methods_to_ignore:
continue
json_path = os.path.join(folder_path, json_file)
methods_data[method_name] = json_path
if len(methods_data) < 2:
print(f"Not enough methods to compare in {folder_path}")
return None
# Perform pairwise comparisons
results = []
method_names_list = list(methods_data.keys())
method_names_list.remove('Random')
for i in range(len(method_names_list)):
method1_name = method_names_list[i]
method2_name = 'Random'
for metric_name in metric_names:
# Extract metrics for both methods
metrics1 = extract_metric_values(methods_data[method1_name], metric_name)
metrics2 = extract_metric_values(methods_data[method2_name], metric_name)
# Find common budgets
common_budgets = set(metrics1.keys()) & set(metrics2.keys())
for budget in sorted(common_budgets):
values1 = np.array(metrics1[budget])
values2 = np.array(metrics2[budget])
# Skip if not enough samples
if len(values1) < 2 or len(values2) < 2:
continue
# Calculate statistics
mean1, std1 = values1.mean(), values1.std()
mean2, std2 = values2.mean(), values2.std()
# T-test
if len(values1) == len(values2):
t_stat, p_value = stats.ttest_rel(values1, values2)
test_type = "paired"
else:
t_stat, p_value = stats.ttest_ind(values1, values2)
test_type = "unpaired"
# Mann-Whitney U test (non-parametric alternative)
try:
u_stat, u_pvalue = stats.mannwhitneyu(values1, values2, alternative='two-sided')
except ValueError:
u_stat, u_pvalue = np.nan, np.nan
# Cohen's d (effect size)
pooled_std = np.sqrt((std1**2 + std2**2) / 2)
cohens_d = (mean1 - mean2) / pooled_std if pooled_std > 0 else 0
# Determine effect size category
if abs(cohens_d) < 0.2:
effect_size = "negligible"
elif abs(cohens_d) < 0.5:
effect_size = "small"
elif abs(cohens_d) < 0.8:
effect_size = "medium"
else:
effect_size = "large"
results.append({
'method1': method1_name,
'method2': method2_name,
'metric': metric_name,
'budget': int(budget),
'mean1': mean1,
'std1': std1,
'mean2': mean2,
'std2': std2,
'difference': mean1 - mean2,
't_statistic': t_stat,
'p_value': p_value,
'u_statistic': u_stat,
'u_pvalue': u_pvalue,
'cohens_d': cohens_d,
'effect_size': effect_size,
'test_type': test_type,
'significant_005': p_value < 0.05,
'significant_001': p_value < 0.01,
})
if not results:
return None
df = pd.DataFrame(results)
# Apply Bonferroni correction
n_tests = len(df)
bonferroni_alpha = 0.05 / n_tests
df['bonferroni_significant'] = df['p_value'] < bonferroni_alpha
df['bonferroni_alpha'] = bonferroni_alpha
return df
def save_statistical_results(
df: pd.DataFrame,
folder_path: str,
dataset: str
) -> None:
"""
Save statistical comparison results to CSV and generate summary report.
Creates statistical_analysis directory with CSV results, text summary,
and LaTeX table of significant differences.
Args:
df: DataFrame with statistical results from statistical_comparison_methods.
folder_path: Path where to save results.
dataset: Dataset name for labeling outputs.
"""
if df is None or df.empty:
return
# Create output directory
parts = folder_path.split(os.sep)
if "synthetic" in folder_path:
distribution = parts[-2]
num_samples = parts[-1]
stats_dir = os.path.join(
folder_path.split('/')[0], "statistical_analysis",
dataset, distribution, num_samples
)
else:
num_samples = parts[-1]
stats_dir = os.path.join(
parts[0], parts[-4], "statistical_analysis",
dataset, num_samples
)
os.makedirs(stats_dir, exist_ok=True)
# Save full results
csv_path = os.path.join(stats_dir, "statistical_comparison.csv")
df.to_csv(csv_path, index=False)
# Generate and save summary
summary_path = os.path.join(stats_dir, "statistical_summary.txt")
with open(summary_path, 'w') as f:
f.write("=" * 80 + "\n")
f.write("STATISTICAL SIGNIFICANCE SUMMARY\n")
f.write("=" * 80 + "\n\n")
# Significant differences (p < 0.05)
sig_results = df[df['significant_005']].sort_values(['metric', 'budget'])
if not sig_results.empty:
f.write("SIGNIFICANT DIFFERENCES (p < 0.05):\n")
f.write("-" * 80 + "\n")
for _, row in sig_results.iterrows():
f.write(f"\n{row['metric'].upper()} at budget {row['budget']}:\n")
f.write(f" {row['method1']} vs {row['method2']}\n")
f.write(f" Mean difference: {row['difference']:.4f}\n")
f.write(f" p-value: {row['p_value']:.4f}\n")
f.write(f" Cohen's d: {row['cohens_d']:.4f} ({row['effect_size']})\n")
else:
f.write("No significant differences found at p < 0.05\n")
f.write("\n" + "=" * 80 + "\n\n")
# Bonferroni corrected results
bonf_results = df[df['bonferroni_significant']].sort_values(['metric', 'budget'])
if not bonf_results.empty:
f.write(f"BONFERRONI CORRECTED SIGNIFICANT DIFFERENCES (α = {df['bonferroni_alpha'].iloc[0]:.6f}):\n")
f.write("-" * 80 + "\n")
for _, row in bonf_results.iterrows():
f.write(f"\n{row['metric'].upper()} at budget {row['budget']}:\n")
f.write(f" {row['method1']} vs {row['method2']}\n")
f.write(f" Mean difference: {row['difference']:.4f}\n")
f.write(f" p-value: {row['p_value']:.6f}\n")
f.write(f" Cohen's d: {row['cohens_d']:.4f} ({row['effect_size']})\n")
else:
f.write("No significant differences after Bonferroni correction\n")
# Generate LaTeX table for significant results
generate_statistical_latex_table(df, stats_dir, dataset)
def generate_statistical_latex_table(
df: pd.DataFrame,
output_dir: str,
dataset: str
) -> None:
"""
Generate LaTeX table showing Bonferroni-corrected significant comparisons.
Args:
df: DataFrame with statistical results.
output_dir: Directory to save the .tex file.
dataset: Dataset name for table caption.
"""
sig_results = df[df['bonferroni_significant']].sort_values(['metric', 'budget'])
if sig_results.empty:
return
latex = "\\begin{table}[h]\n\\centering\n\\small\n"
latex += "\\begin{tabular}{llccccc}\n\\hline\n"
latex += "Metric & Budget & Method 1 & Method 2 & Diff. & p-value & Effect Size \\\\\n\\hline\n"
for _, row in sig_results.iterrows():
latex += f"{row['metric']} & {int(row['budget'])} & "
latex += f"{row['method1']:.10s} & {row['method2']:.10s} & "
latex += f"{row['difference']:.3f} & {row['p_value']:.4f} & "
latex += f"{row['effect_size']} \\\\\n"
latex += "\\hline\n\\end{tabular}\n"
latex += f"\\caption{{Statistically significant differences for {dataset} "
latex += f"(Bonferroni corrected, $\\alpha = {sig_results['bonferroni_alpha'].iloc[0]:.4f}$)}}\n"
latex += f"\\label{{tab:stats_{dataset}}}\n"
latex += "\\end{table}"
latex_path = os.path.join(output_dir, "statistical_comparison.tex")
with open(latex_path, 'w') as f:
f.write(latex)
def compute_number_english_samples(inputs, threshold):
"""
Count samples below and above threshold for multilingual dataset splits.
Args:
inputs: List of sample indices.
threshold: Cutoff index separating languages.
Returns:
Tuple of (count_below_threshold, count_above_threshold).
"""
english = 0
for item in inputs:
if item < threshold:
english +=1
return english, len(inputs) - english
def seed_everything(seed: int = 42) -> None:
"""
Set random seeds for reproducibility across multiple libraries.
Args:
seed: Integer seed for random number generation
"""
import random
import numpy
import torch
random.seed(seed)
numpy.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed(seed)
def get_complete_predictions(dataset_name, predictor_name, language="spanish"):
"""
Load pre-computed predictions from cache file.
Args:
dataset_name: Name of the dataset.
predictor_name: Name of the predictor model.
Returns:
Array of predictions, or None if file not found.
"""
if dataset_name not in ["multilingual", "xlsum"]:
path = os.path.join("autoeval", predictor_name, f"all_predictions_{dataset_name}.npy")
else:
path = os.path.join("autoeval", predictor_name, f"all_predictions_{dataset_name}_{language}.npy")
if not os.path.exists(path):
print(f"File {path} not available. You must generate the predictions.")
return None
else:
all_predictions = np.load(path, allow_pickle=True)
return all_predictions
def shuffle_data(texts, labels, all_predictions):
"""
Shuffle texts, labels, and predictions together maintaining alignment.
Args:
texts: List of input texts.
labels: List of corresponding labels.
all_predictions: List of model predictions.
Returns:
Tuple of (shuffled_texts, shuffled_labels, shuffled_predictions).
"""
combined = list(zip(texts, labels, all_predictions))
random.shuffle(combined)
shuffled_texts, shuffled_labels, shuffled_predictions = zip(*combined)
return list(shuffled_texts), list(shuffled_labels), list(shuffled_predictions)
def compute_class_metrics(
labels,
indices,
pipeline_name: str = None,
) -> Tuple[float, float]:
"""
Compute minority class precision and recall for selected samples.
For NER/POS tasks, operates at sequence level (sequence contains minority tag).
For classification, operates at sample level.
Args:
labels: List of labels (flat for classification, nested for NER).
indices: Selected sample indices.
pipeline_name: Task type ('ner', 'pos', or None for classification).
Returns:
Dict with 'unbalance_precision' and 'unbalance_recall'.
"""
if pipeline_name in ["ner", "pos"]:
# Handle NER case: flatten the nested lists of labels
flat_labels = []
for label_seq in labels:
flat_labels.extend(label_seq)
# Convert to numpy array for efficient counting
labels_array = np.array(flat_labels)
# Find the minority class
unique_classes, counts = np.unique(labels_array, return_counts=True)
minority_class = unique_classes[np.argmin(counts)]
# Find sequences containing the minority class
minority_indices = []
for i, label_seq in enumerate(labels):
# If any token in the sequence is of minority class, include the sequence
if minority_class in label_seq:
minority_indices.append(i)
# Find selected sequences that contain minority class
selected_minority = np.intersect1d(indices, minority_indices)
else:
# Handle simple classification case
labels_array = np.array(labels)
# Count instances of each class
class_counts = [
np.sum(labels_array == i) for i in range(len(np.unique(labels_array)))
]
# Identify minority class and its instances
minority_class = np.argmin(class_counts)
minority_indices = np.where(labels_array == minority_class)[0]
# Find selected instances of minority class
selected_minority = np.intersect1d(indices, minority_indices)
# Calculate unbalance metrics
try:
unbalance_precision = round(len(selected_minority) / len(indices), 4)
except ZeroDivisionError:
unbalance_precision = 0
# Recall: proportion of minority class samples that were selected
try:
unbalance_recall = round(len(selected_minority) / len(minority_indices), 4)
except ZeroDivisionError:
unbalance_recall = 0
return {
"unbalance_precision": unbalance_precision,
"unbalance_recall": unbalance_recall,
}
def save_json(
file_name: str,
data: dict,
dataset_name: str,
base_folder: str = "results",
additional_params: dict = None,
) -> None:
"""
Save results to JSON file with organized directory structure.
Args:
file_name: Name of the JSON file (without extension).
data: Dictionary containing results to save.
dataset_name: Name of the dataset for directory organization.
base_folder: Base directory for results.
additional_params: Optional params like num_samples, language_prior.
"""
# Create base directories
os.makedirs(f"{base_folder}/json", exist_ok=True)
os.makedirs(f"{base_folder}/json/{dataset_name}", exist_ok=True)
path = f"{base_folder}/json/{dataset_name}"
# Handle additional parameters for synthetic data
if additional_params is not None:
if 'num_samples' in additional_params.keys():
os.makedirs(
f"{base_folder}/json/{dataset_name}/{additional_params['num_samples']}",
exist_ok=True,
)
path = f"{base_folder}/json/{dataset_name}/{additional_params['num_samples']}"
#data[0]['class_distribution'] = additional_params['class_distribution']
if 'language_prior' in additional_params.keys():
data[0]['language_prior'] = additional_params['language_prior']
data[0]['stats_languages'] = additional_params['stats_languages']
# Save data to JSON file
with open(os.path.join(path, f"{file_name}.json"), "w") as f:
json.dump(data, f)
def get_mapping() -> dict:
"""
Get mapping dictionary for method and parameter names to short codes.
Returns:
dict: Mapping of full names to short codes
"""
return {
# Testing methods
"Random": "0",
"Coverage": "1",
"Distance": "2",
"Uncertainty": "3",
"Agreement": "4",
"Surrogate": "5",
"Diversity" : "6",
"Diffuse" : "7",
"Stratified" : "8",
# Clustering methods
"dbscan": "a",
"kmeans": "b",
"shift": "c",
# Selection strategies
"clusters": "y",
"centroids": "x",
"max_dist": "z",
# Acquisition functions
"gaussian_prior": "s",
"mutual_information": "t",
# Model types
"SVM": "r",
"RF": "p",
}
def map_methods_to_id(results: dict, **kwargs) -> str:
"""
Convert method names and parameters to a compact identifier string.
Args:
results: Dictionary containing results
**kwargs: Additional parameters to include in the identifier
Returns:
str: Compact identifier string
"""
mapping = get_mapping()
output = ""
# Map method names
for key in results.keys():
try:
output += mapping[key]
except KeyError:
continue
# Handle additional parameters
if kwargs:
for value in kwargs.values():
try:
if value != "-1":
output += f"_{mapping[value]}"
except (KeyError, TypeError):
continue
if kwargs["n_clusters"] != -1:
output += f"_{kwargs['n_clusters']}"
return output
def preprocess_text(text: str, length: int = 512) -> str:
"""
Preprocess text by truncating to specified length.
Args:
text: Input text to preprocess
length: Maximum number of words to keep
Returns:
str: Preprocessed text
"""
return " ".join(text.split()[:length])
def evaluate_metrics(
y_true: List[int],
y_pred: List[int],
results_not_active: dict = None,
pipeline_name: str = None,
) -> Dict[str, float]:
"""
Calculate evaluation metrics for classification or sequence labeling results.
Args:
y_true: List of true labels (nested for NER/POS).
y_pred: List of predicted labels.
results_not_active: If provided, returns absolute differences from these values.
pipeline_name: Task type ('ner', 'pos', or None for classification).
Returns:
Dict with 'accuracy', 'precision', 'recall', 'f1' (or their differences).
"""
# Calculate base metrics
if pipeline_name == "ner":
mlb = MultiLabelBinarizer()
y_true = mlb.fit_transform(y_true)
y_pred = mlb.transform(y_pred)
if pipeline_name not in ["ner", "pos"]:
accuracy = accuracy_score(y_true, y_pred)
else:
y_true = [label for seq in y_true for label in seq]
y_pred = [label for seq in y_pred for label in seq]
accuracy = accuracy_score(y_true, y_pred)
precision, recall, f1, _ = precision_recall_fscore_support(
y_true, y_pred, average="weighted", zero_division=0
)
# If reference results provided, compute differences
if results_not_active is not None:
return {
"accuracy": abs(results_not_active["accuracy"] - accuracy),
"precision": abs(results_not_active["precision"] - precision),
"recall": abs(results_not_active["recall"] - recall),
"f1": abs(results_not_active["f1"] - f1),
}
# Otherwise return raw metrics
return {"accuracy": accuracy, "precision": precision, "recall": recall, "f1": f1}
def format_distribution(distribution: str) -> str:
"""
Format the distribution string into LaTeX array notation.
Args:
distribution (str): Distribution string (e.g., "0.7_0.3" or "0.33_0.33_0.34")
Returns:
str: Formatted LaTeX string (e.g., "$[0.7, 0.3]$" or "$[0.33, 0.33, 0.34]$")
"""
# Split the distribution string and format as array
classes = distribution.split("_")
return f"$[{', '.join(classes)}]$"
def read_result_file(file_path: str) -> Dict[int, List[Tuple[float, float]]]:
"""
Read a single result file and extract the metrics.
Args:
file_path (str): Path to the result file
Returns:
Dict[int, List[Tuple[float, float]]]: Dictionary mapping n_samples to list of (mean, std) tuples
Example:
{
20: [(0.123, 0.045), (0.234, 0.056), (0.345, 0.067)], # (precision, recall, f1)
50: [(0.234, 0.056), (0.345, 0.067), (0.456, 0.078)],
...
}
"""
results = {}
with open(file_path, "r") as f:
for line in f:
# Remove trailing \\ and split by &
parts = line.strip().rstrip("\\").split("&")
n_samples = float(parts[0].strip())
# Extract numerical values using regex
values = []
for part in parts[1:]:
match = re.search(r"(-?\d+\.\d+)\s*\$\\pm\$\s*(-?\d+\.\d+)", part)
if match:
mean, std = float(match.group(1)), float(match.group(2))
values.append((mean, std))
results[n_samples] = values
return results
def find_best_methods(
results_dict: Dict[str, Dict[int, List[Tuple[float, float]]]],
n_samples: int,
metric_idx: int,
) -> Tuple[str, str]:
"""
Find the best and second best methods for a given metric at a specific n_samples.
Args:
results_dict: Dictionary containing results for all methods
n_samples: Number of samples to compare
metric_idx: Index of the metric (0: precision, 1: recall, 2: f1)
Returns:
Tuple[str, str]: Names of the best and second best performing methods
"""
performances = []
for method, results in results_dict.items():
mean, _ = results[n_samples][metric_idx]
if mean != -1: # Ignore -1 values
performances.append((mean, method))
# Sort by performance (descending)
performances.sort(reverse=True)
if len(performances) == 0:
return None, None
elif len(performances) == 1:
return performances[0][1], None
else:
return performances[0][1], performances[1][1]
def generate_latex_table(
results_dict: Dict[str, Dict[int, List[Tuple[float, float]]]],
dataset: str,
distribution: str = None,
num_samples: str = None,
) -> str:
"""
Generate LaTeX table from results with bold/underline formatting for best values.
Args:
results_dict: Dict mapping method names to their results.
dataset: Dataset name for caption.
distribution: Optional class distribution string.
num_samples: Optional sample count string.
Returns:
Complete LaTeX table string.
"""
latex = "\\begin{table}[h]\n\\centering\n\\resizebox{\\textwidth}{!}{\n\\begin{tabular}{l|"
num_methods = len(results_dict)
latex += "ccc|" * num_methods
latex = latex.rstrip("|") + "}\n\\hline\n"
latex += "N samples"
for method in results_dict.keys():
method_name = method.replace("_", " ")
latex += f" & \\multicolumn{{3}}{{c|}}{{{method_name}}}"
latex = latex.rstrip("|")
latex += " \\\\\n"
latex += " & "
metrics = ["Precision", "F1"] * num_methods#"Recall", "F1"] * num_methods
latex += " & ".join(metrics)
latex += " \\\\\n\\hline\n"
n_samples = sorted(list(next(iter(results_dict.values())).keys()))
for n in n_samples:
row = [str(n)]
# Find best and second best methods for each metric at current n_samples
best_methods = [
find_best_methods(results_dict, n, metric_idx) for metric_idx in range(3)
]
for method in results_dict.keys():
for metric_idx, (mean, std) in enumerate(results_dict[method][n]):
if mean == -1 and std == -1:
row.append("-")
else:
value = f"{mean:.3f} $\\pm$ {std:.3f}"
best, second_best = best_methods[metric_idx]
if method == best:
value = f"\\textbf{{{value}}}"
elif method == second_best:
value = f"\\underline{{{value}}}"
row.append(value)
latex += " & ".join(row) + " \\\\\n"
latex += "\\hline\n\\end{tabular}}\n"
if distribution is not None:
latex += f"\\caption{{Results for {dataset} dataset with {format_distribution(distribution)} distribution and {num_samples} samples. "
else:
latex += f"\\caption{{Results for {dataset} dataset. "
latex += "Bold values indicate best performance and underlined values indicate second best performance for each metric.}\n"
if distribution is not None:
latex += f"\\label{{tab:{dataset}_{distribution}_{num_samples}}}\n"
else:
latex += f"\\label{{tab:{dataset}}}\n"
latex += "\\end{table}"
return latex
def process_results_structure(base_path: str = "synthetic/overleaf") -> None:
"""
Process entire results directory structure and generate LaTeX tables.
Iterates through dataset/distribution/samples directories and creates
tables in a latex_tables output directory.
Args:
base_path: Path to base directory containing results.
"""
base_path = Path(base_path)
# Create output directory for LaTeX tables
output_dir = base_path / "latex_tables"
os.makedirs(output_dir, exist_ok=True)
# Iterate through all directories
for dataset_dir in base_path.iterdir():
if not dataset_dir.is_dir():
continue
for dist_dir in dataset_dir.iterdir():
if not dist_dir.is_dir():
continue
for samples_dir in dist_dir.iterdir():
if not samples_dir.is_dir():
continue
# Process all txt files in the current directory
results_dict = {}
incomplete_methods = []
for result_file in samples_dir.glob("*.txt"):
method_name = result_file.stem
try:
file_results = read_result_file(str(result_file))
if file_results: # Only add if we got valid results
results_dict[method_name] = file_results
else:
incomplete_methods.append(method_name)
except Exception:
incomplete_methods.append(method_name)
if incomplete_methods:
print(
f"Warning: Skipping incomplete results for methods: {', '.join(incomplete_methods)} "
f"in {dataset_dir.name}/{dist_dir.name}/{samples_dir.name}"
)
if results_dict: # Only proceed if we have some valid results
try:
# Generate LaTeX table
latex_table = generate_latex_table(
results_dict,
dataset_dir.name,
dist_dir.name,
samples_dir.name,
)
# Save the table
output_file = (
output_dir
/ f"{dataset_dir.name}_{dist_dir.name}_{samples_dir.name}.tex"
)
with open(output_file, "w") as f:
f.write(latex_table)
print(f"Generated table: {output_file}")
except Exception as e:
print(
f"Error generating table for {dataset_dir.name}/{dist_dir.name}/{samples_dir.name}: {str(e)}"
)
def save_exp(
all_results: List[Dict],
dataset_name: str = "imdb",
synthetic: bool = False,
**kwargs,
) -> None:
"""
Save experimental results to JSON files with appropriate directory structure.
Args:
all_results: List of dictionaries containing experimental results
dataset_name: Name of the dataset
synthetic: Whether the results are from synthetic data
**kwargs: Additional parameters for file organization
"""
os.makedirs(kwargs["base_folder"], exist_ok=True)
base_folder = kwargs["base_folder"]
if "language_prior" in kwargs.keys():
save_json(
file_name=map_methods_to_id(all_results[0][list(all_results[0].keys())[0]], **kwargs),
data=all_results,
dataset_name=dataset_name,
base_folder=base_folder,
additional_params=kwargs,
)
else:
save_json(
file_name=map_methods_to_id(all_results[0], **kwargs),
data=all_results,
dataset_name=dataset_name,
base_folder=base_folder,
additional_params=kwargs,
)
def model_name_map(original_name, inverse=False) -> str:
if not inverse:
mapping = {
"bert-base-multilingual-cased": "bert",
"distilbert-base-multilingual-cased": "distilbert",
"Qwen/Qwen3-Embedding-0.6B": "qwen",
"NovaSearch/stella_en_1.5B_v5" : "stella",
}
else:
mapping = {
"bert": "bert-base-multilingual-cased",
"distilbert": "distilbert-base-multilingual-cased",
"qwen": "Qwen/Qwen3-Embedding-0.6B",
"stella" : "NovaSearch/stella_en_1.5B_v5",
}
return mapping[original_name]
def compute_rouge(predictions, references, rouge_types=None, use_stemmer=False):
if rouge_types is None:
rouge_types = ["rouge1", "rouge2", "rougeL", "rougeLsum"]
scorer = rouge_scorer.RougeScorer(rouge_types=rouge_types, use_stemmer=use_stemmer)
aggregator = scoring.BootstrapAggregator()
for ref, pred in zip(references, predictions):
score = scorer.score(ref, pred)
aggregator.add_scores(score)
result = aggregator.aggregate()
final = {}
for key in result:
mid = result[key].mid
final[f"{key}_precision"] = mid.precision.item()
final[f"{key}_recall"] = mid.recall.item()
return final
def decode_filename(filename: str, reverse_mapping: Dict[str, str], separator = '-') -> str:
"""
Convert encoded filename back to human-readable method name.
Args:
filename: Encoded filename to decode
reverse_mapping: Dictionary mapping codes back to method names
Returns:
str: Human-readable method name
"""
name = os.path.splitext(filename)[0]
parts = name.split("_")
# Decode main method name
if parts[0] in reverse_mapping:
method_name = reverse_mapping[parts[0]]
else:
method_name = parts[0]
# Decode additional parameters
if len(parts) > 1:
for i in range(1, len(parts)):
if parts[i] in reverse_mapping:
method_name += f" {separator} {reverse_mapping[parts[i]]}"
else:
method_name += f" ({parts[i]})"
return method_name
def extract_metrics(
data: List[Dict], metric_name: str
) -> Tuple[List[float], List[float], List[float]]:
"""
Extract metric values and statistics from experimental data.
Args:
data: List of dictionaries containing experimental results
metric_name: Name of the metric to extract
Returns:
tuple: (split_sizes, mean_metric_values, std_metric_values)
"""
all_metrics = defaultdict(list)
# Collect metrics for each split size
for item in data:
for method_name, method_data in item.items():
for split_size, metrics in method_data.items():
split_size_float = float(split_size)
if split_size_float != 1.0: # Exclude full dataset results
all_metrics[split_size_float].append(metrics[metric_name])
# Calculate statistics
split_sizes = sorted(all_metrics.keys())
metric_values = [np.mean(all_metrics[size]) for size in split_sizes]
std_values = [np.std(all_metrics[size]) for size in split_sizes]