Arun-AK commited on
Commit
ebbfb24
·
verified ·
1 Parent(s): fb4a3f0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +173 -172
app.py CHANGED
@@ -7,178 +7,6 @@ import seaborn as sns
7
  import io
8
  import gradio as gr
9
  import pickle
10
- # Load fine-tuned results from pickle
11
- finetuned_pickle_path = 'best_params_backup.pkl'
12
-
13
- with open(finetuned_pickle_path, 'rb') as f:
14
- best_params_per_dataset = pickle.load(f)
15
-
16
- # Convert to DataFrame with accuracy only
17
- ft_rows = []
18
- for key, val in best_params_per_dataset.items():
19
- parts = key.split("_", 1)
20
- dataset = parts[0]
21
- model = parts[1] if len(parts) > 1 else "unknown"
22
- ft_rows.append({
23
- "dataset": dataset,
24
- "model": model,
25
- "accuracy": round(val["score"], 4)
26
- })
27
-
28
- finetuned_df = pd.DataFrame(ft_rows)
29
-
30
- # Build fine-tuned pairwise comparisons — all datasets
31
- ft_models = ["Random Forest", "Decision Tree", "SVM", "KNN", "NN"]
32
-
33
- ft_all_results = []
34
- ft_model_list = ft_models.copy()
35
-
36
- for model_a in ft_models:
37
- other = ft_model_list.copy()
38
- other.remove(model_a)
39
- for model_b in other:
40
- data_a = finetuned_df[finetuned_df['model'] == model_a].set_index('dataset')['accuracy']
41
- data_b = finetuned_df[finetuned_df['model'] == model_b].set_index('dataset')['accuracy']
42
- combined = pd.DataFrame({'a': data_a, 'b': data_b}).dropna()
43
- if len(combined) < 2:
44
- continue
45
- t_stat, p_val = ttest_rel(combined['a'], combined['b'])
46
- ft_all_results.append({
47
- 'model_a': model_a,
48
- 'model_b': model_b,
49
- 'mean_a': combined['a'].mean(),
50
- 'mean_b': combined['b'].mean(),
51
- 'std_a': combined['a'].std(),
52
- 'std_b': combined['b'].std(),
53
- 'n_datasets': len(combined),
54
- 't_statistic': t_stat,
55
- 'p_value': p_val
56
- })
57
- ft_model_list = other.copy()
58
-
59
- ft_results_df = pd.DataFrame(ft_all_results)
60
-
61
- # Build per-category fine-tuned comparisons
62
- ft_sig = {}
63
- for cat_key in list(DATASET_CATEGORIES.keys()):
64
- cat_datasets = list(DATASET_CATEGORIES[cat_key].keys())
65
- df_cat = finetuned_df[finetuned_df['dataset'].isin(cat_datasets)]
66
- cat_results = []
67
- ft_model_list = ft_models.copy()
68
- for model_a in ft_models:
69
- other = ft_model_list.copy()
70
- other.remove(model_a)
71
- for model_b in other:
72
- data_a = df_cat[df_cat['model'] == model_a].set_index('dataset')['accuracy']
73
- data_b = df_cat[df_cat['model'] == model_b].set_index('dataset')['accuracy']
74
- combined = pd.DataFrame({'a': data_a, 'b': data_b}).dropna()
75
- if len(combined) < 2:
76
- continue
77
- t_stat, p_val = ttest_rel(combined['a'], combined['b'])
78
- cat_results.append({
79
- 'model_a': model_a,
80
- 'model_b': model_b,
81
- 'mean_a': combined['a'].mean(),
82
- 'mean_b': combined['b'].mean(),
83
- 'std_a': combined['a'].std(),
84
- 'std_b': combined['b'].std(),
85
- 'n_datasets': len(combined),
86
- 't_statistic': t_stat,
87
- 'p_value': p_val
88
- })
89
- ft_model_list = other.copy()
90
- ft_sig[cat_key] = pd.DataFrame(cat_results)
91
-
92
- ft_sig["AllDatasets"] = ft_results_df
93
- def get_keys(d, values):
94
- return [k for k, v in d.items() if v in values]
95
- pickle_file_path = 'model_results1.pkl'
96
-
97
- model_results = pd.read_pickle(pickle_file_path)
98
-
99
- csv_file_path = 'the_model_results.csv'
100
-
101
- model_results_csv = pd.read_csv(csv_file_path)
102
-
103
- fmodel_results = pd.concat([model_results, model_results_csv.rename(columns = {"dataset_name" : "dataset"})], ignore_index=True)
104
-
105
- def ft_compare_groups(data_choice, model1, model2):
106
- data1 = ft_sig[data_choice.split(' (')[0]]
107
- comparison_data = data1[
108
- ((data1['model_a'] == model1) & (data1['model_b'] == model2)) |
109
- ((data1['model_a'] == model2) & (data1['model_b'] == model1))
110
- ]
111
-
112
- if comparison_data.empty:
113
- fig = plt.figure(figsize=(10, 6))
114
- plt.close(fig)
115
- return fig, "No comparison data found. Don't pick the same models."
116
-
117
- plot_data = []
118
- p_values_text = []
119
-
120
- for _, row in comparison_data.iterrows():
121
- if row['model_a'] == model1:
122
- plot_data.append({'Model': model1, 'Mean Accuracy': row['mean_a']})
123
- plot_data.append({'Model': model2, 'Mean Accuracy': row['mean_b']})
124
- else:
125
- plot_data.append({'Model': model1, 'Mean Accuracy': row['mean_b']})
126
- plot_data.append({'Model': model2, 'Mean Accuracy': row['mean_a']})
127
- p_values_text.append(
128
- f"accuracy p-value: {row['p_value']:.5f} "
129
- f"(Significant (cutoff = 0.05): {'Yes' if row['p_value'] < 0.05 else 'No'})"
130
- )
131
-
132
- df_plot = pd.DataFrame(plot_data)
133
-
134
- fig = plt.figure(figsize=(10, 6))
135
- sns.barplot(x='Model', y='Mean Accuracy', data=df_plot)
136
- plt.title(f'Fine-Tuned: {model1} vs {model2} — Accuracy')
137
- plt.ylabel('Mean Accuracy')
138
- plt.xlabel('Model')
139
- plt.ylim(0, 1)
140
- plt.tight_layout()
141
-
142
- return fig, "\n".join(p_values_text)
143
-
144
-
145
- def ft_compare_ind(med, game, ed, bank, sci, social, ml, other, models_to_compare=None):
146
- selected_keys = []
147
- dropdowns = [med, game, ed, bank, sci, social, ml, other]
148
-
149
- for cat_name, dropdown_values in zip(cats1, dropdowns):
150
- if dropdown_values:
151
- selected_keys.extend(get_keys(DATASET_CATEGORIES[cat_name], dropdown_values))
152
-
153
- if not models_to_compare:
154
- models_to_compare = ft_models
155
-
156
- dataset_id_to_name = {
157
- id: name
158
- for category_dict in DATASET_CATEGORIES.values()
159
- for id, name in category_dict.items()
160
- }
161
-
162
- filtered_df = finetuned_df[
163
- (finetuned_df["dataset"].isin(selected_keys)) &
164
- (finetuned_df["model"].isin(models_to_compare))
165
- ].copy()
166
-
167
- heatmap_data = filtered_df.pivot_table(
168
- index='dataset',
169
- columns='model',
170
- values='accuracy'
171
- )
172
- heatmap_data = heatmap_data.rename(index=dataset_id_to_name)
173
-
174
- fig = plt.figure(figsize=(12, 8))
175
- sns.heatmap(heatmap_data, annot=True, cmap="crest", fmt=".3f", cbar=True)
176
- plt.title(f"Fine-Tuned Accuracy per Dataset and Model ({len(selected_keys)} datasets)")
177
- plt.ylabel("Dataset")
178
- plt.xlabel("Model")
179
- plt.tight_layout()
180
-
181
- return fig, "Comparison complete."
182
  DATASET_CATEGORIES = {
183
  "Medical & Healthcare": {
184
  "D1": "Heart Disease (Comprehensive)",
@@ -401,6 +229,179 @@ DATASET_CATEGORIES = {
401
  }
402
  }
403
  cats1 = list(DATASET_CATEGORIES.keys())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
404
  import pandas as pd
405
  from scipy.stats import ttest_rel
406
 
 
7
  import io
8
  import gradio as gr
9
  import pickle
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  DATASET_CATEGORIES = {
11
  "Medical & Healthcare": {
12
  "D1": "Heart Disease (Comprehensive)",
 
229
  }
230
  }
231
  cats1 = list(DATASET_CATEGORIES.keys())
232
+ # Load fine-tuned results from pickle
233
+ finetuned_pickle_path = 'best_params_backup.pkl'
234
+
235
+ with open(finetuned_pickle_path, 'rb') as f:
236
+ best_params_per_dataset = pickle.load(f)
237
+
238
+ # Convert to DataFrame with accuracy only
239
+ ft_rows = []
240
+ for key, val in best_params_per_dataset.items():
241
+ parts = key.split("_", 1)
242
+ dataset = parts[0]
243
+ model = parts[1] if len(parts) > 1 else "unknown"
244
+ ft_rows.append({
245
+ "dataset": dataset,
246
+ "model": model,
247
+ "accuracy": round(val["score"], 4)
248
+ })
249
+
250
+ finetuned_df = pd.DataFrame(ft_rows)
251
+
252
+ # Build fine-tuned pairwise comparisons — all datasets
253
+ ft_models = ["Random Forest", "Decision Tree", "SVM", "KNN", "NN"]
254
+
255
+ ft_all_results = []
256
+ ft_model_list = ft_models.copy()
257
+
258
+ for model_a in ft_models:
259
+ other = ft_model_list.copy()
260
+ other.remove(model_a)
261
+ for model_b in other:
262
+ data_a = finetuned_df[finetuned_df['model'] == model_a].set_index('dataset')['accuracy']
263
+ data_b = finetuned_df[finetuned_df['model'] == model_b].set_index('dataset')['accuracy']
264
+ combined = pd.DataFrame({'a': data_a, 'b': data_b}).dropna()
265
+ if len(combined) < 2:
266
+ continue
267
+ t_stat, p_val = ttest_rel(combined['a'], combined['b'])
268
+ ft_all_results.append({
269
+ 'model_a': model_a,
270
+ 'model_b': model_b,
271
+ 'mean_a': combined['a'].mean(),
272
+ 'mean_b': combined['b'].mean(),
273
+ 'std_a': combined['a'].std(),
274
+ 'std_b': combined['b'].std(),
275
+ 'n_datasets': len(combined),
276
+ 't_statistic': t_stat,
277
+ 'p_value': p_val
278
+ })
279
+ ft_model_list = other.copy()
280
+
281
+ ft_results_df = pd.DataFrame(ft_all_results)
282
+
283
+ # Build per-category fine-tuned comparisons
284
+ ft_sig = {}
285
+ for cat_key in list(DATASET_CATEGORIES.keys()):
286
+ cat_datasets = list(DATASET_CATEGORIES[cat_key].keys())
287
+ df_cat = finetuned_df[finetuned_df['dataset'].isin(cat_datasets)]
288
+ cat_results = []
289
+ ft_model_list = ft_models.copy()
290
+ for model_a in ft_models:
291
+ other = ft_model_list.copy()
292
+ other.remove(model_a)
293
+ for model_b in other:
294
+ data_a = df_cat[df_cat['model'] == model_a].set_index('dataset')['accuracy']
295
+ data_b = df_cat[df_cat['model'] == model_b].set_index('dataset')['accuracy']
296
+ combined = pd.DataFrame({'a': data_a, 'b': data_b}).dropna()
297
+ if len(combined) < 2:
298
+ continue
299
+ t_stat, p_val = ttest_rel(combined['a'], combined['b'])
300
+ cat_results.append({
301
+ 'model_a': model_a,
302
+ 'model_b': model_b,
303
+ 'mean_a': combined['a'].mean(),
304
+ 'mean_b': combined['b'].mean(),
305
+ 'std_a': combined['a'].std(),
306
+ 'std_b': combined['b'].std(),
307
+ 'n_datasets': len(combined),
308
+ 't_statistic': t_stat,
309
+ 'p_value': p_val
310
+ })
311
+ ft_model_list = other.copy()
312
+ ft_sig[cat_key] = pd.DataFrame(cat_results)
313
+
314
+ ft_sig["AllDatasets"] = ft_results_df
315
+ def get_keys(d, values):
316
+ return [k for k, v in d.items() if v in values]
317
+ pickle_file_path = 'model_results1.pkl'
318
+
319
+ model_results = pd.read_pickle(pickle_file_path)
320
+
321
+ csv_file_path = 'the_model_results.csv'
322
+
323
+ model_results_csv = pd.read_csv(csv_file_path)
324
+
325
+ fmodel_results = pd.concat([model_results, model_results_csv.rename(columns = {"dataset_name" : "dataset"})], ignore_index=True)
326
+
327
+ def ft_compare_groups(data_choice, model1, model2):
328
+ data1 = ft_sig[data_choice.split(' (')[0]]
329
+ comparison_data = data1[
330
+ ((data1['model_a'] == model1) & (data1['model_b'] == model2)) |
331
+ ((data1['model_a'] == model2) & (data1['model_b'] == model1))
332
+ ]
333
+
334
+ if comparison_data.empty:
335
+ fig = plt.figure(figsize=(10, 6))
336
+ plt.close(fig)
337
+ return fig, "No comparison data found. Don't pick the same models."
338
+
339
+ plot_data = []
340
+ p_values_text = []
341
+
342
+ for _, row in comparison_data.iterrows():
343
+ if row['model_a'] == model1:
344
+ plot_data.append({'Model': model1, 'Mean Accuracy': row['mean_a']})
345
+ plot_data.append({'Model': model2, 'Mean Accuracy': row['mean_b']})
346
+ else:
347
+ plot_data.append({'Model': model1, 'Mean Accuracy': row['mean_b']})
348
+ plot_data.append({'Model': model2, 'Mean Accuracy': row['mean_a']})
349
+ p_values_text.append(
350
+ f"accuracy p-value: {row['p_value']:.5f} "
351
+ f"(Significant (cutoff = 0.05): {'Yes' if row['p_value'] < 0.05 else 'No'})"
352
+ )
353
+
354
+ df_plot = pd.DataFrame(plot_data)
355
+
356
+ fig = plt.figure(figsize=(10, 6))
357
+ sns.barplot(x='Model', y='Mean Accuracy', data=df_plot)
358
+ plt.title(f'Fine-Tuned: {model1} vs {model2} — Accuracy')
359
+ plt.ylabel('Mean Accuracy')
360
+ plt.xlabel('Model')
361
+ plt.ylim(0, 1)
362
+ plt.tight_layout()
363
+
364
+ return fig, "\n".join(p_values_text)
365
+
366
+
367
+ def ft_compare_ind(med, game, ed, bank, sci, social, ml, other, models_to_compare=None):
368
+ selected_keys = []
369
+ dropdowns = [med, game, ed, bank, sci, social, ml, other]
370
+
371
+ for cat_name, dropdown_values in zip(cats1, dropdowns):
372
+ if dropdown_values:
373
+ selected_keys.extend(get_keys(DATASET_CATEGORIES[cat_name], dropdown_values))
374
+
375
+ if not models_to_compare:
376
+ models_to_compare = ft_models
377
+
378
+ dataset_id_to_name = {
379
+ id: name
380
+ for category_dict in DATASET_CATEGORIES.values()
381
+ for id, name in category_dict.items()
382
+ }
383
+
384
+ filtered_df = finetuned_df[
385
+ (finetuned_df["dataset"].isin(selected_keys)) &
386
+ (finetuned_df["model"].isin(models_to_compare))
387
+ ].copy()
388
+
389
+ heatmap_data = filtered_df.pivot_table(
390
+ index='dataset',
391
+ columns='model',
392
+ values='accuracy'
393
+ )
394
+ heatmap_data = heatmap_data.rename(index=dataset_id_to_name)
395
+
396
+ fig = plt.figure(figsize=(12, 8))
397
+ sns.heatmap(heatmap_data, annot=True, cmap="crest", fmt=".3f", cbar=True)
398
+ plt.title(f"Fine-Tuned Accuracy per Dataset and Model ({len(selected_keys)} datasets)")
399
+ plt.ylabel("Dataset")
400
+ plt.xlabel("Model")
401
+ plt.tight_layout()
402
+
403
+ return fig, "Comparison complete."
404
+
405
  import pandas as pd
406
  from scipy.stats import ttest_rel
407