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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dash import Dash
3
+
4
+ # =====================================================
5
+ # 全局变量(只声明,不初始化!)
6
+ # =====================================================
7
+
8
+ DATASET_METADATA = None
9
+ DISPLAY_COMPLEXITY = None
10
+ dataset_options = None
11
+ complexity_data = None
12
+
13
+ INITIALIZED = False
14
+
15
+ RESULT_DIR = "/code/results"
16
+
17
+ # =====================================================
18
+ # 原有函数(保持你的实现)
19
+ # =====================================================
20
+
21
+ def build_dataset_metadata():
22
+ """
23
+ 你的原始实现
24
+ """
25
+ metadata = {}
26
+ for name in list_available_datasets():
27
+ last_updated = datetime.datetime.fromtimestamp(1707382400).strftime("%Y-%m-%d")
28
+ num_samples = None
29
+ total_features = None
30
+ if scipy:
31
+ mat_path = os.path.join(DATA_DIR, f"{name}.mat")
32
+ if os.path.exists(mat_path):
33
+ try:
34
+ mat = scipy.io.loadmat(mat_path)
35
+ if "X" in mat:
36
+ X = mat["X"]
37
+ num_samples, total_features = X.shape
38
+ except Exception:
39
+ num_samples = None
40
+ total_features = None
41
+ metadata[name] = {
42
+ "name": name,
43
+ "last_updated": last_updated,
44
+ "num_samples": num_samples,
45
+ "total_features": total_features,
46
+ }
47
+
48
+ print(f"Loaded datasets from {RESULT_DIR}")
49
+ return metadata
50
+
51
+
52
+ def build_complexity_display():
53
+ """
54
+ 你的原始实现
55
+ """
56
+ display_complexity = {}
57
+ for algo, comp in ALGO_COMPLEXITY.items():
58
+ t = comp.get("time", "")
59
+ s = comp.get("space", "")
60
+ t_disp = t.replace("**", "^").replace(" * ", "")
61
+ if "O(" not in t_disp:
62
+ t_disp = f"O({t_disp})" if t_disp else ""
63
+ s_disp = s.replace("**", "^").replace(" * ", "")
64
+ if "O(" not in s_disp:
65
+ s_disp = f"O({s_disp})" if s_disp else ""
66
+ display_complexity[algo] = {"time": t_disp, "space": s_disp}
67
+ return display_complexity
68
+
69
+
70
+
71
+ # =====================================================
72
+ # ⭐ 关键:只初始化一次(Lazy Init)
73
+ # =====================================================
74
+
75
+ def initialize_once():
76
+ global INITIALIZED
77
+ global DATASET_METADATA
78
+ global DISPLAY_COMPLEXITY
79
+ global dataset_options
80
+ global complexity_data
81
+
82
+ if INITIALIZED:
83
+ return
84
+
85
+ print("Initializing system ...")
86
+
87
+ DATASET_METADATA = build_dataset_metadata()
88
+ DISPLAY_COMPLEXITY = build_complexity_display()
89
+
90
+ dataset_options = [
91
+ {"label": name, "value": name}
92
+ for name in sorted(DATASET_METADATA.keys())
93
+ ]
94
+
95
+ complexity_options = sorted({
96
+ v.get("time")
97
+ for v in DISPLAY_COMPLEXITY.values()
98
+ if v.get("time")
99
+ })
100
+
101
+ complexity_data = (
102
+ [{"label": "All Complexities", "value": "all"}]
103
+ + [{"label": c, "value": c} for c in complexity_options]
104
+ )
105
+
106
+ INITIALIZED = True
107
+ print("Initialization finished.")
108
+
109
+
110
+ # =====================================================
111
+ # Dash App 创建(允许被 import)
112
+ # =====================================================
113
+
114
+ app = Dash(__name__)
115
+ server = app.server
116
+
117
+ # 你的 layout 定义(保持原样)
118
+ app.layout =dmc.MantineProvider(
119
+ children=html.Div(
120
+ className="app-shell",
121
+ children=[
122
+ html.Aside(
123
+ className="sidebar",
124
+ children=[
125
+ html.Div(
126
+ [
127
+ html.H1("AutoFS", style={"fontSize": "1.5em", "margin": 0, "color": "white"}),
128
+ html.Div("Feature Selection Leaderboard", style={"fontSize": "0.8em", "color": "#bdc3c7"}),
129
+ ],
130
+ style={"textAlign": "center", "marginBottom": "10px"},
131
+ ),
132
+ html.Div(
133
+ className="stats-grid",
134
+ children=[
135
+ html.Div([html.Div("-", id="stat-count", className="stat-value"), html.Div("Methods", className="stat-label")], className="stat-card"),
136
+ html.Div([html.Div("-", id="stat-best", className="stat-value"), html.Div("Best F1", className="stat-label")], className="stat-card"),
137
+ html.Div([html.Div("-", id="stat-updated", className="stat-value"), html.Div("Updated", className="stat-label")], className="stat-card"),
138
+ ],
139
+ ),
140
+ html.Div(
141
+ [
142
+ html.H2("Navigation"),
143
+ html.Ul(
144
+ className="nav-links",
145
+ children=[
146
+ html.Li(html.A("📊 Overview", href="#overview")),
147
+ html.Li(html.A("🏆 Leaderboard", href="#main-table")),
148
+ html.Li(html.A("📈 Charts", href="#charts")),
149
+ html.Li(html.A("ℹ️ Details", href="#details")),
150
+ html.Li(html.A("🌍 Global Rankings", href="/global")),
151
+ html.Li(html.A("📤 Submit Data/Method", href="/submit")),
152
+ ],
153
+ ),
154
+ ]
155
+ ),
156
+ html.Div(
157
+ [
158
+ html.H2("Global Controls"),
159
+ dmc.Select(
160
+ id="view-mode",
161
+ data=[
162
+ {"label": "Overall (Mean)", "value": "overall"},
163
+ {"label": "F1 by Classifier", "value": "classifiers-f1"},
164
+ {"label": "AUC by Classifier", "value": "classifiers-auc"},
165
+ ],
166
+ value="overall",
167
+ clearable=False,
168
+ style={"marginBottom": "10px"},
169
+ ),
170
+ ]
171
+ ),
172
+ html.Div(
173
+ [
174
+ html.H2("Filters"),
175
+ dmc.Select(
176
+ id="dataset-select",
177
+ data=dataset_options,
178
+ value="Authorship",
179
+ clearable=False,
180
+ style={"marginBottom": "10px"},
181
+ ),
182
+ html.Div(
183
+ [
184
+ html.Div(
185
+ [
186
+ html.Span("Min F1 Score: "),
187
+ html.Span("0.0000", id="val-f1", style={"color": "var(--accent-color)"}),
188
+ ],
189
+ style={"marginBottom": "6px", "color": "#bdc3c7"},
190
+ ),
191
+ dmc.Slider(id="filter-f1", min=0, max=1, step=0.0001, value=0),
192
+ ],
193
+ style={"marginBottom": "12px"},
194
+ ),
195
+ html.Div(
196
+ [
197
+ html.Div(
198
+ [
199
+ html.Span("Del. Rate: "),
200
+ html.Span("0% - 100%", id="val-del-rate", style={"color": "var(--accent-color)"}),
201
+ ],
202
+ style={"marginBottom": "6px", "color": "#bdc3c7"},
203
+ ),
204
+ dmc.RangeSlider(id="filter-del-rate", min=0, max=100, value=[0, 100], step=1),
205
+ ],
206
+ style={"marginBottom": "12px"},
207
+ ),
208
+ html.Div(
209
+ [
210
+ html.Div(
211
+ [
212
+ html.Span("Max Features: "),
213
+ html.Span("All", id="val-feats", style={"color": "var(--accent-color)"}),
214
+ ],
215
+ style={"marginBottom": "6px", "color": "#bdc3c7"},
216
+ ),
217
+ dmc.Slider(id="filter-feats", min=1, max=100, step=1, value=100),
218
+ ],
219
+ style={"marginBottom": "12px"},
220
+ ),
221
+ dmc.Select(
222
+ id="filter-complexity",
223
+ data=complexity_data,
224
+ value="all",
225
+ clearable=False,
226
+ style={"marginBottom": "12px"},
227
+ ),
228
+ dmc.CheckboxGroup(id="filter-algos", children=[], value=[], orientation="vertical"),
229
+ ]
230
+ ),
231
+ ],
232
+ ),
233
+ html.Main(
234
+ className="main-content",
235
+ children=[
236
+ html.Header(
237
+ [
238
+ html.H1("🏆 Leaderboard Dashboard", style={"color": "var(--secondary-color)", "margin": 0}),
239
+ html.Div("Comprehensive benchmark of feature selection algorithms across diverse datasets.", className="subtitle"),
240
+ ]
241
+ ),
242
+ html.Div(
243
+ className="card",
244
+ children=[
245
+ html.P([
246
+ "Feature selection is a critical step in machine learning and data analysis, aimed at ",
247
+ html.Strong("identifying the most relevant subset of features"),
248
+ " from a high-dimensional dataset. By eliminating irrelevant or redundant features, feature selection not only ",
249
+ html.Strong("improves model interpretability"),
250
+ " but also ",
251
+ html.Strong("enhances predictive performance"),
252
+ " and ",
253
+ html.Strong("reduces computational cost"),
254
+ ".",
255
+ ]),
256
+ html.P([
257
+ "This leaderboard presents a comprehensive comparison of various feature selection algorithms across multiple benchmark datasets. It includes several ",
258
+ html.Strong("information-theoretic and mutual information-based methods"),
259
+ ", which quantify the statistical dependency between features and the target variable to rank feature relevance. Mutual information approaches are particularly effective in ",
260
+ html.Strong("capturing both linear and non-linear relationships"),
261
+ ", making them suitable for complex datasets where classical correlation-based methods may fail.",
262
+ ]),
263
+ html.P([
264
+ "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 ",
265
+ html.Strong("classification accuracy, F1-score, and area under the ROC curve (AUC)"),
266
+ " are reported, providing insights into how the selected features contribute to predictive modeling.",
267
+ ]),
268
+ html.P([
269
+ "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.",
270
+ ]),
271
+ ],
272
+ style={"marginTop": "16px"},
273
+ ),
274
+ dmc.Grid(
275
+ id="overview",
276
+ gutter="md",
277
+ style={"marginTop": "16px"},
278
+ children=[
279
+ dmc.Col(
280
+ span=12,
281
+ md=6,
282
+ children=html.Div(
283
+ className="card",
284
+ children=[
285
+ html.H3("About This Dataset"),
286
+ html.P(["Analyzing performance on ", html.Strong(html.Span("Selected", id="desc-dataset-name")), "."]),
287
+ ],
288
+ ),
289
+ ),
290
+ dmc.Col(
291
+ span=12,
292
+ md=6,
293
+ children=html.Div(
294
+ className="card",
295
+ children=[
296
+ html.H3("Dataset Metadata"),
297
+ html.Div(["Name: ", html.Span("-", id="meta-name")]),
298
+ html.Div(["Samples: ", html.Span("-", id="meta-samples"), " | Features: ", html.Span("-", id="meta-features")]),
299
+ html.Div(["Last Updated: ", html.Span("-", id="meta-updated")]),
300
+ ],
301
+ ),
302
+ ),
303
+ ],
304
+ ),
305
+ html.Div(
306
+ id="main-table",
307
+ style={"marginTop": "24px"},
308
+ children=[
309
+ html.H3("📋 Detailed Rankings"),
310
+ html.Div(id="custom-table-container", className="custom-table-wrapper"),
311
+ ],
312
+ ),
313
+ html.Div(
314
+ id="charts",
315
+ style={"marginTop": "24px"},
316
+ children=[
317
+ dmc.Grid(
318
+ gutter="md",
319
+ children=[
320
+ dmc.Col(
321
+ span=12,
322
+ md=6,
323
+ children=html.Div(
324
+ className="chart-card",
325
+ children=[
326
+ html.H3("📊 Performance Comparison"),
327
+ dcc.Graph(id="score-graph", config={"responsive": True}, style={"height": "100%"}),
328
+ ],
329
+ ),
330
+ ),
331
+ dmc.Col(
332
+ span=12,
333
+ md=6,
334
+ children=html.Div(
335
+ className="chart-card",
336
+ children=[
337
+ html.H3("📉 Pareto Frontier (Trade-off)"),
338
+ html.Div("X: Selected Features vs Y: F1 Score (Top-Left is better)", style={"fontSize": "0.9em", "color": "#666"}),
339
+ dcc.Graph(id="pareto-graph", config={"responsive": True}, style={"height": "100%"}),
340
+ ],
341
+ ),
342
+ ),
343
+ ],
344
+ )
345
+ ],
346
+ ),
347
+ html.Div(
348
+ id="details",
349
+ style={"marginTop": "50px", "color": "#999", "textAlign": "center", "borderTop": "1px solid #eee", "paddingTop": "20px"},
350
+ children="AutoFS Benchmark Platform © 2026",
351
+ ),
352
+ ],
353
+ ),
354
+ ],
355
+ )
356
+ )
357
+
358
+
359
+
360
+ # =====================================================
361
+ # ⭐ Callback 中确保初始化
362
+ # =====================================================
363
+
364
+ @app.callback(
365
+ Output("filter-feats", "max"),
366
+ Output("filter-feats", "value"),
367
+ Output("filter-f1", "min"),
368
+ Output("filter-f1", "max"),
369
+ Output("filter-f1", "value"),
370
+ Output("filter-algos", "children"),
371
+ Output("filter-algos", "value"),
372
+ Output("meta-name", "children"),
373
+ Output("meta-samples", "children"),
374
+ Output("meta-features", "children"),
375
+ Output("meta-updated", "children"),
376
+ Output("desc-dataset-name", "children"),
377
+ Output("stat-updated", "children"),
378
+ Output("stat-count", "children"),
379
+ Output("stat-best", "children"),
380
+ Output("score-graph", "figure"),
381
+ Output("pareto-graph", "figure"),
382
+ Output("custom-table-container", "children"),
383
+ Output("val-f1", "children"),
384
+ Output("val-feats", "children"),
385
+ Output("val-del-rate", "children"),
386
+ Input("dataset-select", "value"),
387
+ Input("view-mode", "value"),
388
+ Input("filter-f1", "value"),
389
+ Input("filter-feats", "value"),
390
+ Input("filter-del-rate", "value"),
391
+ Input("filter-complexity", "value"),
392
+ Input("filter-algos", "value"),
393
+ State("filter-f1", "min"),
394
+ State("filter-f1", "max"),
395
+ State("filter-feats", "max"),
396
+ State("filter-algos", "children"),
397
+ State("filter-algos", "value"),
398
+ )
399
+
400
+ def update_dashboard_all(
401
+ dataset,
402
+ view_mode,
403
+ min_f1_value,
404
+ max_features_value,
405
+ del_range,
406
+ complexity,
407
+ selected_algos,
408
+ f1_min_state,
409
+ f1_max_state,
410
+ feats_max_state,
411
+ algo_children_state,
412
+ algo_value_state,
413
+ ):
414
+ initialize_once()
415
+ triggered_id = callback_context.triggered_id if callback_context.triggered else None
416
+ dataset_changed = triggered_id == "dataset-select" or triggered_id is None
417
+ selected = dataset or "Authorship"
418
+ meta = DATASET_METADATA.get(selected, {"name": selected, "last_updated": "-", "num_samples": None, "total_features": None})
419
+ results = get_results_for_dataset(selected)
420
+ algo_list = sorted({r.get("algorithm") for r in results if r.get("algorithm")})
421
+ if dataset_changed:
422
+ f1_scores = [r.get("mean_f1") for r in results if r.get("mean_f1") is not None]
423
+ if f1_scores:
424
+ min_f1 = min(f1_scores)
425
+ safe_min = max(0, math.floor((min_f1 - 0.1) * 10) / 10)
426
+ else:
427
+ safe_min = 0
428
+ max_feats = meta.get("total_features") or 100
429
+ f1_min = safe_min
430
+ f1_max = 1
431
+ f1_value = safe_min
432
+ feats_max = max_feats
433
+ feats_value = max_feats
434
+ algo_children = [dmc.Checkbox(label=a, value=a) for a in algo_list]
435
+ algo_value = algo_list
436
+ else:
437
+ f1_min = f1_min_state if f1_min_state is not None else 0
438
+ f1_max = f1_max_state if f1_max_state is not None else 1
439
+ f1_value = min_f1_value if min_f1_value is not None else f1_min
440
+ feats_max = feats_max_state if feats_max_state is not None else (meta.get("total_features") or 100)
441
+ feats_value = max_features_value if max_features_value is not None else feats_max
442
+ if algo_children_state:
443
+ algo_children = algo_children_state
444
+ else:
445
+ algo_children = [dmc.Checkbox(label=a, value=a) for a in algo_list]
446
+ if selected_algos is not None:
447
+ algo_value = selected_algos
448
+ else:
449
+ algo_value = algo_value_state if algo_value_state is not None else algo_list
450
+ filtered = apply_filters(results, meta, f1_value or 0, feats_value, del_range, complexity, algo_value or [])
451
+ count = len(filtered)
452
+ if filtered:
453
+ best = max(filtered, key=lambda r: r.get("mean_f1") or 0)
454
+ best_text = f"{best.get('algorithm')} ({(best.get('mean_f1') or 0):.3f})"
455
+ else:
456
+ best_text = "-"
457
+ score_fig = build_score_figure(filtered, view_mode or "overall")
458
+ pareto_fig = build_pareto_figure(filtered)
459
+ table_component = build_table(filtered, view_mode or "overall")
460
+ val_f1 = f"{(f1_value or 0):.4f}"
461
+ val_feats = str(int(feats_value)) if isinstance(feats_value, (int, float)) else "All"
462
+ del_min = del_range[0] if del_range else 0
463
+ del_max = del_range[1] if del_range else 100
464
+ val_del = f"{del_min:.0f}% - {del_max:.0f}%"
465
+ meta_samples = meta.get("num_samples") if meta.get("num_samples") is not None else "Unavailable"
466
+ meta_features = meta.get("total_features") if meta.get("total_features") is not None else "Unavailable"
467
+ return (
468
+ feats_max,
469
+ feats_value,
470
+ f1_min,
471
+ f1_max,
472
+ f1_value,
473
+ algo_children,
474
+ algo_value,
475
+ meta.get("name", "-"),
476
+ meta_samples,
477
+ meta_features,
478
+ meta.get("last_updated", "-"),
479
+ meta.get("name", "-"),
480
+ meta.get("last_updated", "-"),
481
+ count,
482
+ best_text,
483
+ score_fig,
484
+ pareto_fig,
485
+ table_component,
486
+ val_f1,
487
+ val_feats,
488
+ val_del,
489
+ )
490
+
491
+
492
+
493
+ # =====================================================
494
+ # ⭐ 只在真正启动时运行
495
+ # =====================================================
496
+
497
+ if __name__ == "__main__":
498
+ initialize_once()
499
+
500
+ port = int(os.environ.get("PORT", 7865))
501
+
502
+ print(f"Loaded {len(DATASET_METADATA)} datasets from {RESULT_DIR}")
503
+ print(f"Dash is running on http://0.0.0.0:{port}/")
504
+
505
+ app.run(
506
+ host="0.0.0.0",
507
+ port=port,
508
+ debug=False
509
+ )