ananyakarn commited on
Commit
2f51316
·
verified ·
1 Parent(s): 219e937
Files changed (1) hide show
  1. app.py +149 -3
app.py CHANGED
@@ -5,7 +5,6 @@ import torch, numpy as np, random
5
  torch.manual_seed(42)
6
  np.random.seed(42)
7
  random.seed(42)
8
-
9
  # =========================
10
  # 1. SAFE DOWNLOAD FUNCTION (FIXED)
11
  # =========================
@@ -229,6 +228,153 @@ Xa_test = sc_a.transform(Xa_test)
229
  Xv_test = sc_v.transform(Xv_test)
230
 
231
  # =========================
232
- # 11. MODELS + TRAIN + EVAL (UNCHANGED)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
  # =========================
234
- # (keep exactly as your current code)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  torch.manual_seed(42)
6
  np.random.seed(42)
7
  random.seed(42)
 
8
  # =========================
9
  # 1. SAFE DOWNLOAD FUNCTION (FIXED)
10
  # =========================
 
228
  Xv_test = sc_v.transform(Xv_test)
229
 
230
  # =========================
231
+ # 11. MODELS
232
+ # =========================
233
+ import torch.nn as nn
234
+
235
+ class Model(nn.Module):
236
+ def __init__(self, vdim):
237
+ super().__init__()
238
+ self.t = nn.Sequential(nn.Linear(768,128), nn.ReLU())
239
+ self.a = nn.Sequential(nn.Linear(40,32), nn.ReLU())
240
+ self.v = nn.Sequential(nn.Linear(vdim,64), nn.ReLU())
241
+
242
+ self.f = nn.Sequential(
243
+ nn.Linear(224,64),
244
+ nn.ReLU(),
245
+ nn.Dropout(0.3),
246
+ nn.Linear(64,1)
247
+ )
248
+
249
+ def forward(self, t, a, v):
250
+ return self.f(torch.cat([self.t(t), self.a(a), self.v(v)], dim=1))
251
+
252
+
253
+ class AttentionFusionModel(nn.Module):
254
+ def __init__(self, vdim):
255
+ super().__init__()
256
+
257
+ self.t = nn.Sequential(nn.Linear(768,128), nn.ReLU())
258
+ self.a = nn.Sequential(nn.Linear(40,32), nn.ReLU())
259
+ self.v = nn.Sequential(nn.Linear(vdim,64), nn.ReLU())
260
+
261
+ self.attn = nn.Sequential(
262
+ nn.Linear(224,64),
263
+ nn.Tanh(),
264
+ nn.Linear(64,3)
265
+ )
266
+
267
+ self.f = nn.Sequential(
268
+ nn.Linear(224,64),
269
+ nn.ReLU(),
270
+ nn.Dropout(0.3),
271
+ nn.Linear(64,1)
272
+ )
273
+
274
+ def forward(self, t, a, v):
275
+ t_feat = self.t(t)
276
+ a_feat = self.a(a)
277
+ v_feat = self.v(v)
278
+
279
+ combined = torch.cat([t_feat, a_feat, v_feat], dim=1)
280
+
281
+ weights = torch.softmax(self.attn(combined), dim=1)
282
+
283
+ fused = torch.cat([
284
+ weights[:,0:1] * t_feat,
285
+ weights[:,1:2] * a_feat,
286
+ weights[:,2:3] * v_feat
287
+ ], dim=1)
288
+
289
+ return self.f(fused)
290
+
291
+
292
+ # =========================
293
+ # 12. CONVERT TO TENSORS
294
+ # =========================
295
+ Xt = torch.tensor(Xt, dtype=torch.float32).to(device)
296
+ Xa = torch.tensor(Xa, dtype=torch.float32).to(device)
297
+ Xv = torch.tensor(Xv, dtype=torch.float32).to(device)
298
+ yt = torch.tensor(y_train, dtype=torch.float32).to(device)
299
+
300
+ Xt_test = torch.tensor(Xt_test, dtype=torch.float32).to(device)
301
+ Xa_test = torch.tensor(Xa_test, dtype=torch.float32).to(device)
302
+ Xv_test = torch.tensor(Xv_test, dtype=torch.float32).to(device)
303
+
304
+
305
+ # =========================
306
+ # 13. TRAIN BASELINE MODEL
307
+ # =========================
308
+ baseline_model = Model(Xv.shape[1]).to(device)
309
+
310
+ opt1 = torch.optim.Adam(baseline_model.parameters(), lr=1e-4)
311
+ loss_fn = nn.BCEWithLogitsLoss()
312
+
313
+ print("\nTraining Baseline Model...")
314
+
315
+ for e in range(5): # 🔥 reduced epochs (important)
316
+ baseline_model.train()
317
+ opt1.zero_grad()
318
+
319
+ outputs = baseline_model(Xt, Xa, Xv).squeeze()
320
+ loss = loss_fn(outputs, yt)
321
+
322
+ loss.backward()
323
+ opt1.step()
324
+
325
+ print(f"Epoch {e+1}, Loss: {loss.item():.4f}")
326
+
327
+
328
+ # =========================
329
+ # 14. TRAIN ATTENTION MODEL
330
  # =========================
331
+ attention_model = AttentionFusionModel(Xv.shape[1]).to(device)
332
+
333
+ opt2 = torch.optim.AdamW(attention_model.parameters(), lr=1e-4)
334
+ loss_fn_attn = nn.BCEWithLogitsLoss()
335
+
336
+ print("\nTraining Attention Model...")
337
+
338
+ for e in range(5): # 🔥 reduced epochs
339
+ attention_model.train()
340
+ opt2.zero_grad()
341
+
342
+ outputs = attention_model(Xt, Xa, Xv).squeeze()
343
+ loss = loss_fn_attn(outputs, yt)
344
+
345
+ loss.backward()
346
+ opt2.step()
347
+
348
+ print(f"Epoch {e+1}, Loss: {loss.item():.4f}")
349
+
350
+
351
+ # =========================
352
+ # 15. EVALUATION
353
+ # =========================
354
+ from sklearn.metrics import accuracy_score, f1_score
355
+
356
+ baseline_model.eval()
357
+ attention_model.eval()
358
+
359
+ with torch.no_grad():
360
+ pred_baseline = (torch.sigmoid(
361
+ baseline_model(Xt_test, Xa_test, Xv_test).squeeze()
362
+ ) > 0.5).int().cpu().numpy()
363
+
364
+ pred_attention = (torch.sigmoid(
365
+ attention_model(Xt_test, Xa_test, Xv_test).squeeze()
366
+ ) > 0.5).int().cpu().numpy()
367
+
368
+
369
+ # =========================
370
+ # 16. RESULTS
371
+ # =========================
372
+ print("\n===== MODEL COMPARISON =====")
373
+
374
+ print("\nBaseline Model:")
375
+ print("Accuracy:", accuracy_score(y_test, pred_baseline))
376
+ print("F1 Score:", f1_score(y_test, pred_baseline))
377
+
378
+ print("\nAttention Model:")
379
+ print("Accuracy:", accuracy_score(y_test, pred_attention))
380
+ print("F1 Score:", f1_score(y_test, pred_attention))