ananyakarn commited on
Commit
54eb800
·
verified ·
1 Parent(s): f04fed2

trying with balanced dataset

Browse files
Files changed (1) hide show
  1. app.py +51 -35
app.py CHANGED
@@ -11,6 +11,7 @@ from transformers import AutoTokenizer, AutoModel
11
  from sklearn.ensemble import RandomForestClassifier
12
  from sklearn.preprocessing import StandardScaler
13
  from sklearn.metrics import accuracy_score, f1_score
 
14
 
15
  # =========================
16
  # 1. DOWNLOAD DATASET
@@ -31,12 +32,12 @@ if not os.path.exists(extract_path):
31
  zip_ref.extractall(extract_path)
32
 
33
  # =========================
34
- # 2. LOAD BERT MODEL
35
  # =========================
36
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
37
 
38
- tokenizer = AutoTokenizer.from_pretrained("bert-base-multilingual-cased")
39
- bert = AutoModel.from_pretrained("bert-base-multilingual-cased").to(device)
40
  bert.eval()
41
 
42
  # =========================
@@ -69,14 +70,29 @@ def get_label(folder):
69
  return 1 if "_P" in folder else 0
70
 
71
  # =========================
72
- # 4. TRAIN MODEL (LIGHT)
73
  # =========================
74
- print("Training model...")
75
 
76
- X, y = [], []
 
 
 
 
 
 
77
 
78
- folders = [f for f in os.listdir(extract_path) if os.path.isdir(os.path.join(extract_path, f))]
79
- folders = folders[:20] # 🔥 small subset for speed
 
 
 
 
 
 
 
 
 
80
 
81
  for folder in folders:
82
  path = os.path.join(extract_path, folder)
@@ -93,43 +109,43 @@ for folder in folders:
93
  X = np.array(X)
94
  y = np.array(y)
95
 
 
 
 
 
 
 
 
96
  scaler = StandardScaler()
97
- X = scaler.fit_transform(X)
 
 
 
 
 
 
98
 
99
  model = RandomForestClassifier(n_estimators=50, random_state=42)
100
- model.fit(X, y)
101
 
102
  print("Model ready!")
103
 
104
  # =========================
105
- # 5. RUN PREDICTIONS
106
  # =========================
107
  def run_on_dataset():
108
 
109
- results = []
110
- preds = []
111
- labels = []
112
-
113
- for i, folder in enumerate(folders):
114
- path = os.path.join(extract_path, folder)
115
-
116
- text = load_text(path)
117
- text_feat = get_text_embedding(text)
118
- audio_feat = get_audio_features(path)
119
-
120
- x = np.concatenate([text_feat, audio_feat])
121
- x = scaler.transform([x])
122
 
123
- pred = model.predict(x)[0]
124
- label = get_label(folder)
125
 
126
- preds.append(pred)
127
- labels.append(label)
128
-
129
- results.append(f"{folder} → {'Depressed' if pred==1 else 'Control'}")
130
-
131
- acc = accuracy_score(labels, preds)
132
- f1 = f1_score(labels, preds)
133
 
134
  output = "\n".join(results)
135
  output += f"\n\nAccuracy: {acc:.3f}"
@@ -138,14 +154,14 @@ def run_on_dataset():
138
  return output
139
 
140
  # =========================
141
- # 6. GRADIO UI
142
  # =========================
143
  app = gr.Interface(
144
  fn=run_on_dataset,
145
  inputs=[],
146
  outputs="text",
147
  title="Multimodal Depression Detection",
148
- description="Automatically trains on dataset and evaluates predictions (text + audio)"
149
  )
150
 
151
  app.launch()
 
11
  from sklearn.ensemble import RandomForestClassifier
12
  from sklearn.preprocessing import StandardScaler
13
  from sklearn.metrics import accuracy_score, f1_score
14
+ from sklearn.model_selection import train_test_split
15
 
16
  # =========================
17
  # 1. DOWNLOAD DATASET
 
32
  zip_ref.extractall(extract_path)
33
 
34
  # =========================
35
+ # 2. LOAD LIGHTWEIGHT BERT
36
  # =========================
37
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
38
 
39
+ tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
40
+ bert = AutoModel.from_pretrained("distilbert-base-uncased").to(device)
41
  bert.eval()
42
 
43
  # =========================
 
70
  return 1 if "_P" in folder else 0
71
 
72
  # =========================
73
+ # 4. BUILD BALANCED DATASET
74
  # =========================
75
+ print("Building balanced dataset...")
76
 
77
+ all_folders = [f for f in os.listdir(extract_path) if os.path.isdir(os.path.join(extract_path, f))]
78
+
79
+ p_folders = [f for f in all_folders if "_P" in f]
80
+ c_folders = [f for f in all_folders if "_C" in f]
81
+
82
+ # 🔥 pick equal samples
83
+ num_samples = min(10, len(p_folders), len(c_folders))
84
 
85
+ p_folders = p_folders[:num_samples]
86
+ c_folders = c_folders[:num_samples]
87
+
88
+ folders = p_folders + c_folders
89
+
90
+ print(f"Using {len(p_folders)} depressed and {len(c_folders)} control samples")
91
+
92
+ # =========================
93
+ # 5. FEATURE EXTRACTION
94
+ # =========================
95
+ X, y = [], []
96
 
97
  for folder in folders:
98
  path = os.path.join(extract_path, folder)
 
109
  X = np.array(X)
110
  y = np.array(y)
111
 
112
+ # =========================
113
+ # 6. TRAIN-TEST SPLIT
114
+ # =========================
115
+ X_train, X_test, y_train, y_test = train_test_split(
116
+ X, y, test_size=0.3, random_state=42, stratify=y
117
+ )
118
+
119
  scaler = StandardScaler()
120
+ X_train = scaler.fit_transform(X_train)
121
+ X_test = scaler.transform(X_test)
122
+
123
+ # =========================
124
+ # 7. TRAIN MODEL
125
+ # =========================
126
+ print("Training model...")
127
 
128
  model = RandomForestClassifier(n_estimators=50, random_state=42)
129
+ model.fit(X_train, y_train)
130
 
131
  print("Model ready!")
132
 
133
  # =========================
134
+ # 8. RUN EVALUATION
135
  # =========================
136
  def run_on_dataset():
137
 
138
+ preds = model.predict(X_test)
 
 
 
 
 
 
 
 
 
 
 
 
139
 
140
+ acc = accuracy_score(y_test, preds)
141
+ f1 = f1_score(y_test, preds)
142
 
143
+ results = []
144
+ for i, pred in enumerate(preds):
145
+ label = y_test[i]
146
+ results.append(
147
+ f"Sample {i+1} → Pred: {'Depressed' if pred else 'Control'} | True: {'Depressed' if label else 'Control'}"
148
+ )
 
149
 
150
  output = "\n".join(results)
151
  output += f"\n\nAccuracy: {acc:.3f}"
 
154
  return output
155
 
156
  # =========================
157
+ # 9. GRADIO UI
158
  # =========================
159
  app = gr.Interface(
160
  fn=run_on_dataset,
161
  inputs=[],
162
  outputs="text",
163
  title="Multimodal Depression Detection",
164
+ description="Balanced dataset training + evaluation (text + audio)"
165
  )
166
 
167
  app.launch()