-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
1466 lines (1260 loc) · 60.7 KB
/
main.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
import tkinter as tk
from tkinter import filedialog, messagebox
import pandas as pd
import numpy as np
import random
import warnings
import yaml
import os
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import cross_validate, KFold
from sklearn.exceptions import ConvergenceWarning
from sklearn.metrics import accuracy_score, f1_score, recall_score
# Classifiers
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.naive_bayes import GaussianNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression, RidgeClassifier, SGDClassifier
from sklearn.ensemble import (
RandomForestClassifier,
AdaBoostClassifier,
ExtraTreesClassifier,
GradientBoostingClassifier
)
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysis
from sklearn.neural_network import MLPClassifier
from xgboost import XGBClassifier
from sklearn.naive_bayes import BernoulliNB, MultinomialNB
from sklearn.linear_model import PassiveAggressiveClassifier, Perceptron
from catboost import CatBoostClassifier
from lightgbm import LGBMClassifier
from tkinter import ttk
# For parallel coordinates (matplotlib)
import matplotlib
matplotlib.use("TkAgg") # Use the TkAgg backend for embedding in Tkinter
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from pandas.plotting import parallel_coordinates
class ClassifierApp:
def __init__(self, root):
self.root = root
self.root.title("Machine Learning Classifier Comparison Tool")
# Set default window size
self.root.geometry("1080x720") # Width x Height
# Data holders
self.data = None
self.class_column = None
# Optional evaluation data
self.eval_data = None
self.eval_class_column = None
# For storing results
self.results = []
# Load parameter configurations from YAML
try:
with open('classifier_config.yaml', 'r') as f:
self.param_config = yaml.safe_load(f)
except Exception as e:
messagebox.showerror("Error", f"Failed to load classifier configuration: {e}")
self.root.destroy()
return
# Main Notebook for tabs
self.notebook = ttk.Notebook(root)
self.notebook.pack(fill=tk.BOTH, expand=True)
# Tabs
self.file_frame = ttk.Frame(self.notebook)
self.notebook.add(self.file_frame, text="Data Load and Statistics")
self.classifiers_frame = ttk.Frame(self.notebook)
self.notebook.add(self.classifiers_frame, text="Classifier Selection")
self.params_tab = ttk.Frame(self.notebook)
self.notebook.add(self.params_tab, text="Classifier Parameters")
self.results_tab = ttk.Frame(self.notebook)
self.notebook.add(self.results_tab, text="Results Table")
# NEW: Plot tab for embedded parallel coordinates
self.plot_tab = ttk.Frame(self.notebook)
self.notebook.add(self.plot_tab, text="Results Plot")
# Add About tab after Plot tab
self.about_tab = ttk.Frame(self.notebook)
self.notebook.add(self.about_tab, text="Program About")
# For storing the FigureCanvas
self.plot_canvas = None
# Build each section
self.build_file_tab()
self.build_classifiers_tab()
self.build_params_tab()
self.build_results_tab()
self.build_plot_tab()
self.build_about_tab()
# ------------------------------------------------------------------------
# Tab 1: File loading and info
# ------------------------------------------------------------------------
def build_file_tab(self):
# Main file label and load button
self.file_label = tk.Label(self.file_frame, text="No training data file loaded")
self.file_label.pack(pady=5)
self.load_button = tk.Button(
self.file_frame, text="Load File", command=self.load_file
)
self.load_button.pack(pady=5)
# Evaluation file label and load button
self.eval_label = tk.Label(self.file_frame, text="No secondary evaluation data file loaded")
self.eval_label.pack(pady=5)
self.eval_button = tk.Button(
self.file_frame, text="Load File (Optional)", command=self.load_eval_file
)
self.eval_button.pack(pady=5)
# Info text (shows main data info only)
self.info_text = tk.Text(self.file_frame, height=10, state=tk.DISABLED, wrap=tk.WORD)
self.info_text.pack(padx=5, pady=5, fill=tk.BOTH, expand=True)
def load_file(self):
file_path = filedialog.askopenfilename(filetypes=[("CSV files", "*.csv")])
if not file_path:
return
try:
self.data = pd.read_csv(file_path)
self.class_column = self.find_class_column(self.data)
self.display_dataset_info(self.data, self.class_column)
self.file_label.config(text=f"Training Data Loaded: {file_path}")
except Exception as e:
messagebox.showerror("Error", f"Failed to load file: {e}")
def load_eval_file(self):
file_path = filedialog.askopenfilename(filetypes=[("CSV files", "*.csv")])
if not file_path:
return
try:
self.eval_data = pd.read_csv(file_path)
self.eval_class_column = self.find_class_column(self.eval_data)
self.eval_label.config(text=f"Evaluation Data Loaded: {file_path}")
# Update the dataset info to show both datasets
if hasattr(self, 'data') and self.data is not None:
self.display_dataset_info(self.data, self.class_column)
except Exception as e:
messagebox.showerror("Error", f"Failed to load eval file: {e}")
def find_class_column(self, df):
for col in df.columns:
if "class" in col.lower():
return col
raise ValueError("No column with 'class' found.")
def display_dataset_info(self, df, class_col):
"""Display dataset information for both training and evaluation data if available"""
# Get data type analysis (excluding class column)
type_analysis, types_count, dataset_type = self.analyze_data_types(df)
# Get class information
class_counts = df[class_col].value_counts()
total_cases = len(df)
num_classes = len(class_counts)
balance_ratio = class_counts.min() / class_counts.max() if class_counts.max() != 0 else 0
majority_class = class_counts.idxmax()
# Build the info text for training data
info = (
f"Training Dataset Statistical Information:\n"
f"Number of Classes: {num_classes}\n"
f"Class case counts: {class_counts.to_dict()}\n"
f"Class balance: {balance_ratio:.2f} (Majority class: {majority_class})\n"
f"Classes: {', '.join(map(str, df[class_col].unique()))}\n\n"
f"Dataset Type: {dataset_type.upper()}\n"
f"Feature Types:\n"
f"{chr(10).join(f' {col}: {dtype}' for col, dtype in sorted(type_analysis.items()))}\n\n"
f"Missing Values: "
f"{'none' if df.isnull().sum().sum() == 0 else f'contains missing values ({df.isnull().sum().sum()})'}"
)
# If evaluation data is loaded, add its information
if hasattr(self, 'eval_data') and self.eval_data is not None:
eval_type_analysis, eval_types_count, eval_dataset_type = self.analyze_data_types(self.eval_data)
eval_class_counts = self.eval_data[self.eval_class_column].value_counts()
eval_num_classes = len(eval_class_counts)
eval_balance_ratio = eval_class_counts.min() / eval_class_counts.max() if eval_class_counts.max() != 0 else 0
eval_majority_class = eval_class_counts.idxmax()
info += (
f"\n\n{'-' * 50}\n\n" # Add separator
f"Secondary Evaluation Dataset Statistical Information:\n"
f"Number of Classes: {eval_num_classes}\n"
f"Class case counts: {eval_class_counts.to_dict()}\n"
f"Class balance: {eval_balance_ratio:.2f} (Majority class: {eval_majority_class})\n"
f"Classes: {', '.join(map(str, self.eval_data[self.eval_class_column].unique()))}\n\n"
f"Dataset Type: {eval_dataset_type.upper()}\n"
f"Feature Types:\n"
f"{chr(10).join(f' {col}: {dtype}' for col, dtype in sorted(eval_type_analysis.items()))}\n\n"
f"Missing Values: "
f"{'none' if self.eval_data.isnull().sum().sum() == 0 else f'contains missing values ({self.eval_data.isnull().sum().sum()})'}"
)
self.info_text.config(state=tk.NORMAL)
self.info_text.delete(1.0, tk.END)
self.info_text.insert(tk.END, info)
self.info_text.config(state=tk.DISABLED)
# ------------------------------------------------------------------------
# Tab 2: Classifier selection
# ------------------------------------------------------------------------
def build_classifiers_tab(self):
self.selected_classifiers = {}
# Create a frame to hold all classifier rows
classifiers_frame = ttk.Frame(self.classifiers_frame)
classifiers_frame.pack(fill=tk.X, pady=5)
# Create a frame for toggle buttons
toggle_frame = ttk.Frame(classifiers_frame)
toggle_frame.grid(row=0, column=0, columnspan=4, padx=5, pady=5, sticky=tk.W)
# Add toggle buttons
self.select_all_button = ttk.Button(
toggle_frame,
text="Select All",
command=self.toggle_all_classifiers
)
self.select_all_button.pack(side=tk.LEFT, padx=5)
self.select_numerical_button = ttk.Button(
toggle_frame,
text="Select Numerical",
command=lambda: self.toggle_by_type("numerical")
)
self.select_numerical_button.pack(side=tk.LEFT, padx=5)
self.select_binary_button = ttk.Button(
toggle_frame,
text="Select Binary",
command=lambda: self.toggle_by_type("binary")
)
self.select_binary_button.pack(side=tk.LEFT, padx=5)
self.select_categorical_button = ttk.Button(
toggle_frame,
text="Select Categorical",
command=lambda: self.toggle_by_type("categorical")
)
self.select_categorical_button.pack(side=tk.LEFT, padx=5)
# Dictionary mapping classifiers to their data types
self.classifier_types = {
"Decision Tree": ["numerical", "binary", "categorical"],
"Random Forest": ["numerical", "binary", "categorical"],
"Extra Trees": ["numerical", "binary", "categorical"],
"KNN": ["numerical"],
"SVM": ["numerical"],
"LDA": ["numerical"],
"Logistic Regression": ["numerical"],
"Ridge": ["numerical"],
"Naive Bayes": ["numerical"],
"Bernoulli NB": ["binary"],
"Multinomial NB": ["categorical"],
"QDA": ["numerical"],
"MLP": ["numerical"],
"SGD": ["numerical"],
"Gradient Boosting": ["numerical", "binary", "categorical"],
"AdaBoost": ["numerical", "binary", "categorical"],
"XGBoost": ["numerical", "binary", "categorical"],
"CatBoost": ["numerical", "binary", "categorical"],
"LightGBM": ["numerical", "binary", "categorical"],
"Passive Aggressive": ["numerical"],
"Perceptron": ["numerical"]
}
# Classifiers with names, acronyms, and data type hints - now in 3 columns
classifier_rows = [
# Row 1
[
("Decision Tree (All Types)", "DT"),
("Random Forest (All Types)", "RF"),
("Extra Trees (All Types)", "ET"),
],
# Row 2
[
("K-Nearest Neighbors (Numerical)", "KNN"),
("Support Vector Machine (Numerical)", "SVM"),
("Linear Discriminant Analysis (Numerical)", "LDA"),
],
# Row 3
[
("Logistic Regression (Numerical)", "LR"),
("Ridge Classifier (Numerical)", "RC"),
("Gaussian Naive Bayes (Numerical)", "GNB"),
],
# Row 4
[
("Bernoulli Naive Bayes (Binary)", "BNB"),
("Multinomial Naive Bayes (Counts/Text)", "MNB"),
("Quadratic Discriminant Analysis (Numerical)", "QDA"),
],
# Row 5
[
("Multi-Layer Perceptron (Numerical)", "MLP"),
("Stochastic Gradient Descent (Numerical)", "SGD"),
("Gradient Boosting (All Types)", "GB"),
],
# Row 6
[
("AdaBoost (All Types)", "AB"),
("XGBoost (All Types)", "XGB"),
("CatBoost (Categorical)", "CB"),
],
# Row 7
[
("LightGBM (All Types)", "LGBM"),
("Passive Aggressive Classifier (Numerical)", "PA"),
("Perceptron (Numerical)", "PCP"),
]
]
# Configure grid columns to be equal width
for i in range(3):
classifiers_frame.grid_columnconfigure(i, weight=1)
# Create checkboxes for each classifier - start from row 1 instead of 0
for row_idx, row_classifiers in enumerate(classifier_rows):
for col_idx, (clf_display_name, acronym) in enumerate(row_classifiers):
var = tk.BooleanVar(value=False)
chk = tk.Checkbutton(
classifiers_frame,
text=f"{clf_display_name} ({acronym})",
variable=var
)
chk.grid(row=row_idx + 1, column=col_idx, padx=5, pady=5, sticky=tk.W) # +1 to row_idx
# Map the short internal name to the variable
internal_name = {
# Row 1
"Decision Tree (All Types)": "Decision Tree",
"Random Forest (All Types)": "Random Forest",
"Extra Trees (All Types)": "Extra Trees",
# Row 2
"K-Nearest Neighbors (Numerical)": "KNN",
"Support Vector Machine (Numerical)": "SVM",
"Linear Discriminant Analysis (Numerical)": "LDA",
# Row 3
"Logistic Regression (Numerical)": "Logistic Regression",
"Ridge Classifier (Numerical)": "Ridge",
"Gaussian Naive Bayes (Numerical)": "Naive Bayes",
# Row 4
"Bernoulli Naive Bayes (Binary)": "Bernoulli NB",
"Multinomial Naive Bayes (Counts/Text)": "Multinomial NB",
"Quadratic Discriminant Analysis (Numerical)": "QDA",
# Row 5
"Multi-Layer Perceptron (Numerical)": "MLP",
"Stochastic Gradient Descent (Numerical)": "SGD",
"Gradient Boosting (All Types)": "Gradient Boosting",
# Row 6
"AdaBoost (All Types)": "AdaBoost",
"XGBoost (All Types)": "XGBoost",
"CatBoost (Categorical)": "CatBoost",
# Row 7
"LightGBM (All Types)": "LightGBM",
"Passive Aggressive Classifier (Numerical)": "Passive Aggressive",
"Perceptron (Numerical)": "Perceptron",
}[clf_display_name]
self.selected_classifiers[internal_name] = var
# Common CV parameters
common_params_frame = ttk.LabelFrame(
self.classifiers_frame, text="Cross-Validation and Run Parameters"
)
common_params_frame.pack(fill=tk.X, pady=10, padx=5)
self.cross_val_split = self.add_param_entry(
parent=common_params_frame,
label="Cross-Validation Split (>=1, 1=no CV):",
default="5",
)
self.run_count = self.add_param_entry(
parent=common_params_frame, label="Classifier train and evaluation runs count (>=1):", default="10"
)
self.random_seed = self.add_param_entry(
parent=common_params_frame,
label="Random number generator seed for CV and classifiers:",
default=str(random.randint(0, 10**6)),
)
# Run button
self.run_button = tk.Button(
self.classifiers_frame,
text="Run Selected Classifiers",
command=self.run_classifiers,
)
self.run_button.pack(pady=5)
# Add status frame at the bottom
self.status_frame = ttk.Frame(self.classifiers_frame)
self.status_frame.pack(fill=tk.X, pady=5, padx=5)
# Progress bar
self.progress_bar = ttk.Progressbar(
self.status_frame,
mode='determinate',
length=300
)
self.progress_bar.pack(fill=tk.X, pady=2)
# Status label
self.status_label = ttk.Label(self.status_frame, text="")
self.status_label.pack(pady=2)
def toggle_all_classifiers(self):
"""Toggle all classifiers on/off"""
# Toggle the state
new_state = not any(var.get() for var in self.selected_classifiers.values())
# Update all checkboxes
for var in self.selected_classifiers.values():
var.set(new_state)
# Update button text
self.select_all_button.config(
text="Deselect All" if new_state else "Select All"
)
def add_param_entry(self, parent, label, default):
frame = ttk.Frame(parent)
frame.pack(fill=tk.X, pady=2)
lbl = ttk.Label(frame, text=label)
lbl.pack(side=tk.LEFT, padx=5)
entry = ttk.Entry(frame, width=8)
entry.insert(0, default)
entry.pack(side=tk.LEFT, padx=5)
return entry
def toggle_by_type(self, data_type):
"""Toggle all classifiers of a specific data type"""
# First check if any classifier of this type is unchecked
any_unchecked = False
for clf_name, types in self.classifier_types.items():
if data_type in types and not self.selected_classifiers[clf_name].get():
any_unchecked = True
break
# If any are unchecked, check all. Otherwise, uncheck all
new_state = any_unchecked
for clf_name, types in self.classifier_types.items():
if data_type in types:
self.selected_classifiers[clf_name].set(new_state)
# Update button text based on data type
if data_type == "numerical":
self.select_numerical_button.config(
text="Deselect Numerical" if new_state else "Select Numerical"
)
elif data_type == "binary":
self.select_binary_button.config(
text="Deselect Binary" if new_state else "Select Binary"
)
elif data_type == "categorical":
self.select_categorical_button.config(
text="Deselect Categorical" if new_state else "Select Categorical"
)
# ------------------------------------------------------------------------
# Tab 3: Hyperparameter controls
# ------------------------------------------------------------------------
def build_params_tab(self):
canvas = tk.Canvas(self.params_tab)
scrollbar = ttk.Scrollbar(self.params_tab, orient="vertical", command=canvas.yview)
scroll_frame = ttk.Frame(canvas)
scroll_frame.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
canvas.create_window((0, 0), window=scroll_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)
# Add mouse wheel scrolling
def _on_mousewheel(event):
canvas.yview_scroll(int(-1*(event.delta/120)), "units")
canvas.bind_all("<MouseWheel>", _on_mousewheel)
def _bind_mousewheel(event):
canvas.bind_all("<MouseWheel>", _on_mousewheel)
def _unbind_mousewheel(event):
canvas.unbind_all("<MouseWheel>")
canvas.bind('<Enter>', _bind_mousewheel)
canvas.bind('<Leave>', _unbind_mousewheel)
# Create left and right columns
left_column = ttk.Frame(scroll_frame)
right_column = ttk.Frame(scroll_frame)
left_column.grid(row=0, column=0, padx=5, pady=5, sticky="n")
right_column.grid(row=0, column=1, padx=5, pady=5, sticky="n")
# Configure grid to make columns equal width
scroll_frame.grid_columnconfigure(0, weight=1)
scroll_frame.grid_columnconfigure(1, weight=1)
self.hyperparam_entries = {}
# Split classifiers into two groups
classifier_names = list(self.param_config.keys())
mid_point = (len(classifier_names) + 1) // 2
# Left column classifiers
for clf_name in classifier_names[:mid_point]:
group = ttk.LabelFrame(left_column, text=clf_name)
group.pack(fill=tk.X, padx=5, pady=5)
self.hyperparam_entries[clf_name] = {}
for param_name, info in self.param_config[clf_name].items():
self._create_param_widget(group, clf_name, param_name, info)
# Right column classifiers
for clf_name in classifier_names[mid_point:]:
group = ttk.LabelFrame(right_column, text=clf_name)
group.pack(fill=tk.X, padx=5, pady=5)
self.hyperparam_entries[clf_name] = {}
for param_name, info in self.param_config[clf_name].items():
self._create_param_widget(group, clf_name, param_name, info)
canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
def _create_param_widget(self, group, clf_name, param_name, info):
"""Helper method to create parameter widgets"""
param_type = info["type"]
default_value = info["default"]
param_help = info["help"]
row_frame = ttk.Frame(group)
row_frame.pack(fill=tk.X, pady=2)
lbl = ttk.Label(row_frame, text=param_name + ":")
lbl.pack(side=tk.LEFT, padx=5)
if param_type == "combo":
combo = ttk.Combobox(row_frame, values=info["options"], state="readonly", width=15)
combo.set(default_value)
combo.pack(side=tk.LEFT, padx=5)
self.hyperparam_entries[clf_name][param_name] = combo
elif param_type in ["numeric", "text"]:
entry = ttk.Entry(row_frame, width=8)
entry.insert(0, str(default_value))
entry.pack(side=tk.LEFT, padx=5)
self.hyperparam_entries[clf_name][param_name] = entry
help_label = ttk.Label(row_frame, text=f"({param_help})", foreground="gray")
help_label.pack(side=tk.LEFT, padx=5)
# ------------------------------------------------------------------------
# Tab 4: Results
# ------------------------------------------------------------------------
def build_results_tab(self):
"""
We'll keep columns for best/worst/avg/std for accuracy, F1, recall.
This remains the same structure for either main-data CV or eval-data CV.
"""
# Add sorting state variables
self.sort_column = None
self.sort_reverse = False
self.results_table = ttk.Treeview(
self.results_tab,
columns=(
"Classifier",
# ACC
"ACC Best", "ACC Worst", "ACC Avg", "ACC Std",
# F1
"F1 Best", "F1 Worst", "F1 Avg", "F1 Std",
# Recall
"REC Best", "REC Worst", "REC Avg", "REC Std"
),
show="headings",
height=10
)
# Configure column headings with click binding
for col in self.results_table["columns"]:
self.results_table.heading(
col,
text=col,
command=lambda c=col: self.sort_results_by(c)
)
self.results_table.column(col, width=80, anchor=tk.CENTER)
self.results_table.pack(fill=tk.BOTH, expand=True, pady=10, padx=5)
# Export button
self.export_button = tk.Button(
self.results_tab,
text="Export to CSV",
command=self.export_results
)
self.export_button.pack(side=tk.LEFT, padx=5, pady=5)
# Visualize button
self.visualize_button = tk.Button(
self.results_tab,
text="Visualize",
command=self.visualize_results
)
self.visualize_button.pack(side=tk.LEFT, padx=5, pady=5)
def sort_results_by(self, column):
"""Sort results table by the selected column"""
# If clicking the same column, reverse the sort order
if self.sort_column == column:
self.sort_reverse = not self.sort_reverse
else:
self.sort_column = column
self.sort_reverse = False
# Get all items
items = [(self.results_table.set(item, column), item) for item in self.results_table.get_children("")]
# Sort items
if column != "Classifier":
# For numeric columns, extract the actual value before the parentheses
items = [(float(val.split()[0]), item) for val, item in items]
items.sort(reverse=self.sort_reverse)
items = [(str(val), item) for val, item in items]
else:
# For Classifier column, sort alphabetically
items.sort(reverse=self.sort_reverse)
# Rearrange items in sorted order
for index, (_, item) in enumerate(items):
self.results_table.move(item, "", index)
# Add visual feedback - update column header
for col in self.results_table["columns"]:
if col == column:
# Add arrow to indicate sort direction
arrow = "↓" if self.sort_reverse else "↑"
self.results_table.heading(col, text=f"{col} {arrow}")
else:
# Remove arrow from other columns
self.results_table.heading(col, text=col)
# ------------------------------------------------------------------------
# Tab 5: Plot (for embedded parallel coordinates)
# ------------------------------------------------------------------------
def build_plot_tab(self):
"""
Build the Plot tab with toggle buttons and export button
"""
# Frame for controls
controls_frame = ttk.Frame(self.plot_tab)
controls_frame.pack(fill=tk.X, pady=5)
# Normalization toggle button
self.normalize_var = tk.BooleanVar(value=True)
self.normalize_button = ttk.Button(
controls_frame,
text="Toggle Normalization (On)",
command=self.toggle_normalization
)
self.normalize_button.pack(side=tk.LEFT, padx=5)
# Show axes toggle button - change default to False
self.show_axes_var = tk.BooleanVar(value=False) # Default to no axes
self.show_axes_button = ttk.Button(
controls_frame,
text="Toggle Axes (Off)", # Update initial text
command=self.toggle_axes
)
self.show_axes_button.pack(side=tk.LEFT, padx=5)
# Export plot button
self.export_plot_button = ttk.Button(
controls_frame,
text="Export Plot",
command=self.export_plot
)
self.export_plot_button.pack(side=tk.LEFT, padx=5)
# Placeholder label for plot area
self.plot_placeholder = tk.Label(self.plot_tab, text="Parallel Coordinates will be shown here.")
self.plot_placeholder.pack(pady=10)
def toggle_normalization(self):
"""Toggle normalization and update the visualization"""
self.normalize_var.set(not self.normalize_var.get())
# Update button text
self.normalize_button.config(
text=f"Toggle Normalization ({'On' if self.normalize_var.get() else 'Off'})"
)
# Redraw the visualization if we have results
if hasattr(self, 'train_results') and self.train_results:
self.visualize_results()
def toggle_axes(self):
"""Toggle axes visibility and update the visualization"""
self.show_axes_var.set(not self.show_axes_var.get())
# Update button text
self.show_axes_button.config(
text=f"Toggle Axes ({'On' if self.show_axes_var.get() else 'Off'})"
)
# Redraw the visualization if we have results
if hasattr(self, 'train_results') and self.train_results:
self.visualize_results()
def visualize_results(self):
"""Build parallel coordinates plots for training and evaluation results"""
if not hasattr(self, 'train_results') or not self.train_results:
messagebox.showerror("Error", "No results to visualize.")
return
# Convert results to DataFrames
columns = [
"Classifier",
"ACC Best", "ACC Worst", "ACC Avg", "ACC Std",
"F1 Best", "F1 Worst", "F1 Avg", "F1 Std",
"REC Best", "REC Worst", "REC Avg", "REC Std"
]
train_df = pd.DataFrame(self.train_results, columns=columns)
train_df['Dataset'] = 'Training'
if hasattr(self, 'eval_results') and self.eval_results:
eval_df = pd.DataFrame(self.eval_results, columns=columns)
eval_df['Dataset'] = 'Evaluation'
# Combine the dataframes
df = pd.concat([train_df, eval_df], ignore_index=True)
else:
df = train_df
# Check normalization toggle
numerical_cols = [
"ACC Best", "ACC Worst", "ACC Avg", "ACC Std",
"F1 Best", "F1 Worst", "F1 Avg", "F1 Std",
"REC Best", "REC Worst", "REC Avg", "REC Std"
]
if self.normalize_var.get():
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
df[numerical_cols] = scaler.fit_transform(df[numerical_cols])
# Clear the previous plot if it exists
if self.plot_canvas:
self.plot_canvas.get_tk_widget().destroy()
plt.close('all')
# Create the figure with a smaller width
fig, ax = plt.subplots(figsize=(8, 6))
# Define specific colors and line styles
colors = [
'#e6194b', '#3cb44b', '#ffe119', '#4363d8', '#f58231', '#911eb4',
'#46f0f0', '#f032e6', '#bcf60c', '#fabebe', '#008080', '#e6beff',
'#9a6324', '#fffac8', '#800000', '#aaffc3', '#808000', '#ffd8b1',
'#000075', '#808080', '#ffffff', '#000000'
]
line_styles = ['-', '--', ':', '-.'] # Used after colors are exhausted
# Create unique combinations of colors and line styles
style_cycler = []
num_classifiers = len(df)
for i in range(num_classifiers):
if i < len(colors):
# Use unique color with solid line
style_cycler.append({
'color': colors[i],
'linestyle': '-'
})
else:
# After colors are exhausted, cycle through colors with different line styles
color_idx = i % len(colors)
style_idx = (i // len(colors)) % len(line_styles)
style_cycler.append({
'color': colors[color_idx],
'linestyle': line_styles[style_idx]
})
# Plot each classifier's line with a unique style
for idx, (classifier, dataset) in enumerate(df.groupby(['Classifier', 'Dataset'])):
classifier_name, dataset_type = classifier # Unpack the tuple
classifier_data = df[(df['Classifier'] == classifier_name) & (df['Dataset'] == dataset_type)]
# Create label with classifier name and dataset type
label = f"{classifier_name} ({dataset_type})"
# Plot the parallel coordinates for this classifier
for i in range(len(numerical_cols)-1):
ax.plot(
[i, i+1],
[classifier_data[numerical_cols[i]], classifier_data[numerical_cols[i+1]]], # Fixed brackets
label=label if i == 0 else "_nolegend_",
**style_cycler[idx]
)
# Always keep the border (spines) and labels
for spine in ax.spines.values():
spine.set_visible(True)
# Always show x and y labels
ax.set_xticks(range(len(numerical_cols)))
ax.set_xticklabels(numerical_cols, rotation=45, ha='right')
ax.yaxis.set_visible(True)
# Toggle parallel axes visibility
if self.show_axes_var.get():
# Draw parallel coordinate axes
ax.grid(True, linestyle='--', alpha=0.7)
# Draw vertical lines for each dimension
for i in range(len(numerical_cols)):
ax.axvline(x=i, color='gray', linestyle='-', alpha=0.5)
else:
# Hide just the grid
ax.grid(False)
# Adjust the legend position
legend = ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15),
ncol=3, frameon=False, title="Classifiers")
# Add a title and labels
ax.set_title("Parallel Coordinates: Classifier Evaluation Metrics")
ax.set_ylabel("Normalized Evaluation Metric Value" if self.normalize_var.get() else "Evaluation Metric Value")
# Adjust layout to prevent label cutoff
plt.tight_layout()
# Remove the placeholder label if it exists
if hasattr(self, 'plot_placeholder') and self.plot_placeholder:
self.plot_placeholder.destroy()
self.plot_placeholder = None
# Embed the figure in the plot tab
self.plot_canvas = FigureCanvasTkAgg(fig, master=self.plot_tab)
self.plot_canvas.draw()
self.plot_canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
# Switch to the Plot tab
self.notebook.select(self.plot_tab)
def export_plot(self):
"""Save the current plot to a PNG file"""
if not hasattr(self, 'plot_canvas') or not self.plot_canvas:
messagebox.showerror("Error", "No plot to export.")
return
file_path = filedialog.asksaveasfilename(
defaultextension=".png",
filetypes=[("PNG files", "*.png")]
)
if not file_path:
return
try:
# Get the figure from the canvas
fig = self.plot_canvas.figure
# Save with tight layout to prevent cutoff
fig.savefig(
file_path,
bbox_inches='tight',
dpi=300
)
messagebox.showinfo("Success", "Plot exported successfully.")
except Exception as e:
messagebox.showerror("Error", f"Failed to export plot: {str(e)}")
# ------------------------------------------------------------------------
# Running classifiers
# ------------------------------------------------------------------------
def run_classifiers(self):
# Helper function for setting all random seeds
def set_all_seeds(seed):
random.seed(seed)
np.random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
if self.data is None:
messagebox.showerror("Error", "No main dataset loaded.")
return
try:
num_splits = int(self.cross_val_split.get())
if num_splits < 1:
raise ValueError("Cross-validation splits must be >= 1")
run_count = int(self.run_count.get())
if run_count < 1:
raise ValueError("Run count must be >= 1")
random_seed = int(self.random_seed.get())
set_all_seeds(random_seed) # Set initial seeds
# Main data
X_main = self.data.drop(columns=self.class_column)
y_main = self.data[self.class_column]
# Label-encode main data if needed
if y_main.dtype == object or y_main.dtype.kind in {'U', 'S'}:
self.label_encoder = LabelEncoder()
y_main = self.label_encoder.fit_transform(y_main)
# Check if we have optional eval data
use_eval = (self.eval_data is not None)
if use_eval:
X_eval = self.eval_data.drop(columns=self.eval_class_column)
y_eval = self.eval_data[self.eval_class_column]
# Encode eval data with same encoder
if y_eval.dtype == object or y_eval.dtype.kind in {'U', 'S'}:
y_eval = self.label_encoder.transform(y_eval)
# Create separate lists for training and evaluation results
self.train_results = []
self.eval_results = []
convergence_issues = set()
# Count total operations for progress bar - double if using eval data
selected_clf_count = sum(1 for var in self.selected_classifiers.values() if var.get())
total_operations = selected_clf_count * run_count * (2 if use_eval else 1)
current_operation = 0
# Reset and show progress bar
self.progress_bar['value'] = 0
self.progress_bar['maximum'] = total_operations
for clf_name, var in self.selected_classifiers.items():
if not var.get():
continue
# Update status to show classifier name and total runs
self.status_label['text'] = f"Training - Running {clf_name} (0/{run_count} runs)..."
self.root.update()
hyperparams = self.parse_hyperparams(clf_name)
classifier = self.build_classifier(clf_name, hyperparams, random_seed)
# Training results collection
train_accuracy_scores = []
train_f1_scores = []
train_recall_scores = []
# Evaluation results collection (if using eval data)
eval_accuracy_scores = []
eval_f1_scores = []
eval_recall_scores = []
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always", ConvergenceWarning)
for run_i in range(run_count):
seed_for_run = random_seed + run_i
set_all_seeds(seed_for_run) # Set all seeds for this run
current_operation += 1
self.progress_bar['value'] = current_operation
self.status_label['text'] = f"Training - Running {clf_name} ({run_i + 1}/{run_count} runs)..."
self.root.update()
if num_splits == 1:
# No CV - train on full dataset
classifier.random_state = seed_for_run
classifier.fit(X_main, y_main)
# Get predictions using the same model instance for both datasets
train_preds = classifier.predict(X_main)
train_accuracy_scores.append(accuracy_score(y_main, train_preds))
train_f1_scores.append(f1_score(y_main, train_preds, average='macro'))
train_recall_scores.append(recall_score(y_main, train_preds, average='macro'))
if use_eval:
eval_preds = classifier.predict(X_eval)
eval_accuracy_scores.append(accuracy_score(y_eval, eval_preds))
eval_f1_scores.append(f1_score(y_eval, eval_preds, average='macro'))
eval_recall_scores.append(recall_score(y_eval, eval_preds, average='macro'))
else:
# Use same CV splits and same random state for both datasets