Fancy-yousa commited on
Commit
e268078
·
verified ·
1 Parent(s): 6d7d84b

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -1077
app.py DELETED
@@ -1,1077 +0,0 @@
1
- import os
2
- import sys
3
- import json
4
- import datetime
5
- import math
6
- try:
7
- import scipy.io
8
- except ImportError:
9
- scipy = None
10
- try:
11
- import numpy as np
12
- except ImportError:
13
- np = None
14
- try:
15
- import pandas as pd
16
- except ImportError:
17
- pd = None
18
- from flask import Flask, jsonify, request, render_template, send_from_directory
19
- from dash import Dash, html, dcc, dash_table, Input, Output, State, callback_context
20
- import dash_mantine_components as dmc
21
- import plotly.graph_objects as go
22
-
23
- sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
24
- from leaderboard import rank_results
25
- try:
26
- from complex_com import algorithms as ALGO_COMPLEXITY
27
- except ImportError:
28
- ALGO_COMPLEXITY = {}
29
-
30
- base_dir = os.getcwd()
31
- if not os.path.isdir(os.path.join(base_dir, "results")):
32
- base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
33
- PROJECT_ROOT = base_dir
34
- RESULT_DIR = os.path.join(PROJECT_ROOT, "results")
35
- DATA_DIR = os.path.join(PROJECT_ROOT, "data")
36
- PDF_DIR = os.path.join(PROJECT_ROOT, "pdf")
37
-
38
- os.makedirs(RESULT_DIR, exist_ok=True)
39
-
40
- server = Flask(__name__)
41
-
42
- RESULT_CACHE = {}
43
-
44
-
45
- def save_result_json(dataset, results):
46
- path = os.path.join(RESULT_DIR, f"{dataset}.json")
47
- with open(path, "w", encoding="utf-8") as f:
48
- json.dump(results, f, indent=4)
49
-
50
-
51
- def load_result_json(dataset):
52
- path = os.path.join(RESULT_DIR, f"{dataset}.json")
53
- if not os.path.exists(path):
54
- return None
55
- with open(path, "r", encoding="utf-8") as f:
56
- return json.load(f)
57
-
58
-
59
- def list_available_datasets():
60
- datasets = set()
61
- for f in os.listdir(RESULT_DIR):
62
- if f.endswith(".json"):
63
- datasets.add(f.replace(".json", ""))
64
- datasets.add("Authorship")
65
- return sorted(datasets)
66
-
67
-
68
- def run_agent_for_dataset(dataset):
69
- return []
70
-
71
-
72
- def build_dataset_metadata():
73
- datasets = {}
74
- for name in list_available_datasets():
75
- last_updated = datetime.datetime.fromtimestamp(1707382400).strftime("%Y-%m-%d")
76
- num_samples = None
77
- total_features = None
78
- if scipy:
79
- mat_path = os.path.join(DATA_DIR, f"{name}.mat")
80
- if os.path.exists(mat_path):
81
- try:
82
- mat = scipy.io.loadmat(mat_path)
83
- if "X" in mat:
84
- X = mat["X"]
85
- num_samples, total_features = X.shape
86
- except Exception:
87
- num_samples = None
88
- total_features = None
89
- datasets[name] = {
90
- "name": name,
91
- "last_updated": last_updated,
92
- "num_samples": num_samples,
93
- "total_features": total_features,
94
- }
95
- return datasets
96
-
97
-
98
- DATASET_METADATA = build_dataset_metadata()
99
-
100
-
101
- def build_complexity_display():
102
- display_complexity = {}
103
- for algo, comp in ALGO_COMPLEXITY.items():
104
- t = comp.get("time", "")
105
- s = comp.get("space", "")
106
- t_disp = t.replace("**", "^").replace(" * ", "")
107
- if "O(" not in t_disp:
108
- t_disp = f"O({t_disp})" if t_disp else ""
109
- s_disp = s.replace("**", "^").replace(" * ", "")
110
- if "O(" not in s_disp:
111
- s_disp = f"O({s_disp})" if s_disp else ""
112
- display_complexity[algo] = {"time": t_disp, "space": s_disp}
113
- return display_complexity
114
-
115
-
116
- DISPLAY_COMPLEXITY = build_complexity_display()
117
-
118
- VIEW_CONFIG = {
119
- "overall": [
120
- {"key": "mean_f1", "label": "Mean F1"},
121
- {"key": "mean_auc", "label": "Mean AUC"},
122
- ],
123
- "classifiers-f1": [
124
- {"key": "metrics.nb.f1", "label": "NB F1"},
125
- {"key": "metrics.svm.f1", "label": "SVM F1"},
126
- {"key": "metrics.rf.f1", "label": "RF F1"},
127
- ],
128
- "classifiers-auc": [
129
- {"key": "metrics.nb.auc", "label": "NB AUC"},
130
- {"key": "metrics.svm.auc", "label": "SVM AUC"},
131
- {"key": "metrics.rf.auc", "label": "RF AUC"},
132
- ],
133
- }
134
-
135
-
136
- def get_results_for_dataset(dataset):
137
- if dataset in RESULT_CACHE:
138
- leaderboard = rank_results(RESULT_CACHE[dataset])
139
- else:
140
- results = load_result_json(dataset)
141
- if results is None:
142
- results = run_agent_for_dataset(dataset)
143
- if results:
144
- save_result_json(dataset, results)
145
- RESULT_CACHE[dataset] = results or []
146
- leaderboard = rank_results(results or [])
147
- if not isinstance(leaderboard, list):
148
- if hasattr(leaderboard, "to_dict"):
149
- leaderboard = leaderboard.to_dict(orient="records")
150
- else:
151
- leaderboard = list(leaderboard)
152
- return leaderboard
153
-
154
-
155
- def get_metric_value(row, key):
156
- value = row
157
- for part in key.split("."):
158
- if isinstance(value, dict):
159
- value = value.get(part)
160
- else:
161
- return None
162
- return value
163
-
164
-
165
- def get_feature_count(row):
166
- num_features = row.get("num_features")
167
- if isinstance(num_features, (int, float)):
168
- return int(num_features)
169
- selected = row.get("selected_features")
170
- if isinstance(selected, list):
171
- return len(selected)
172
- return 0
173
-
174
-
175
- def apply_filters(results, dataset_meta, min_f1, max_features, del_range, complexity, selected_algos):
176
- total_features = dataset_meta.get("total_features") if dataset_meta else None
177
- filtered = []
178
- min_del = (del_range[0] if del_range else 0) / 100
179
- max_del = (del_range[1] if del_range else 100) / 100
180
- min_f1 = min_f1 if min_f1 is not None else 0
181
- max_features = max_features if max_features is not None else float("inf")
182
- selected_algos = selected_algos if selected_algos else None
183
- for r in results:
184
- algo = r.get("algorithm")
185
- if selected_algos and algo not in selected_algos:
186
- continue
187
- raw_f1 = r.get("mean_f1")
188
- try:
189
- f1 = float(raw_f1) if raw_f1 is not None else 0
190
- except (TypeError, ValueError):
191
- f1 = 0
192
- if f1 < min_f1:
193
- continue
194
- feats = get_feature_count(r)
195
- if feats > max_features:
196
- continue
197
- if isinstance(total_features, (int, float)) and total_features > 0:
198
- del_rate = 1 - (feats / total_features)
199
- if del_rate < min_del or del_rate > max_del:
200
- continue
201
- if complexity and complexity != "all":
202
- comp = DISPLAY_COMPLEXITY.get(algo, {}).get("time")
203
- if comp != complexity:
204
- continue
205
- filtered.append(r)
206
- return filtered
207
-
208
-
209
- def build_score_figure(results, view_mode):
210
- if not results:
211
- fig = go.Figure()
212
- fig.add_annotation(
213
- text="No Data Available",
214
- x=0.5,
215
- y=0.5,
216
- xref="paper",
217
- yref="paper",
218
- showarrow=False,
219
- font=dict(size=16, color="#999"),
220
- )
221
- fig.update_layout(
222
- xaxis=dict(visible=False),
223
- yaxis=dict(visible=False),
224
- margin=dict(l=20, r=20, t=20, b=20),
225
- )
226
- return fig
227
- top = results[:20]
228
- labels = [r.get("algorithm") for r in top]
229
- fig = go.Figure()
230
- if view_mode == "overall":
231
- fig.add_trace(go.Bar(
232
- name="Mean F1",
233
- y=labels,
234
- x=[r.get("mean_f1") for r in top],
235
- orientation="h",
236
- marker_color="rgba(52, 152, 219, 0.7)",
237
- ))
238
- fig.add_trace(go.Bar(
239
- name="Mean AUC",
240
- y=labels,
241
- x=[r.get("mean_auc") for r in top],
242
- orientation="h",
243
- marker_color="rgba(46, 204, 113, 0.7)",
244
- ))
245
- elif view_mode == "classifiers-f1":
246
- for idx, clf in enumerate(["nb", "svm", "rf"]):
247
- fig.add_trace(go.Bar(
248
- name=clf.upper(),
249
- y=labels,
250
- x=[get_metric_value(r, f"metrics.{clf}.f1") for r in top],
251
- orientation="h",
252
- marker_color=f"hsla({200 + idx * 40}, 70%, 60%, 0.7)",
253
- ))
254
- else:
255
- for idx, clf in enumerate(["nb", "svm", "rf"]):
256
- fig.add_trace(go.Bar(
257
- name=clf.upper(),
258
- y=labels,
259
- x=[get_metric_value(r, f"metrics.{clf}.auc") for r in top],
260
- orientation="h",
261
- marker_color=f"hsla({100 + idx * 40}, 70%, 60%, 0.7)",
262
- ))
263
- fig.update_layout(
264
- barmode="group",
265
- margin=dict(l=20, r=20, t=20, b=20),
266
- legend=dict(orientation="h"),
267
- yaxis=dict(autorange="reversed"),
268
- )
269
- return fig
270
-
271
-
272
- def build_pareto_figure(results):
273
- x_vals = [get_feature_count(r) for r in results]
274
- y_vals = [r.get("mean_f1") for r in results]
275
- labels = [r.get("algorithm") for r in results]
276
- fig = go.Figure()
277
- fig.add_trace(go.Scatter(
278
- x=x_vals,
279
- y=y_vals,
280
- mode="markers",
281
- text=labels,
282
- marker=dict(color="rgba(230, 126, 34, 0.7)", size=10),
283
- ))
284
- fig.update_layout(
285
- margin=dict(l=20, r=20, t=20, b=20),
286
- xaxis_title="Num Features",
287
- yaxis_title="Mean F1",
288
- )
289
- return fig
290
-
291
-
292
- def build_table(results, view_mode):
293
- config = VIEW_CONFIG[view_mode]
294
- headers = ["Rank", "Algorithm"] + [c["label"] for c in config] + ["Selected Features"]
295
- col_keys = [c["key"] for c in config]
296
- max_map = {}
297
- for key in col_keys:
298
- vals = []
299
- for r in results:
300
- v = get_metric_value(r, key)
301
- try:
302
- v = float(v) if v is not None else None
303
- except Exception:
304
- v = None
305
- if v is not None:
306
- vals.append(v)
307
- max_map[key] = max(vals) if vals else 0
308
- thead = html.Thead(
309
- html.Tr([html.Th(h, className="cth") for h in headers], className="chead")
310
- )
311
- rows = []
312
- if not results:
313
- empty_cells = [html.Td("", className="ctd")] * (len(headers) - 2)
314
- rows.append(
315
- html.Tr(
316
- [html.Td("", className="ctd"), html.Td("No Data Available", className="ctd")]+empty_cells,
317
- className="crow"
318
- )
319
- )
320
- else:
321
- for idx, r in enumerate(results):
322
- rank = idx + 1
323
- medal = {1: "🥇", 2: "🥈", 3: "🥉"}.get(rank, str(rank))
324
- row_class = (
325
- "crow crow-gold" if rank == 1 else
326
- "crow crow-silver" if rank == 2 else
327
- "crow crow-bronze" if rank == 3 else
328
- "crow"
329
- )
330
- algo = r.get("algorithm") or "Unknown"
331
- metric_tds = []
332
- for c in config:
333
- key = c["key"]
334
- raw = get_metric_value(r, key)
335
- try:
336
- val = float(raw) if raw is not None else 0.0
337
- except Exception:
338
- val = 0.0
339
- m = max_map.get(key) or 0.0
340
- pct = (val / m * 100.0) if m > 0 else 0
341
- is_max = (m > 0 and abs(val - m) < 1e-12)
342
- bar = html.Div(
343
- [
344
- html.Div(className="bar-track", children=html.Div(className="bar-fill", style={"width": f"{pct:.2f}%"})),
345
- html.Span(f"{val:.4f}", className=("bar-text is-max" if is_max else "bar-text")),
346
- ],
347
- className="bar-cell",
348
- title=f"max={m:.4f}" if is_max else None,
349
- )
350
- cell = html.Td(bar, className="ctd cnum")
351
- metric_tds.append(cell)
352
- selected = r.get("selected_features")
353
- feat_count = get_feature_count(r)
354
- if isinstance(selected, list):
355
- features_title = ", ".join(str(s) for s in selected)
356
- else:
357
- features_title = "N/A"
358
- feature_td = html.Td(
359
- f"{feat_count} features",
360
- className="ctd cfeat",
361
- title=features_title,
362
- style={"whiteSpace": "nowrap"},
363
- )
364
- row = html.Tr(
365
- [html.Td(medal, className="ctd crank"), html.Td(algo, className="ctd calgo")] + metric_tds + [feature_td],
366
- className=row_class,
367
- )
368
- rows.append(row)
369
- tbody = html.Tbody(rows)
370
- table = html.Table([thead, tbody], className="custom-table")
371
- return html.Div(className="table-container", children=table)
372
-
373
-
374
- dataset_options = [{"label": name, "value": name} for name in sorted(DATASET_METADATA.keys())]
375
- default_dataset = "Authorship" if "Authorship" in DATASET_METADATA else (dataset_options[0]["value"] if dataset_options else "Authorship")
376
-
377
- complexity_options = sorted({v.get("time") for v in DISPLAY_COMPLEXITY.values() if v.get("time")})
378
- complexity_data = [{"label": "All Complexities", "value": "all"}] + [
379
- {"label": c, "value": c} for c in complexity_options
380
- ]
381
-
382
- dash_app = Dash(__name__, server=server, url_base_pathname="/")
383
- app = dash_app
384
-
385
- css = """
386
- :root {
387
- --primary-color: #3498db;
388
- --secondary-color: #2c3e50;
389
- --background-color: #f8f9fa;
390
- --text-color: #333;
391
- --border-color: #dee2e6;
392
- --hover-color: #f1f1f1;
393
- --accent-color: #e67e22;
394
- --sidebar-width: 280px;
395
- }
396
- body {
397
- font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
398
- margin: 0;
399
- padding: 0;
400
- background-color: var(--background-color);
401
- color: var(--text-color);
402
- }
403
- .app-shell {
404
- display: flex;
405
- min-height: 100vh;
406
- }
407
- .sidebar {
408
- width: var(--sidebar-width);
409
- background-color: var(--secondary-color);
410
- color: white;
411
- position: fixed;
412
- height: 100vh;
413
- overflow-y: auto;
414
- padding: 20px;
415
- box-sizing: border-box;
416
- left: 0;
417
- top: 0;
418
- z-index: 100;
419
- display: flex;
420
- flex-direction: column;
421
- gap: 20px;
422
- }
423
- .sidebar h2 {
424
- font-size: 1.1em;
425
- margin-bottom: 10px;
426
- color: #ecf0f1;
427
- border-bottom: 1px solid #34495e;
428
- padding-bottom: 5px;
429
- }
430
- .main-content {
431
- margin-left: var(--sidebar-width);
432
- padding: 24px;
433
- width: calc(100% - var(--sidebar-width));
434
- box-sizing: border-box;
435
- }
436
- .stats-grid {
437
- display: grid;
438
- grid-template-columns: 1fr;
439
- gap: 10px;
440
- }
441
- .stat-card {
442
- background: rgba(255,255,255,0.1);
443
- padding: 10px;
444
- border-radius: 6px;
445
- text-align: center;
446
- }
447
- .stat-value {
448
- font-size: 1.2em;
449
- font-weight: 600;
450
- color: var(--accent-color);
451
- }
452
- .stat-label {
453
- font-size: 0.8em;
454
- color: #bdc3c7;
455
- }
456
- .card {
457
- background: white;
458
- padding: 16px;
459
- border-radius: 8px;
460
- box-shadow: 0 1px 3px rgba(0,0,0,0.1);
461
- }
462
- .chart-card {
463
- background: white;
464
- padding: 16px;
465
- border-radius: 8px;
466
- box-shadow: 0 1px 3px rgba(0,0,0,0.1);
467
- height: 420px;
468
- display: flex;
469
- flex-direction: column;
470
- }
471
- .chart-card .dash-graph {
472
- flex: 1;
473
- }
474
- .table-container {
475
- background: white;
476
- padding: 12px;
477
- border-radius: 8px;
478
- box-shadow: 0 1px 3px rgba(0,0,0,0.1);
479
- }
480
- .nav-links {
481
- list-style: none;
482
- padding: 0;
483
- margin: 0;
484
- }
485
- .nav-links li a {
486
- display: block;
487
- padding: 8px;
488
- color: #bdc3c7;
489
- text-decoration: none;
490
- border-radius: 4px;
491
- }
492
- .nav-links li a:hover {
493
- background: rgba(255,255,255,0.1);
494
- color: white;
495
- }
496
-
497
- /* Custom Table Styles */
498
- .custom-table-wrapper {
499
- overflow-x: auto;
500
- overflow-y: auto;
501
- max-height: 520px;
502
- background: #fff;
503
- border: 1px solid #eee;
504
- border-radius: 8px;
505
- box-shadow: 0 1px 3px rgba(0,0,0,0.06);
506
- }
507
- .custom-table {
508
- width: 100%;
509
- border-collapse: separate;
510
- border-spacing: 0;
511
- table-layout: fixed;
512
- }
513
- .custom-table thead th {
514
- text-align: left;
515
- border-bottom: 2px solid var(--border-color);
516
- padding: 10px;
517
- }
518
- .custom-table tbody td {
519
- padding: 8px 10px;
520
- border-bottom: 1px solid #eee;
521
- vertical-align: middle;
522
- }
523
- .custom-table tbody tr:hover {
524
- background: #fafafa;
525
- transition: background 0.2s ease;
526
- }
527
- .custom-table tbody tr:nth-child(even) { background: #fcfcfc; }
528
- .custom-table thead th {
529
- position: sticky;
530
- top: 0;
531
- background: #fff;
532
- z-index: 1;
533
- }
534
- .cnum { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace; text-align: right; }
535
- .is-max { font-weight: 600; color: var(--accent-color); }
536
- .crow-gold { background: rgba(255,215,0,0.12); }
537
- .crow-silver { background: rgba(192,192,192,0.12); }
538
- .crow-bronze { background: rgba(205,127,50,0.12); }
539
- .crank { width: 56px; text-align: center; }
540
- .calgo { font-weight: 500; }
541
- .cth { background: var(--background-color); }
542
- .cfeat { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
543
-
544
- /* In-cell Data Bars */
545
- .bar-cell {
546
- position: relative;
547
- height: 26px;
548
- display: flex;
549
- align-items: center;
550
- justify-content: flex-end;
551
- }
552
- .bar-track {
553
- position: absolute;
554
- left: 6px;
555
- right: 6px;
556
- height: 60%;
557
- background: #f4f7fb;
558
- border: 1px solid #e6eef7;
559
- border-radius: 6px;
560
- overflow: hidden;
561
- }
562
- .bar-fill {
563
- height: 100%;
564
- background: linear-gradient(90deg, #7db9e8 0%, #3498db 100%);
565
- opacity: 0.35;
566
- transition: width 200ms ease;
567
- }
568
- .bar-text {
569
- position: relative;
570
- z-index: 1;
571
- font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
572
- padding: 0 6px;
573
- line-height: 1;
574
- }
575
- """
576
-
577
- dash_app.index_string = f"""
578
- <!DOCTYPE html>
579
- <html>
580
- <head>
581
- {{%metas%}}
582
- <title>AutoFS Leaderboard</title>
583
- {{%favicon%}}
584
- {{%css%}}
585
- <style>{css}</style>
586
- </head>
587
- <body>
588
- {{%app_entry%}}
589
- <footer>
590
- {{%config%}}
591
- {{%scripts%}}
592
- {{%renderer%}}
593
- </footer>
594
- </body>
595
- </html>
596
- """
597
-
598
- dash_app.layout = dmc.MantineProvider(
599
- children=html.Div(
600
- className="app-shell",
601
- children=[
602
- html.Aside(
603
- className="sidebar",
604
- children=[
605
- html.Div(
606
- [
607
- html.H1("AutoFS", style={"fontSize": "1.5em", "margin": 0, "color": "white"}),
608
- html.Div("Feature Selection Leaderboard", style={"fontSize": "0.8em", "color": "#bdc3c7"}),
609
- ],
610
- style={"textAlign": "center", "marginBottom": "10px"},
611
- ),
612
- html.Div(
613
- className="stats-grid",
614
- children=[
615
- html.Div([html.Div("-", id="stat-count", className="stat-value"), html.Div("Methods", className="stat-label")], className="stat-card"),
616
- html.Div([html.Div("-", id="stat-best", className="stat-value"), html.Div("Best F1", className="stat-label")], className="stat-card"),
617
- html.Div([html.Div("-", id="stat-updated", className="stat-value"), html.Div("Updated", className="stat-label")], className="stat-card"),
618
- ],
619
- ),
620
- html.Div(
621
- [
622
- html.H2("Navigation"),
623
- html.Ul(
624
- className="nav-links",
625
- children=[
626
- html.Li(html.A("📊 Overview", href="#overview")),
627
- html.Li(html.A("🏆 Leaderboard", href="#main-table")),
628
- html.Li(html.A("📈 Charts", href="#charts")),
629
- html.Li(html.A("ℹ️ Details", href="#details")),
630
- html.Li(html.A("🌍 Global Rankings", href="/global")),
631
- html.Li(html.A("📤 Submit Data/Method", href="/submit")),
632
- ],
633
- ),
634
- ]
635
- ),
636
- html.Div(
637
- [
638
- html.H2("Global Controls"),
639
- dmc.Select(
640
- id="view-mode",
641
- data=[
642
- {"label": "Overall (Mean)", "value": "overall"},
643
- {"label": "F1 by Classifier", "value": "classifiers-f1"},
644
- {"label": "AUC by Classifier", "value": "classifiers-auc"},
645
- ],
646
- value="overall",
647
- clearable=False,
648
- style={"marginBottom": "10px"},
649
- ),
650
- ]
651
- ),
652
- html.Div(
653
- [
654
- html.H2("Filters"),
655
- dmc.Select(
656
- id="dataset-select",
657
- data=dataset_options,
658
- value="Authorship",
659
- clearable=False,
660
- style={"marginBottom": "10px"},
661
- ),
662
- html.Div(
663
- [
664
- html.Div(
665
- [
666
- html.Span("Min F1 Score: "),
667
- html.Span("0.0000", id="val-f1", style={"color": "var(--accent-color)"}),
668
- ],
669
- style={"marginBottom": "6px", "color": "#bdc3c7"},
670
- ),
671
- dmc.Slider(id="filter-f1", min=0, max=1, step=0.0001, value=0),
672
- ],
673
- style={"marginBottom": "12px"},
674
- ),
675
- html.Div(
676
- [
677
- html.Div(
678
- [
679
- html.Span("Del. Rate: "),
680
- html.Span("0% - 100%", id="val-del-rate", style={"color": "var(--accent-color)"}),
681
- ],
682
- style={"marginBottom": "6px", "color": "#bdc3c7"},
683
- ),
684
- dmc.RangeSlider(id="filter-del-rate", min=0, max=100, value=[0, 100], step=1),
685
- ],
686
- style={"marginBottom": "12px"},
687
- ),
688
- html.Div(
689
- [
690
- html.Div(
691
- [
692
- html.Span("Max Features: "),
693
- html.Span("All", id="val-feats", style={"color": "var(--accent-color)"}),
694
- ],
695
- style={"marginBottom": "6px", "color": "#bdc3c7"},
696
- ),
697
- dmc.Slider(id="filter-feats", min=1, max=100, step=1, value=100),
698
- ],
699
- style={"marginBottom": "12px"},
700
- ),
701
- dmc.Select(
702
- id="filter-complexity",
703
- data=complexity_data,
704
- value="all",
705
- clearable=False,
706
- style={"marginBottom": "12px"},
707
- ),
708
- dmc.CheckboxGroup(id="filter-algos", children=[], value=[], orientation="vertical"),
709
- ]
710
- ),
711
- ],
712
- ),
713
- html.Main(
714
- className="main-content",
715
- children=[
716
- html.Header(
717
- [
718
- html.H1("🏆 Leaderboard Dashboard", style={"color": "var(--secondary-color)", "margin": 0}),
719
- html.Div("Comprehensive benchmark of feature selection algorithms across diverse datasets.", className="subtitle"),
720
- ]
721
- ),
722
- html.Div(
723
- className="card",
724
- children=[
725
- html.P([
726
- "Feature selection is a critical step in machine learning and data analysis, aimed at ",
727
- html.Strong("identifying the most relevant subset of features"),
728
- " from a high-dimensional dataset. By eliminating irrelevant or redundant features, feature selection not only ",
729
- html.Strong("improves model interpretability"),
730
- " but also ",
731
- html.Strong("enhances predictive performance"),
732
- " and ",
733
- html.Strong("reduces computational cost"),
734
- ".",
735
- ]),
736
- html.P([
737
- "This leaderboard presents a comprehensive comparison of various feature selection algorithms across multiple benchmark datasets. It includes several ",
738
- html.Strong("information-theoretic and mutual information-based methods"),
739
- ", which quantify the statistical dependency between features and the target variable to rank feature relevance. Mutual information approaches are particularly effective in ",
740
- html.Strong("capturing both linear and non-linear relationships"),
741
- ", making them suitable for complex datasets where classical correlation-based methods may fail.",
742
- ]),
743
- html.P([
744
- "The leaderboard is structured to reflect algorithm performance across different datasets, allowing for an objective assessment of each method’s ability to select informative features. For each method and dataset combination, metrics such as ",
745
- html.Strong("classification accuracy, F1-score, and area under the ROC curve (AUC)"),
746
- " are reported, providing insights into how the selected features contribute to predictive modeling.",
747
- ]),
748
- html.P([
749
- "By examining this feature selection leaderboard, researchers and practitioners can gain a better understanding of which methods perform consistently well across diverse domains, helping to guide the choice of feature selection strategies in real-world applications. This serves as a valuable resource for both benchmarking and method development in the field of feature selection.",
750
- ]),
751
- ],
752
- style={"marginTop": "16px"},
753
- ),
754
- dmc.Grid(
755
- id="overview",
756
- gutter="md",
757
- style={"marginTop": "16px"},
758
- children=[
759
- dmc.Col(
760
- span=12,
761
- md=6,
762
- children=html.Div(
763
- className="card",
764
- children=[
765
- html.H3("About This Dataset"),
766
- html.P(["Analyzing performance on ", html.Strong(html.Span("Selected", id="desc-dataset-name")), "."]),
767
- ],
768
- ),
769
- ),
770
- dmc.Col(
771
- span=12,
772
- md=6,
773
- children=html.Div(
774
- className="card",
775
- children=[
776
- html.H3("Dataset Metadata"),
777
- html.Div(["Name: ", html.Span("-", id="meta-name")]),
778
- html.Div(["Samples: ", html.Span("-", id="meta-samples"), " | Features: ", html.Span("-", id="meta-features")]),
779
- html.Div(["Last Updated: ", html.Span("-", id="meta-updated")]),
780
- ],
781
- ),
782
- ),
783
- ],
784
- ),
785
- html.Div(
786
- id="main-table",
787
- style={"marginTop": "24px"},
788
- children=[
789
- html.H3("📋 Detailed Rankings"),
790
- html.Div(id="custom-table-container", className="custom-table-wrapper"),
791
- ],
792
- ),
793
- html.Div(
794
- id="charts",
795
- style={"marginTop": "24px"},
796
- children=[
797
- dmc.Grid(
798
- gutter="md",
799
- children=[
800
- dmc.Col(
801
- span=12,
802
- md=6,
803
- children=html.Div(
804
- className="chart-card",
805
- children=[
806
- html.H3("📊 Performance Comparison"),
807
- dcc.Graph(id="score-graph", config={"responsive": True}, style={"height": "100%"}),
808
- ],
809
- ),
810
- ),
811
- dmc.Col(
812
- span=12,
813
- md=6,
814
- children=html.Div(
815
- className="chart-card",
816
- children=[
817
- html.H3("📉 Pareto Frontier (Trade-off)"),
818
- html.Div("X: Selected Features vs Y: F1 Score (Top-Left is better)", style={"fontSize": "0.9em", "color": "#666"}),
819
- dcc.Graph(id="pareto-graph", config={"responsive": True}, style={"height": "100%"}),
820
- ],
821
- ),
822
- ),
823
- ],
824
- )
825
- ],
826
- ),
827
- html.Div(
828
- id="details",
829
- style={"marginTop": "50px", "color": "#999", "textAlign": "center", "borderTop": "1px solid #eee", "paddingTop": "20px"},
830
- children="AutoFS Benchmark Platform © 2026",
831
- ),
832
- ],
833
- ),
834
- ],
835
- )
836
- )
837
-
838
-
839
- @dash_app.callback(
840
- Output("filter-feats", "max"),
841
- Output("filter-feats", "value"),
842
- Output("filter-f1", "min"),
843
- Output("filter-f1", "max"),
844
- Output("filter-f1", "value"),
845
- Output("filter-algos", "children"),
846
- Output("filter-algos", "value"),
847
- Output("meta-name", "children"),
848
- Output("meta-samples", "children"),
849
- Output("meta-features", "children"),
850
- Output("meta-updated", "children"),
851
- Output("desc-dataset-name", "children"),
852
- Output("stat-updated", "children"),
853
- Output("stat-count", "children"),
854
- Output("stat-best", "children"),
855
- Output("score-graph", "figure"),
856
- Output("pareto-graph", "figure"),
857
- Output("custom-table-container", "children"),
858
- Output("val-f1", "children"),
859
- Output("val-feats", "children"),
860
- Output("val-del-rate", "children"),
861
- Input("dataset-select", "value"),
862
- Input("view-mode", "value"),
863
- Input("filter-f1", "value"),
864
- Input("filter-feats", "value"),
865
- Input("filter-del-rate", "value"),
866
- Input("filter-complexity", "value"),
867
- Input("filter-algos", "value"),
868
- State("filter-f1", "min"),
869
- State("filter-f1", "max"),
870
- State("filter-feats", "max"),
871
- State("filter-algos", "children"),
872
- State("filter-algos", "value"),
873
- )
874
- def update_dashboard_all(
875
- dataset,
876
- view_mode,
877
- min_f1_value,
878
- max_features_value,
879
- del_range,
880
- complexity,
881
- selected_algos,
882
- f1_min_state,
883
- f1_max_state,
884
- feats_max_state,
885
- algo_children_state,
886
- algo_value_state,
887
- ):
888
- triggered_id = callback_context.triggered_id if callback_context.triggered else None
889
- dataset_changed = triggered_id == "dataset-select" or triggered_id is None
890
- selected = dataset or "Authorship"
891
- meta = DATASET_METADATA.get(selected, {"name": selected, "last_updated": "-", "num_samples": None, "total_features": None})
892
- results = get_results_for_dataset(selected)
893
- algo_list = sorted({r.get("algorithm") for r in results if r.get("algorithm")})
894
- if dataset_changed:
895
- f1_scores = [r.get("mean_f1") for r in results if r.get("mean_f1") is not None]
896
- if f1_scores:
897
- min_f1 = min(f1_scores)
898
- safe_min = max(0, math.floor((min_f1 - 0.1) * 10) / 10)
899
- else:
900
- safe_min = 0
901
- max_feats = meta.get("total_features") or 100
902
- f1_min = safe_min
903
- f1_max = 1
904
- f1_value = safe_min
905
- feats_max = max_feats
906
- feats_value = max_feats
907
- algo_children = [dmc.Checkbox(label=a, value=a) for a in algo_list]
908
- algo_value = algo_list
909
- else:
910
- f1_min = f1_min_state if f1_min_state is not None else 0
911
- f1_max = f1_max_state if f1_max_state is not None else 1
912
- f1_value = min_f1_value if min_f1_value is not None else f1_min
913
- feats_max = feats_max_state if feats_max_state is not None else (meta.get("total_features") or 100)
914
- feats_value = max_features_value if max_features_value is not None else feats_max
915
- if algo_children_state:
916
- algo_children = algo_children_state
917
- else:
918
- algo_children = [dmc.Checkbox(label=a, value=a) for a in algo_list]
919
- if selected_algos is not None:
920
- algo_value = selected_algos
921
- else:
922
- algo_value = algo_value_state if algo_value_state is not None else algo_list
923
- filtered = apply_filters(results, meta, f1_value or 0, feats_value, del_range, complexity, algo_value or [])
924
- count = len(filtered)
925
- if filtered:
926
- best = max(filtered, key=lambda r: r.get("mean_f1") or 0)
927
- best_text = f"{best.get('algorithm')} ({(best.get('mean_f1') or 0):.3f})"
928
- else:
929
- best_text = "-"
930
- score_fig = build_score_figure(filtered, view_mode or "overall")
931
- pareto_fig = build_pareto_figure(filtered)
932
- table_component = build_table(filtered, view_mode or "overall")
933
- val_f1 = f"{(f1_value or 0):.4f}"
934
- val_feats = str(int(feats_value)) if isinstance(feats_value, (int, float)) else "All"
935
- del_min = del_range[0] if del_range else 0
936
- del_max = del_range[1] if del_range else 100
937
- val_del = f"{del_min:.0f}% - {del_max:.0f}%"
938
- meta_samples = meta.get("num_samples") if meta.get("num_samples") is not None else "Unavailable"
939
- meta_features = meta.get("total_features") if meta.get("total_features") is not None else "Unavailable"
940
- return (
941
- feats_max,
942
- feats_value,
943
- f1_min,
944
- f1_max,
945
- f1_value,
946
- algo_children,
947
- algo_value,
948
- meta.get("name", "-"),
949
- meta_samples,
950
- meta_features,
951
- meta.get("last_updated", "-"),
952
- meta.get("name", "-"),
953
- meta.get("last_updated", "-"),
954
- count,
955
- best_text,
956
- score_fig,
957
- pareto_fig,
958
- table_component,
959
- val_f1,
960
- val_feats,
961
- val_del,
962
- )
963
-
964
-
965
- def sanitize_json(value):
966
- if value is None or isinstance(value, (str, int, float, bool)):
967
- return value
968
- if np and isinstance(value, np.generic):
969
- return value.item()
970
- if np and isinstance(value, np.ndarray):
971
- return value.tolist()
972
- if pd and isinstance(value, (pd.DataFrame, pd.Series)):
973
- if isinstance(value, pd.DataFrame):
974
- return value.to_dict(orient="records")
975
- return value.to_dict()
976
- if isinstance(value, (datetime.datetime, datetime.date)):
977
- return value.isoformat()
978
- if isinstance(value, dict):
979
- return {str(k): sanitize_json(v) for k, v in value.items()}
980
- if isinstance(value, (list, tuple, set)):
981
- return [sanitize_json(v) for v in value]
982
- if hasattr(value, "to_dict"):
983
- return sanitize_json(value.to_dict())
984
- return str(value)
985
-
986
-
987
- @server.route("/global")
988
- def global_view():
989
- return render_template("global.html")
990
-
991
-
992
- @server.route("/submit")
993
- def submit_view():
994
- return render_template("submit.html")
995
-
996
-
997
- @server.route("/api/results")
998
- def get_results_api():
999
- try:
1000
- dataset = request.args.get("dataset") or "Authorship"
1001
- leaderboard = get_results_for_dataset(dataset)
1002
- return jsonify(sanitize_json(leaderboard))
1003
- except Exception as e:
1004
- print(e)
1005
- return jsonify({"error": str(e)})
1006
-
1007
-
1008
- @server.route("/api/datasets")
1009
- def api_datasets():
1010
- try:
1011
- datasets = []
1012
- for name, meta in DATASET_METADATA.items():
1013
- datasets.append({
1014
- "name": name,
1015
- "last_updated": meta.get("last_updated"),
1016
- "num_samples": meta.get("num_samples") if meta.get("num_samples") is not None else "Unavailable",
1017
- "total_features": meta.get("total_features") if meta.get("total_features") is not None else "Unavailable",
1018
- })
1019
- return jsonify(sanitize_json(datasets))
1020
- except Exception as e:
1021
- print(e)
1022
- return jsonify({"error": str(e)})
1023
-
1024
-
1025
- @server.route("/api/global_stats")
1026
- def api_global_stats():
1027
- try:
1028
- algo_totals = {}
1029
- algo_counts = {}
1030
- for dataset in DATASET_METADATA.keys():
1031
- results = get_results_for_dataset(dataset) or []
1032
- for row in results:
1033
- algo = row.get("algorithm") or "Unknown"
1034
- mean_f1 = row.get("mean_f1")
1035
- mean_auc = row.get("mean_auc")
1036
- if mean_f1 is None and mean_auc is None:
1037
- continue
1038
- totals = algo_totals.get(algo, {"f1": 0.0, "auc": 0.0})
1039
- counts = algo_counts.get(algo, {"f1": 0, "auc": 0})
1040
- if mean_f1 is not None:
1041
- totals["f1"] += float(mean_f1)
1042
- counts["f1"] += 1
1043
- if mean_auc is not None:
1044
- totals["auc"] += float(mean_auc)
1045
- counts["auc"] += 1
1046
- algo_totals[algo] = totals
1047
- algo_counts[algo] = counts
1048
- global_stats = []
1049
- for algo, totals in algo_totals.items():
1050
- counts = algo_counts.get(algo, {"f1": 0, "auc": 0})
1051
- mean_f1_global = totals["f1"] / counts["f1"] if counts["f1"] else None
1052
- mean_auc_global = totals["auc"] / counts["auc"] if counts["auc"] else None
1053
- global_stats.append({
1054
- "algorithm": algo,
1055
- "mean_f1_global": mean_f1_global,
1056
- "mean_auc_global": mean_auc_global,
1057
- })
1058
- return jsonify(sanitize_json(global_stats))
1059
- except Exception as e:
1060
- print(e)
1061
- return jsonify({"error": str(e)})
1062
-
1063
-
1064
- @server.route("/api/algos")
1065
- def api_algorithms():
1066
- return jsonify(DISPLAY_COMPLEXITY)
1067
-
1068
-
1069
- @server.route("/pdfs/<path:filename>")
1070
- def serve_pdf(filename):
1071
- return send_from_directory(PDF_DIR, filename)
1072
-
1073
-
1074
- if __name__ == "__main__":
1075
- port = int(os.environ.get("PORT", 7865))
1076
- print(f"Loaded {len(DATASET_METADATA)} datasets from {RESULT_DIR}")
1077
- app.run(host="0.0.0.0", port=port, debug=False)