Exqrch commited on
Commit
2d0dd9b
·
verified ·
1 Parent(s): c628b6a

Upload IndoDiscourse - Toxicity Related Experiment Code.ipynb

Browse files
IndoDiscourse - Toxicity Related Experiment Code.ipynb ADDED
@@ -0,0 +1,1475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "bb8a383e-7d0c-454d-8764-4e3d975b2187",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Experiment List:\n",
9
+ "1. Baseline Performance of Neural Models\n",
10
+ "2. Wisdom of The Crowd Experiment\n",
11
+ "3. Using \"Polarization\" as a Feature for Toxicity Detection\n",
12
+ "4. Incorporating Demographic Information\n",
13
+ "5. Combining Polarization and Demographic Information for Toxicity Detection"
14
+ ]
15
+ },
16
+ {
17
+ "cell_type": "markdown",
18
+ "id": "df99292a-e96d-4d56-b16f-c8fa1a2fd2ea",
19
+ "metadata": {},
20
+ "source": [
21
+ "## 1. Baseline Performance of Neural Models"
22
+ ]
23
+ },
24
+ {
25
+ "cell_type": "markdown",
26
+ "id": "8a1ca696-e05c-4c37-a8c9-d99095e4c2d8",
27
+ "metadata": {},
28
+ "source": [
29
+ "### For IndoBERTweet and NusaBERT"
30
+ ]
31
+ },
32
+ {
33
+ "cell_type": "code",
34
+ "execution_count": null,
35
+ "id": "8e7edb12-8ae7-4c6a-9201-3a2a76890222",
36
+ "metadata": {},
37
+ "outputs": [],
38
+ "source": [
39
+ "import pandas as pd\n",
40
+ "import ast\n",
41
+ "import os\n",
42
+ "import numpy as np\n",
43
+ "from sklearn.model_selection import StratifiedKFold\n",
44
+ "from transformers import Trainer, TrainingArguments, BertForSequenceClassification, BertTokenizer\n",
45
+ "import torch\n",
46
+ "\n",
47
+ "from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, roc_auc_score, average_precision_score\n",
48
+ "\n",
49
+ "def compute_metrics(pred):\n",
50
+ " labels = pred.label_ids\n",
51
+ " preds = pred.predictions.argmax(-1)\n",
52
+ "\n",
53
+ " # Accuracy\n",
54
+ " accuracy = accuracy_score(labels, preds)\n",
55
+ "\n",
56
+ " # Macro F1, Precision, and Recall\n",
57
+ " macro_f1 = f1_score(labels, preds, average='macro')\n",
58
+ " precision = precision_score(labels, preds, average='macro')\n",
59
+ " recall = recall_score(labels, preds, average='macro')\n",
60
+ "\n",
61
+ " # Class-1 only metrics (positive class)\n",
62
+ " precision_class_1 = precision_score(labels, preds, pos_label=1)\n",
63
+ " recall_class_1 = recall_score(labels, preds, pos_label=1)\n",
64
+ " f1_class_1 = f1_score(labels, preds, pos_label=1)\n",
65
+ "\n",
66
+ " # Class-0 only metrics (negative class)\n",
67
+ " precision_class_0 = precision_score(labels, preds, pos_label=0)\n",
68
+ " recall_class_0 = recall_score(labels, preds, pos_label=0)\n",
69
+ " f1_class_0 = f1_score(labels, preds, pos_label=0)\n",
70
+ "\n",
71
+ " # ROC-AUC score for binary classification\n",
72
+ " try:\n",
73
+ " # Compute the ROC AUC score for binary classification directly\n",
74
+ " roc_auc = roc_auc_score(labels, preds)\n",
75
+ " except ValueError:\n",
76
+ " # In case there's an issue with the labels or predictions (e.g., all labels are the same)\n",
77
+ " roc_auc = 0.5 # This would represent random classification if AUC can't be computed\n",
78
+ "\n",
79
+ " # Precision-Recall AUC\n",
80
+ " precision_recall_auc = average_precision_score(labels, preds)\n",
81
+ "\n",
82
+ " return {\n",
83
+ " 'accuracy': accuracy,\n",
84
+ " 'macro_f1': macro_f1,\n",
85
+ " 'precision': precision,\n",
86
+ " 'recall': recall,\n",
87
+ " 'precision_class_1': precision_class_1,\n",
88
+ " 'recall_class_1': recall_class_1,\n",
89
+ " 'f1_class_1': f1_class_1,\n",
90
+ " 'precision_class_0': precision_class_0,\n",
91
+ " 'recall_class_0': recall_class_0,\n",
92
+ " 'f1_class_0': f1_class_0,\n",
93
+ " 'roc_auc': roc_auc,\n",
94
+ " 'precision_recall_auc': precision_recall_auc,\n",
95
+ " }\n",
96
+ "\n",
97
+ "def wisdom_text_handler(merged_df):\n",
98
+ " texts = merged_df['text'].tolist()\n",
99
+ " labels = merged_df['label'].tolist()\n",
100
+ " annot_counts = merged_df['annotator_count'].astype(int).tolist()\n",
101
+ " return texts, labels, annot_counts\n",
102
+ "\n",
103
+ "def wisdom_any_text_handler(merged_df):\n",
104
+ " texts = merged_df['text'].tolist()\n",
105
+ " merged_df['polarized'] = merged_df['polarized'].apply(lambda x: [int(y) for y in ast.literal_eval(x)])\n",
106
+ " merged_df['polarized_value'] = merged_df['polarized'].apply(lambda x: sum(x)/len(x))\n",
107
+ " merged_df['any_label'] = merged_df['polarized_value'].apply(lambda x: 1 if x > 0 else 0) \n",
108
+ " any_label = merged_df['any_label'].tolist()\n",
109
+ " labels = merged_df['label'].tolist()\n",
110
+ " annot_counts = merged_df['annotator_count'].astype(int).tolist()\n",
111
+ " return texts, labels, annot_counts, any_label\n",
112
+ "\n",
113
+ "def train_wisdom_bert_pipeline(model_path: str, merged_df, output_dir: str, approach: str = \"single\"):\n",
114
+ "\n",
115
+ " # Handle texts and labels:\n",
116
+ " texts, labels, annot_counts = wisdom_text_handler(merged_df)\n",
117
+ "\n",
118
+ " # Create output directory\n",
119
+ " os.makedirs(output_dir, exist_ok=True)\n",
120
+ "\n",
121
+ " skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
122
+ " metrics_list = []\n",
123
+ "\n",
124
+ " for fold, (train_index, test_index) in enumerate(skf.split(texts, labels)):\n",
125
+ " train_annot_counts = np.array(annot_counts)[train_index]\n",
126
+ " train_texts, test_texts = np.array(texts)[train_index], np.array(texts)[test_index]\n",
127
+ " train_labels, test_labels = np.array(labels)[train_index], np.array(labels)[test_index]\n",
128
+ " target_annot_count = 1\n",
129
+ " if approach == \"single\":\n",
130
+ " train_indices = np.where(train_annot_counts == target_annot_count)[0]\n",
131
+ " train_texts = np.array(train_texts)[train_indices]\n",
132
+ " train_labels = np.array(train_labels)[train_indices]\n",
133
+ " elif approach == \"more\":\n",
134
+ " train_indices = np.where(train_annot_counts != target_annot_count)[0]\n",
135
+ " train_texts = np.array(train_texts)[train_indices]\n",
136
+ " train_labels = np.array(train_labels)[train_indices]\n",
137
+ " else:\n",
138
+ " raise ValueError(f\"Invalid approach: {approach}\")\n",
139
+ " # Tokenize\n",
140
+ " tokenizer = BertTokenizer.from_pretrained(model_path)\n",
141
+ " train_encodings = tokenizer(train_texts.tolist(), truncation=True, padding=True, max_length=512, return_tensors='pt')\n",
142
+ " test_encodings = tokenizer(test_texts.tolist(), truncation=True, padding=True, max_length=512, return_tensors='pt')\n",
143
+ "\n",
144
+ " train_dataset = Dataset(train_encodings, train_labels)\n",
145
+ " test_dataset = Dataset(test_encodings, test_labels)\n",
146
+ "\n",
147
+ " model = BertForSequenceClassification.from_pretrained(model_path, num_labels=len(set(labels)))\n",
148
+ "\n",
149
+ " training_args = TrainingArguments(\n",
150
+ " output_dir=os.path.join(output_dir, f\"model_fold_{fold}\"),\n",
151
+ " evaluation_strategy=\"epoch\",\n",
152
+ " per_device_train_batch_size=16,\n",
153
+ " per_device_eval_batch_size=64,\n",
154
+ " num_train_epochs=3,\n",
155
+ " logging_dir=os.path.join(output_dir, f\"logs_fold_{fold}\"),\n",
156
+ " )\n",
157
+ "\n",
158
+ " trainer = Trainer(\n",
159
+ " model=model,\n",
160
+ " args=training_args,\n",
161
+ " train_dataset=train_dataset,\n",
162
+ " eval_dataset=test_dataset,\n",
163
+ " compute_metrics=compute_metrics,\n",
164
+ " )\n",
165
+ "\n",
166
+ " # Train and evaluate\n",
167
+ " trainer.train()\n",
168
+ " metrics = trainer.evaluate()\n",
169
+ " metrics_list.append(metrics)\n",
170
+ "\n",
171
+ " # Save model\n",
172
+ " model.save_pretrained(os.path.join(output_dir, f\"model_fold_{fold}\"))\n",
173
+ " tokenizer.save_pretrained(os.path.join(output_dir, f\"model_fold_{fold}\"))\n",
174
+ "\n",
175
+ " # Save performance report\n",
176
+ " pd.DataFrame([metrics]).to_csv(os.path.join(output_dir, f\"performance_fold_{fold}.csv\"), index=False)\n",
177
+ "\n",
178
+ " # Calculate average performance metrics\n",
179
+ " avg_metrics = {metric: np.mean([m[metric] for m in metrics_list]) for metric in metrics_list[0]}\n",
180
+ " pd.DataFrame([avg_metrics]).to_csv(os.path.join(output_dir, \"average_performance.csv\"), index=False)\n",
181
+ "\n",
182
+ "# Dataset class to handle encoding\n",
183
+ "class Dataset(torch.utils.data.Dataset):\n",
184
+ " def __init__(self, encodings, labels):\n",
185
+ " self.encodings = encodings\n",
186
+ " self.labels = [int(label) for label in labels] \n",
187
+ "\n",
188
+ " def __getitem__(self, idx):\n",
189
+ " item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}\n",
190
+ " item['labels'] = torch.tensor(self.labels[idx])\n",
191
+ " return item\n",
192
+ "\n",
193
+ " def __len__(self):\n",
194
+ " return len(self.labels)"
195
+ ]
196
+ },
197
+ {
198
+ "cell_type": "markdown",
199
+ "id": "511649ab-4c9f-4513-a61a-da480bec3f07",
200
+ "metadata": {},
201
+ "source": [
202
+ "### For Multi-e5"
203
+ ]
204
+ },
205
+ {
206
+ "cell_type": "code",
207
+ "execution_count": null,
208
+ "id": "3a224add-ffe1-4f29-843b-92bea15aa07e",
209
+ "metadata": {},
210
+ "outputs": [],
211
+ "source": [
212
+ "import pandas as pd\n",
213
+ "import ast\n",
214
+ "import os\n",
215
+ "import numpy as np\n",
216
+ "import torch\n",
217
+ "from sklearn.model_selection import StratifiedKFold\n",
218
+ "from transformers import Trainer, TrainingArguments, XLMRobertaForSequenceClassification, XLMRobertaTokenizer\n",
219
+ "\n",
220
+ "def baseline_text_handler(merged_df):\n",
221
+ " texts = merged_df['text'].tolist()\n",
222
+ " labels = merged_df['label'].tolist()\n",
223
+ " return texts, labels\n",
224
+ "\n",
225
+ "def train_baseline_XLMRoberta_pipeline(model_path: str, merged_df, output_dir: str):\n",
226
+ "\n",
227
+ " # Handle texts and labels:\n",
228
+ " texts, labels = baseline_text_handler(merged_df)\n",
229
+ "\n",
230
+ " # Create output directory\n",
231
+ " os.makedirs(output_dir, exist_ok=True)\n",
232
+ "\n",
233
+ " skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
234
+ " metrics_list = []\n",
235
+ "\n",
236
+ " for fold, (train_index, test_index) in enumerate(skf.split(texts, labels)):\n",
237
+ " train_texts, test_texts = np.array(texts)[train_index], np.array(texts)[test_index]\n",
238
+ " train_labels, test_labels = np.array(labels)[train_index], np.array(labels)[test_index]\n",
239
+ "\n",
240
+ " # Tokenize\n",
241
+ " tokenizer = XLMRobertaTokenizer.from_pretrained(model_path)\n",
242
+ " train_encodings = tokenizer(train_texts.tolist(), truncation=True, padding=True, max_length=512, return_tensors='pt')\n",
243
+ " test_encodings = tokenizer(test_texts.tolist(), truncation=True, padding=True, max_length=512, return_tensors='pt')\n",
244
+ "\n",
245
+ " train_dataset = Dataset(train_encodings, train_labels)\n",
246
+ " test_dataset = Dataset(test_encodings, test_labels)\n",
247
+ "\n",
248
+ " model = XLMRobertaForSequenceClassification.from_pretrained(model_path, num_labels=len(set(labels)))\n",
249
+ "\n",
250
+ " training_args = TrainingArguments(\n",
251
+ " output_dir=os.path.join(output_dir, f\"model_fold_{fold}\"),\n",
252
+ " evaluation_strategy=\"epoch\",\n",
253
+ " per_device_train_batch_size=16,\n",
254
+ " per_device_eval_batch_size=64,\n",
255
+ " num_train_epochs=3,\n",
256
+ " logging_dir=os.path.join(output_dir, f\"logs_fold_{fold}\"),\n",
257
+ " )\n",
258
+ "\n",
259
+ " trainer = Trainer(\n",
260
+ " model=model,\n",
261
+ " args=training_args,\n",
262
+ " train_dataset=train_dataset,\n",
263
+ " eval_dataset=test_dataset,\n",
264
+ " compute_metrics=compute_metrics,\n",
265
+ " )\n",
266
+ "\n",
267
+ " # Train and evaluate\n",
268
+ " trainer.train()\n",
269
+ " metrics = trainer.evaluate()\n",
270
+ " metrics_list.append(metrics)\n",
271
+ "\n",
272
+ " # Save model\n",
273
+ " model.save_pretrained(os.path.join(output_dir, f\"model_fold_{fold}\"))\n",
274
+ " tokenizer.save_pretrained(os.path.join(output_dir, f\"model_fold_{fold}\"))\n",
275
+ "\n",
276
+ " # Save performance report\n",
277
+ " pd.DataFrame([metrics]).to_csv(os.path.join(output_dir, f\"performance_fold_{fold}.csv\"), index=False)\n",
278
+ "\n",
279
+ " # Final training on the whole dataset\n",
280
+ " tokenizer = XLMRobertaTokenizer.from_pretrained(model_path)\n",
281
+ " encodings = tokenizer(texts, truncation=True, padding=True, max_length=512, return_tensors='pt')\n",
282
+ " dataset = Dataset(encodings, labels)\n",
283
+ "\n",
284
+ " model = XLMRobertaForSequenceClassification.from_pretrained(model_path, num_labels=len(set(labels)))\n",
285
+ "\n",
286
+ " training_args = TrainingArguments(\n",
287
+ " output_dir=os.path.join(output_dir, \"final_model\"),\n",
288
+ " num_train_epochs=3,\n",
289
+ " per_device_train_batch_size=16,\n",
290
+ " )\n",
291
+ "\n",
292
+ " trainer = Trainer(\n",
293
+ " model=model,\n",
294
+ " args=training_args,\n",
295
+ " train_dataset=dataset,\n",
296
+ " )\n",
297
+ "\n",
298
+ " trainer.train()\n",
299
+ " model.save_pretrained(os.path.join(output_dir, \"final_model\"))\n",
300
+ " tokenizer.save_pretrained(os.path.join(output_dir, \"final_model\"))\n",
301
+ "\n",
302
+ " # Calculate average performance metrics\n",
303
+ " avg_metrics = {metric: np.mean([m[metric] for m in metrics_list]) for metric in metrics_list[0]}\n",
304
+ " pd.DataFrame([avg_metrics]).to_csv(os.path.join(output_dir, \"average_performance.csv\"), index=False)"
305
+ ]
306
+ },
307
+ {
308
+ "cell_type": "markdown",
309
+ "id": "ee0f0020-b398-49bd-8b6e-2760a9c69add",
310
+ "metadata": {},
311
+ "source": [
312
+ "## 2. Wisdom of The Crowd Experiment\n",
313
+ "This experiment consists of two main functions: `train_wisdom_bert_pipeline` and `train_wisdom_bert_normalized_sampling_pipeline`.\n",
314
+ "1. train_wisdom_bert_pipeline does not maintain label distribution across experiments (i.e., the Single subset has a different ratio of toxic to non-toxic texts compared to the More subset).\n",
315
+ "2. train_wisdom_bert_normalized_sampling_pipeline applies upsampling to ensure that the Single subset has a distribution of toxic to non-toxic texts that is nearly identical to the More subset."
316
+ ]
317
+ },
318
+ {
319
+ "cell_type": "code",
320
+ "execution_count": null,
321
+ "id": "b6b41af5-5352-4445-9e11-0489e8f2db93",
322
+ "metadata": {},
323
+ "outputs": [],
324
+ "source": [
325
+ "import pandas as pd\n",
326
+ "import ast\n",
327
+ "import os\n",
328
+ "import numpy as np\n",
329
+ "from sklearn.model_selection import StratifiedKFold\n",
330
+ "from transformers import Trainer, TrainingArguments, BertForSequenceClassification, BertTokenizer\n",
331
+ "import torch\n",
332
+ "\n",
333
+ "from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, roc_auc_score, average_precision_score\n",
334
+ "\n",
335
+ "def compute_metrics(pred):\n",
336
+ " labels = pred.label_ids\n",
337
+ " preds = pred.predictions.argmax(-1)\n",
338
+ "\n",
339
+ " # Accuracy\n",
340
+ " accuracy = accuracy_score(labels, preds)\n",
341
+ "\n",
342
+ " # Macro F1, Precision, and Recall\n",
343
+ " macro_f1 = f1_score(labels, preds, average='macro')\n",
344
+ " precision = precision_score(labels, preds, average='macro')\n",
345
+ " recall = recall_score(labels, preds, average='macro')\n",
346
+ "\n",
347
+ " # Class-1 only metrics (positive class)\n",
348
+ " precision_class_1 = precision_score(labels, preds, pos_label=1)\n",
349
+ " recall_class_1 = recall_score(labels, preds, pos_label=1)\n",
350
+ " f1_class_1 = f1_score(labels, preds, pos_label=1)\n",
351
+ "\n",
352
+ " # Class-0 only metrics (negative class)\n",
353
+ " precision_class_0 = precision_score(labels, preds, pos_label=0)\n",
354
+ " recall_class_0 = recall_score(labels, preds, pos_label=0)\n",
355
+ " f1_class_0 = f1_score(labels, preds, pos_label=0)\n",
356
+ "\n",
357
+ " # ROC-AUC score for binary classification\n",
358
+ " try:\n",
359
+ " # Compute the ROC AUC score for binary classification directly\n",
360
+ " roc_auc = roc_auc_score(labels, preds)\n",
361
+ " except ValueError:\n",
362
+ " # In case there's an issue with the labels or predictions (e.g., all labels are the same)\n",
363
+ " roc_auc = 0.5 # This would represent random classification if AUC can't be computed\n",
364
+ "\n",
365
+ " # Precision-Recall AUC\n",
366
+ " precision_recall_auc = average_precision_score(labels, preds)\n",
367
+ "\n",
368
+ " return {\n",
369
+ " 'accuracy': accuracy,\n",
370
+ " 'macro_f1': macro_f1,\n",
371
+ " 'precision': precision,\n",
372
+ " 'recall': recall,\n",
373
+ " 'precision_class_1': precision_class_1,\n",
374
+ " 'recall_class_1': recall_class_1,\n",
375
+ " 'f1_class_1': f1_class_1,\n",
376
+ " 'precision_class_0': precision_class_0,\n",
377
+ " 'recall_class_0': recall_class_0,\n",
378
+ " 'f1_class_0': f1_class_0,\n",
379
+ " 'roc_auc': roc_auc,\n",
380
+ " 'precision_recall_auc': precision_recall_auc,\n",
381
+ " }\n",
382
+ "\n",
383
+ "def wisdom_text_handler(merged_df):\n",
384
+ " texts = merged_df['text'].tolist()\n",
385
+ " labels = merged_df['label'].tolist()\n",
386
+ " annot_counts = merged_df['annotator_count'].astype(int).tolist()\n",
387
+ " return texts, labels, annot_counts\n",
388
+ "\n",
389
+ "def wisdom_any_text_handler(merged_df):\n",
390
+ " texts = merged_df['text'].tolist()\n",
391
+ " merged_df['polarized'] = merged_df['polarized'].apply(lambda x: [int(y) for y in ast.literal_eval(x)])\n",
392
+ " merged_df['polarized_value'] = merged_df['polarized'].apply(lambda x: sum(x)/len(x))\n",
393
+ " merged_df['any_label'] = merged_df['polarized_value'].apply(lambda x: 1 if x > 0 else 0) \n",
394
+ " any_label = merged_df['any_label'].tolist()\n",
395
+ " labels = merged_df['label'].tolist()\n",
396
+ " annot_counts = merged_df['annotator_count'].astype(int).tolist()\n",
397
+ " return texts, labels, annot_counts, any_label\n",
398
+ "\n",
399
+ "def train_wisdom_bert_pipeline(model_path: str, merged_df, output_dir: str, approach: str = \"single\"):\n",
400
+ "\n",
401
+ " # Handle texts and labels:\n",
402
+ " texts, labels, annot_counts = wisdom_text_handler(merged_df)\n",
403
+ "\n",
404
+ " # Create output directory\n",
405
+ " os.makedirs(output_dir, exist_ok=True)\n",
406
+ "\n",
407
+ " skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
408
+ " metrics_list = []\n",
409
+ "\n",
410
+ " for fold, (train_index, test_index) in enumerate(skf.split(texts, labels)):\n",
411
+ " train_annot_counts = np.array(annot_counts)[train_index]\n",
412
+ " train_texts, test_texts = np.array(texts)[train_index], np.array(texts)[test_index]\n",
413
+ " train_labels, test_labels = np.array(labels)[train_index], np.array(labels)[test_index]\n",
414
+ " target_annot_count = 1\n",
415
+ " if approach == \"single\":\n",
416
+ " train_indices = np.where(train_annot_counts == target_annot_count)[0]\n",
417
+ " train_texts = np.array(train_texts)[train_indices]\n",
418
+ " train_labels = np.array(train_labels)[train_indices]\n",
419
+ " elif approach == \"more\":\n",
420
+ " train_indices = np.where(train_annot_counts != target_annot_count)[0]\n",
421
+ " train_texts = np.array(train_texts)[train_indices]\n",
422
+ " train_labels = np.array(train_labels)[train_indices]\n",
423
+ " else:\n",
424
+ " raise ValueError(f\"Invalid approach: {approach}\")\n",
425
+ " # Tokenize\n",
426
+ " tokenizer = BertTokenizer.from_pretrained(model_path)\n",
427
+ " train_encodings = tokenizer(train_texts.tolist(), truncation=True, padding=True, max_length=512, return_tensors='pt')\n",
428
+ " test_encodings = tokenizer(test_texts.tolist(), truncation=True, padding=True, max_length=512, return_tensors='pt')\n",
429
+ "\n",
430
+ " train_dataset = Dataset(train_encodings, train_labels)\n",
431
+ " test_dataset = Dataset(test_encodings, test_labels)\n",
432
+ "\n",
433
+ " model = BertForSequenceClassification.from_pretrained(model_path, num_labels=len(set(labels)))\n",
434
+ "\n",
435
+ " training_args = TrainingArguments(\n",
436
+ " output_dir=os.path.join(output_dir, f\"model_fold_{fold}\"),\n",
437
+ " evaluation_strategy=\"epoch\",\n",
438
+ " per_device_train_batch_size=16,\n",
439
+ " per_device_eval_batch_size=64,\n",
440
+ " num_train_epochs=3,\n",
441
+ " logging_dir=os.path.join(output_dir, f\"logs_fold_{fold}\"),\n",
442
+ " )\n",
443
+ "\n",
444
+ " trainer = Trainer(\n",
445
+ " model=model,\n",
446
+ " args=training_args,\n",
447
+ " train_dataset=train_dataset,\n",
448
+ " eval_dataset=test_dataset,\n",
449
+ " compute_metrics=compute_metrics,\n",
450
+ " )\n",
451
+ "\n",
452
+ " # Train and evaluate\n",
453
+ " trainer.train()\n",
454
+ " metrics = trainer.evaluate()\n",
455
+ " metrics_list.append(metrics)\n",
456
+ "\n",
457
+ " # Save model\n",
458
+ " model.save_pretrained(os.path.join(output_dir, f\"model_fold_{fold}\"))\n",
459
+ " tokenizer.save_pretrained(os.path.join(output_dir, f\"model_fold_{fold}\"))\n",
460
+ "\n",
461
+ " # Save performance report\n",
462
+ " pd.DataFrame([metrics]).to_csv(os.path.join(output_dir, f\"performance_fold_{fold}.csv\"), index=False)\n",
463
+ "\n",
464
+ " # Calculate average performance metrics\n",
465
+ " avg_metrics = {metric: np.mean([m[metric] for m in metrics_list]) for metric in metrics_list[0]}\n",
466
+ " pd.DataFrame([avg_metrics]).to_csv(os.path.join(output_dir, \"average_performance.csv\"), index=False)\n",
467
+ "\n",
468
+ "from sklearn.utils import resample\n",
469
+ "\n",
470
+ "def train_wisdom_bert_normalized_sampling_pipeline(model_path: str, merged_df, output_dir: str, approach: str = \"single\"):\n",
471
+ "\n",
472
+ " # Handle texts and labels:\n",
473
+ " texts, labels, annot_counts = wisdom_text_handler(merged_df)\n",
474
+ " merged_df[\"label\"] = labels\n",
475
+ " merged_df[\"text\"] = texts\n",
476
+ " merged_df[\"annotator_count\"] = annot_counts\n",
477
+ "\n",
478
+ " # Create output directory\n",
479
+ " os.makedirs(output_dir, exist_ok=True)\n",
480
+ "\n",
481
+ " skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
482
+ " metrics_list = []\n",
483
+ "\n",
484
+ " for fold, (train_index, test_index) in enumerate(skf.split(texts, labels)):\n",
485
+ " train_df = merged_df.iloc[train_index]\n",
486
+ " test_df = merged_df.iloc[test_index]\n",
487
+ "\n",
488
+ " # Normalize class ratio in train_df\n",
489
+ " normalized_dfs = []\n",
490
+ " \n",
491
+ " if approach == \"single\":\n",
492
+ " subset = train_df[train_df[\"annotator_count\"] == 1]\n",
493
+ " elif approach == \"more\":\n",
494
+ " subset = train_df[train_df[\"annotator_count\"] != 1]\n",
495
+ " \n",
496
+ " # Split into classes\n",
497
+ " class_0 = subset[subset[\"label\"] == 0]\n",
498
+ " class_1 = subset[subset[\"label\"] == 1]\n",
499
+ "\n",
500
+ " # Desired number of class 1 samples to maintain a 1:3 ratio\n",
501
+ " target_class_1_count = len(class_0) // 3\n",
502
+ "\n",
503
+ " # Resample class 1 (upsample or downsample as needed)\n",
504
+ " if len(class_1) > target_class_1_count:\n",
505
+ " class_1_resampled = resample(class_1, replace=False, n_samples=target_class_1_count, random_state=42)\n",
506
+ " else:\n",
507
+ " class_1_resampled = resample(class_1, replace=True, n_samples=target_class_1_count, random_state=42)\n",
508
+ "\n",
509
+ " # Combine resampled class 1 with class 0\n",
510
+ " normalized_subset = pd.concat([class_0, class_1_resampled])\n",
511
+ " normalized_dfs.append(normalized_subset)\n",
512
+ " normalized_train_df = pd.concat(normalized_dfs)\n",
513
+ " print(normalized_train_df['label'].value_counts())\n",
514
+ "\n",
515
+ " # Prepare texts and labels for training\n",
516
+ " train_texts = normalized_train_df[\"text\"].tolist()\n",
517
+ " train_labels = normalized_train_df[\"label\"].tolist()\n",
518
+ "\n",
519
+ " test_texts = test_df[\"text\"].tolist()\n",
520
+ " test_labels = test_df[\"label\"].tolist()\n",
521
+ "\n",
522
+ " # Tokenize\n",
523
+ " tokenizer = BertTokenizer.from_pretrained(model_path)\n",
524
+ " train_encodings = tokenizer(train_texts, truncation=True, padding=True, max_length=512, return_tensors=\"pt\")\n",
525
+ " test_encodings = tokenizer(test_texts, truncation=True, padding=True, max_length=512, return_tensors=\"pt\")\n",
526
+ "\n",
527
+ " train_dataset = Dataset(train_encodings, train_labels)\n",
528
+ " test_dataset = Dataset(test_encodings, test_labels)\n",
529
+ "\n",
530
+ " model = BertForSequenceClassification.from_pretrained(model_path, num_labels=2)\n",
531
+ "\n",
532
+ " training_args = TrainingArguments(\n",
533
+ " output_dir=os.path.join(output_dir, f\"model_fold_{fold}\"),\n",
534
+ " evaluation_strategy=\"epoch\",\n",
535
+ " per_device_train_batch_size=16,\n",
536
+ " per_device_eval_batch_size=64,\n",
537
+ " num_train_epochs=3,\n",
538
+ " logging_dir=os.path.join(output_dir, f\"logs_fold_{fold}\"),\n",
539
+ " )\n",
540
+ "\n",
541
+ " trainer = Trainer(\n",
542
+ " model=model,\n",
543
+ " args=training_args,\n",
544
+ " train_dataset=train_dataset,\n",
545
+ " eval_dataset=test_dataset,\n",
546
+ " compute_metrics=compute_metrics,\n",
547
+ " )\n",
548
+ "\n",
549
+ " # Train and evaluate\n",
550
+ " trainer.train()\n",
551
+ " metrics = trainer.evaluate()\n",
552
+ " metrics_list.append(metrics)\n",
553
+ "\n",
554
+ " # Save model\n",
555
+ " model.save_pretrained(os.path.join(output_dir, f\"model_fold_{fold}\"))\n",
556
+ " tokenizer.save_pretrained(os.path.join(output_dir, f\"model_fold_{fold}\"))\n",
557
+ "\n",
558
+ " # Save performance report\n",
559
+ " pd.DataFrame([metrics]).to_csv(os.path.join(output_dir, f\"performance_fold_{fold}.csv\"), index=False)\n",
560
+ "\n",
561
+ " # Calculate average performance metrics\n",
562
+ " avg_metrics = {metric: np.mean([m[metric] for m in metrics_list]) for metric in metrics_list[0]}\n",
563
+ " pd.DataFrame([avg_metrics]).to_csv(os.path.join(output_dir, \"average_performance.csv\"), index=False)\n",
564
+ "\n",
565
+ "# Dataset class to handle encoding\n",
566
+ "class Dataset(torch.utils.data.Dataset):\n",
567
+ " def __init__(self, encodings, labels):\n",
568
+ " self.encodings = encodings\n",
569
+ " self.labels = [int(label) for label in labels] \n",
570
+ "\n",
571
+ " def __getitem__(self, idx):\n",
572
+ " item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}\n",
573
+ " item['labels'] = torch.tensor(self.labels[idx])\n",
574
+ " return item\n",
575
+ "\n",
576
+ " def __len__(self):\n",
577
+ " return len(self.labels)"
578
+ ]
579
+ },
580
+ {
581
+ "cell_type": "markdown",
582
+ "id": "ccd9dae4-279d-436c-9f31-c3326b143ea0",
583
+ "metadata": {},
584
+ "source": [
585
+ "## Using \"Polarization\" as a Feature for Toxicity Detection\n",
586
+ "Main Function:\n",
587
+ "`train_featural_bert_pipeline_with_polarized_feature`\n",
588
+ "\n",
589
+ "Note: \n",
590
+ "1. For method = `any`, `bin` and `bin-ceil` method are for pre-eliminary experiments. Both of these methods lead to a worse performing model than `agg`.\n",
591
+ "2. We attempted to use the English translation of the prompt to incorporate the \"Polarization\" feature. However, using the English translation leads to a worsening performance, as IndoBERTweet is mainly trained on the Indonesian language."
592
+ ]
593
+ },
594
+ {
595
+ "cell_type": "code",
596
+ "execution_count": null,
597
+ "id": "a6742fe8-2346-4295-98b2-6a95c915b497",
598
+ "metadata": {},
599
+ "outputs": [],
600
+ "source": [
601
+ "import pandas as pd\n",
602
+ "import ast\n",
603
+ "import os\n",
604
+ "import numpy as np\n",
605
+ "from sklearn.model_selection import StratifiedKFold\n",
606
+ "from transformers import Trainer, TrainingArguments, BertForSequenceClassification, BertTokenizer\n",
607
+ "import torch\n",
608
+ "\n",
609
+ "from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, roc_auc_score, average_precision_score\n",
610
+ "\n",
611
+ "def compute_metrics(pred):\n",
612
+ " labels = pred.label_ids\n",
613
+ " preds = pred.predictions.argmax(-1)\n",
614
+ "\n",
615
+ " # Accuracy\n",
616
+ " accuracy = accuracy_score(labels, preds)\n",
617
+ "\n",
618
+ " # Macro F1, Precision, and Recall\n",
619
+ " macro_f1 = f1_score(labels, preds, average='macro')\n",
620
+ " precision = precision_score(labels, preds, average='macro')\n",
621
+ " recall = recall_score(labels, preds, average='macro')\n",
622
+ "\n",
623
+ " # Class-1 only metrics (positive class)\n",
624
+ " precision_class_1 = precision_score(labels, preds, pos_label=1)\n",
625
+ " recall_class_1 = recall_score(labels, preds, pos_label=1)\n",
626
+ " f1_class_1 = f1_score(labels, preds, pos_label=1)\n",
627
+ "\n",
628
+ " # Class-0 only metrics (negative class)\n",
629
+ " precision_class_0 = precision_score(labels, preds, pos_label=0)\n",
630
+ " recall_class_0 = recall_score(labels, preds, pos_label=0)\n",
631
+ " f1_class_0 = f1_score(labels, preds, pos_label=0)\n",
632
+ "\n",
633
+ " # ROC-AUC score for binary classification\n",
634
+ " try:\n",
635
+ " # Compute the ROC AUC score for binary classification directly\n",
636
+ " roc_auc = roc_auc_score(labels, preds)\n",
637
+ " except ValueError:\n",
638
+ " # In case there's an issue with the labels or predictions (e.g., all labels are the same)\n",
639
+ " roc_auc = 0.5 # This would represent random classification if AUC can't be computed\n",
640
+ "\n",
641
+ " # Precision-Recall AUC\n",
642
+ " precision_recall_auc = average_precision_score(labels, preds)\n",
643
+ "\n",
644
+ " return {\n",
645
+ " 'accuracy': accuracy,\n",
646
+ " 'macro_f1': macro_f1,\n",
647
+ " 'precision': precision,\n",
648
+ " 'recall': recall,\n",
649
+ " 'precision_class_1': precision_class_1,\n",
650
+ " 'recall_class_1': recall_class_1,\n",
651
+ " 'f1_class_1': f1_class_1,\n",
652
+ " 'precision_class_0': precision_class_0,\n",
653
+ " 'recall_class_0': recall_class_0,\n",
654
+ " 'f1_class_0': f1_class_0,\n",
655
+ " 'roc_auc': roc_auc,\n",
656
+ " 'precision_recall_auc': precision_recall_auc,\n",
657
+ " }\n",
658
+ "\n",
659
+ "def featural_text_handler(merged_df, method: str = \"agg\", language: str = \"id\"):\n",
660
+ " \"\"\"\n",
661
+ " Handles toxic and non-toxic text datasets for toxicity classification, \n",
662
+ " applying polarization processing and text formatting.\n",
663
+ "\n",
664
+ " Method options:\n",
665
+ " 1. agg = Aggregate value with a range of [0, 1].\n",
666
+ " 2. bin = Binarized, values of either 0 or 1 (values of 0.5 converted to 0).\n",
667
+ " 3. bin-ceil = Binarized, but values of 0.5 converted to 1.\n",
668
+ " 4. any = Binarized, any value above 0 is converted to 1.\n",
669
+ "\n",
670
+ " Language options:\n",
671
+ " 1. id = Indonesian.\n",
672
+ " 2. en = English.\n",
673
+ " \"\"\"\n",
674
+ " def process_polarized_values(row, method):\n",
675
+ " \"\"\"Processes the polarization values according to the selected method.\"\"\"\n",
676
+ " values = ast.literal_eval(row['polarized']) if isinstance(row['polarized'], str) else row['polarized']\n",
677
+ " values = [int(x) for x in values]\n",
678
+ " if not values:\n",
679
+ " return 0 # Default for missing or empty polarization\n",
680
+ " \n",
681
+ " agg_value = sum(values) / len(values)\n",
682
+ " if method == \"agg\":\n",
683
+ " return agg_value\n",
684
+ " elif method == \"bin\":\n",
685
+ " return 1 if agg_value > 0.5 else 0\n",
686
+ " elif method == \"bin-ceil\":\n",
687
+ " return 1 if agg_value >= 0.5 else 0\n",
688
+ " elif method == \"any\":\n",
689
+ " return 1 if agg_value > 0 else 0\n",
690
+ " else:\n",
691
+ " raise ValueError(f\"Unsupported method: {method}\")\n",
692
+ " merged_df['polarized'] = merged_df['polarized'].fillna(0)\n",
693
+ " merged_df['polarized_value'] = merged_df.apply(lambda row: process_polarized_values(row, method), axis=1)\n",
694
+ "\n",
695
+ " # Format text based on language and add polarization\n",
696
+ " def format_text(row, language):\n",
697
+ " if language == \"id\":\n",
698
+ " return f\"Nilai polarisasi rata-rata (rentang 0 hingga 1): {row['polarized_value']} [SEP] {row['text']}\"\n",
699
+ " elif language == \"en\":\n",
700
+ " return f\"Average polarization value (range of 0 to 1): {row['polarized_value']} [SEP] {row['text']}\"\n",
701
+ " else:\n",
702
+ " raise ValueError(f\"Unsupported language: {language}\")\n",
703
+ "\n",
704
+ " merged_df['combined_text'] = merged_df.apply(lambda row: format_text(row, language), axis=1)\n",
705
+ "\n",
706
+ " # Prepare outputs\n",
707
+ " texts = merged_df['combined_text'].tolist()\n",
708
+ " labels = merged_df['label'].tolist()\n",
709
+ "\n",
710
+ " return texts, labels\n",
711
+ "\n",
712
+ "\n",
713
+ "def train_featural_bert_pipeline_with_polarized_feature(model_path: str, merged_df, output_dir: str,\n",
714
+ " method: str = \"agg\", language: str = \"id\", raw_test: bool = False):\n",
715
+ " # Handle texts and labels\n",
716
+ " texts, labels = featural_text_handler(merged_df, method, language)\n",
717
+ "\n",
718
+ " # Create output directory\n",
719
+ " os.makedirs(output_dir, exist_ok=True)\n",
720
+ "\n",
721
+ " skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
722
+ " metrics_list = []\n",
723
+ "\n",
724
+ " for fold, (train_index, test_index) in enumerate(skf.split(texts, labels)):\n",
725
+ " train_texts, test_texts = np.array(texts)[train_index], np.array(texts)[test_index]\n",
726
+ " if raw_test:\n",
727
+ " test_texts = [text.split('[SEP]')[-1].strip() for text in test_texts]\n",
728
+ " train_labels, test_labels = np.array(labels)[train_index], np.array(labels)[test_index]\n",
729
+ "\n",
730
+ " # Tokenize\n",
731
+ " tokenizer = BertTokenizer.from_pretrained(model_path)\n",
732
+ " train_encodings = tokenizer(list(train_texts), truncation=True, padding=True, max_length=512, return_tensors='pt')\n",
733
+ " test_encodings = tokenizer(list(test_texts), truncation=True, padding=True, max_length=512, return_tensors='pt')\n",
734
+ "\n",
735
+ " train_dataset = Dataset(train_encodings, train_labels)\n",
736
+ " test_dataset = Dataset(test_encodings, test_labels)\n",
737
+ "\n",
738
+ " model = BertForSequenceClassification.from_pretrained(model_path, num_labels=len(set(labels)))\n",
739
+ "\n",
740
+ " training_args = TrainingArguments(\n",
741
+ " output_dir=os.path.join(output_dir, f\"model_fold_{fold}\"),\n",
742
+ " evaluation_strategy=\"epoch\",\n",
743
+ " per_device_train_batch_size=16,\n",
744
+ " per_device_eval_batch_size=64,\n",
745
+ " num_train_epochs=3,\n",
746
+ " logging_dir=os.path.join(output_dir, f\"logs_fold_{fold}\"),\n",
747
+ " save_strategy=\"no\",\n",
748
+ " )\n",
749
+ "\n",
750
+ " trainer = Trainer(\n",
751
+ " model=model,\n",
752
+ " args=training_args,\n",
753
+ " train_dataset=train_dataset,\n",
754
+ " eval_dataset=test_dataset,\n",
755
+ " compute_metrics=compute_metrics,\n",
756
+ " )\n",
757
+ "\n",
758
+ " # Train and evaluate\n",
759
+ " trainer.train()\n",
760
+ " metrics = trainer.evaluate()\n",
761
+ " metrics_list.append(metrics)\n",
762
+ "\n",
763
+ " # Save performance report\n",
764
+ " pd.DataFrame([metrics]).to_csv(os.path.join(output_dir, f\"performance_fold_{fold}.csv\"), index=False)\n",
765
+ "\n",
766
+ " # Calculate average performance metrics\n",
767
+ " avg_metrics = {metric: np.mean([m[metric] for m in metrics_list]) for metric in metrics_list[0]}\n",
768
+ " pd.DataFrame([avg_metrics]).to_csv(os.path.join(output_dir, \"average_performance.csv\"), index=False)\n",
769
+ "\n",
770
+ "# Dataset class to handle encoding\n",
771
+ "class Dataset(torch.utils.data.Dataset):\n",
772
+ " def __init__(self, encodings, labels):\n",
773
+ " self.encodings = encodings\n",
774
+ " self.labels = [int(label) for label in labels] \n",
775
+ "\n",
776
+ " def __getitem__(self, idx):\n",
777
+ " item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}\n",
778
+ " item['labels'] = torch.tensor(self.labels[idx])\n",
779
+ " return item\n",
780
+ "\n",
781
+ " def __len__(self):\n",
782
+ " return len(self.labels)\n"
783
+ ]
784
+ },
785
+ {
786
+ "cell_type": "markdown",
787
+ "id": "6f2d9779-56f3-400f-bf08-9085532026ba",
788
+ "metadata": {},
789
+ "source": [
790
+ "## 4. Incorporating Demographic Information\n",
791
+ "Some normalization are required before passing the values to the model.\n",
792
+ "\n",
793
+ "\n",
794
+ "Main function: `exploded_df_train_baseline_bert_pipeline_with_demographic_feature`"
795
+ ]
796
+ },
797
+ {
798
+ "cell_type": "code",
799
+ "execution_count": null,
800
+ "id": "7d7a591a-fb1c-495e-ba69-cc11d3b2a94c",
801
+ "metadata": {},
802
+ "outputs": [],
803
+ "source": [
804
+ "import pandas as pd\n",
805
+ "import ast\n",
806
+ "import os\n",
807
+ "import numpy as np\n",
808
+ "from typing import List\n",
809
+ "from sklearn.model_selection import StratifiedKFold\n",
810
+ "from transformers import Trainer, TrainingArguments, BertForSequenceClassification, BertTokenizer\n",
811
+ "import torch\n",
812
+ "\n",
813
+ "from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, roc_auc_score, average_precision_score\n",
814
+ "\n",
815
+ "def compute_metrics(pred):\n",
816
+ " labels = pred.label_ids\n",
817
+ " preds = pred.predictions.argmax(-1)\n",
818
+ "\n",
819
+ " # Accuracy\n",
820
+ " accuracy = accuracy_score(labels, preds)\n",
821
+ "\n",
822
+ " # Macro F1, Precision, and Recall\n",
823
+ " macro_f1 = f1_score(labels, preds, average='macro')\n",
824
+ " precision = precision_score(labels, preds, average='macro')\n",
825
+ " recall = recall_score(labels, preds, average='macro')\n",
826
+ "\n",
827
+ " # Class-1 only metrics (positive class)\n",
828
+ " precision_class_1 = precision_score(labels, preds, pos_label=1)\n",
829
+ " recall_class_1 = recall_score(labels, preds, pos_label=1)\n",
830
+ " f1_class_1 = f1_score(labels, preds, pos_label=1)\n",
831
+ "\n",
832
+ " # Class-0 only metrics (negative class)\n",
833
+ " precision_class_0 = precision_score(labels, preds, pos_label=0)\n",
834
+ " recall_class_0 = recall_score(labels, preds, pos_label=0)\n",
835
+ " f1_class_0 = f1_score(labels, preds, pos_label=0)\n",
836
+ "\n",
837
+ " # ROC-AUC score for binary classification\n",
838
+ " try:\n",
839
+ " # Compute the ROC AUC score for binary classification directly\n",
840
+ " roc_auc = roc_auc_score(labels, preds)\n",
841
+ " except ValueError:\n",
842
+ " # In case there's an issue with the labels or predictions (e.g., all labels are the same)\n",
843
+ " roc_auc = 0.5 # This would represent random classification if AUC can't be computed\n",
844
+ "\n",
845
+ " # Precision-Recall AUC\n",
846
+ " precision_recall_auc = average_precision_score(labels, preds)\n",
847
+ "\n",
848
+ " return {\n",
849
+ " 'accuracy': accuracy,\n",
850
+ " 'macro_f1': macro_f1,\n",
851
+ " 'precision': precision,\n",
852
+ " 'recall': recall,\n",
853
+ " 'precision_class_1': precision_class_1,\n",
854
+ " 'recall_class_1': recall_class_1,\n",
855
+ " 'f1_class_1': f1_class_1,\n",
856
+ " 'precision_class_0': precision_class_0,\n",
857
+ " 'recall_class_0': recall_class_0,\n",
858
+ " 'f1_class_0': f1_class_0,\n",
859
+ " 'roc_auc': roc_auc,\n",
860
+ " 'precision_recall_auc': precision_recall_auc,\n",
861
+ " }\n",
862
+ "\n",
863
+ "def demographic_text_handler(merged_df):\n",
864
+ " texts = merged_df['text'].tolist()\n",
865
+ " labels = merged_df['label'].tolist()\n",
866
+ " return merged_df, texts, labels\n",
867
+ "\n",
868
+ "def single_level_demographic_text_handler(df, demographic: List[str] = [], language: str = \"id\"):\n",
869
+ " \"\"\"\n",
870
+ " Handles polar and non-polar text datasets for polarity classification, \n",
871
+ " applying demographic information\n",
872
+ "\n",
873
+ " Language options:\n",
874
+ " 1. id = Indonesian.\n",
875
+ " 2. en = English.\n",
876
+ "\n",
877
+ " Demographic options, may be a list of strings:\n",
878
+ " 1. ethnicity\n",
879
+ " 2. religion\n",
880
+ " 3. disability\n",
881
+ " 4. lgbt\n",
882
+ " 5. gender\n",
883
+ " 6. age_group\n",
884
+ " 7. domisili\n",
885
+ " 8. pendidikan terakhir\n",
886
+ " 9. status pekerjaan\n",
887
+ " 10. president vote leaning\n",
888
+ " \"\"\"\n",
889
+ "\n",
890
+ " id_demographic_names = {\n",
891
+ " 'ethnicity': 'etnisitas',\n",
892
+ " 'religion' : 'agama',\n",
893
+ " 'disability': 'disabilitas',\n",
894
+ " 'lgbt' : 'lgbt',\n",
895
+ " 'gender': 'gender',\n",
896
+ " 'age_group': 'generasi',\n",
897
+ " 'domisili': 'domisili',\n",
898
+ " 'pendidikan terakhir': 'pendidikan terakhir',\n",
899
+ " 'status pekerjaan': 'status pekerjaan',\n",
900
+ " 'president vote leaning': 'pilihan presiden'\n",
901
+ " }\n",
902
+ "\n",
903
+ " en_demographic_names = {\n",
904
+ " 'ethnicity': 'ethnicity',\n",
905
+ " 'religion': 'religion',\n",
906
+ " 'disability': 'disability',\n",
907
+ " 'lgbt': 'lgbt',\n",
908
+ " 'gender': 'gender',\n",
909
+ " 'age_group': 'generation',\n",
910
+ " 'domisili': 'domicile',\n",
911
+ " 'pendidikan terakhir': 'last education level',\n",
912
+ " 'status pekerjaan': 'job status',\n",
913
+ " 'president vote leaning': 'president vote leaning'\n",
914
+ " \n",
915
+ " }\n",
916
+ "\n",
917
+ " # preprocess toxic dataset\n",
918
+ " df['label'] = df['toxicity']\n",
919
+ " \n",
920
+ " # Format text based on language and add polarization\n",
921
+ " def format_text(row, language, demographic):\n",
922
+ " if language == \"id\":\n",
923
+ " if len(demographic) == 0:\n",
924
+ " return \"Informasi Demografis: Tidak tersedia\"\n",
925
+ " \n",
926
+ " input_string = \"Informasi Demografis:\\n\"\n",
927
+ " for demo in demographic:\n",
928
+ " input_string += f\"{id_demographic_names[demo]}: {row[demo]}\\n\"\n",
929
+ " input_string = input_string.strip(\"\\n\")\n",
930
+ " input_string = f\"{input_string} [SEP] {row['text']}\"\n",
931
+ " return input_string\n",
932
+ " elif language == \"en\":\n",
933
+ " if len(demographic) == 0:\n",
934
+ " return \"Demographic Information: Not available\"\n",
935
+ "\n",
936
+ " input_string = \"Demographic Information:\\n\"\n",
937
+ " for demo in demographic:\n",
938
+ " input_string += f\"{en_demographic_names[demo]}: {row[demo]}\\n\"\n",
939
+ " input_string = input_string.strip(\"\\n\")\n",
940
+ " input_string = f\"{input_string} [SEP] {row['text']}\"\n",
941
+ " return input_string\n",
942
+ " else:\n",
943
+ " raise ValueError(f\"Unsupported language: {language}\")\n",
944
+ "\n",
945
+ " df['combined_text'] = df.apply(lambda row: format_text(row, language, demographic), axis=1)\n",
946
+ " print(df['label'].value_counts())\n",
947
+ "\n",
948
+ " # Prepare outputs\n",
949
+ " texts = df['combined_text'].tolist()\n",
950
+ " labels = df['label'].tolist()\n",
951
+ "\n",
952
+ " return texts, labels\n",
953
+ "\n",
954
+ "import pandas as pd\n",
955
+ "import ast\n",
956
+ "def process_and_explode(df):\n",
957
+ " def age_group_f(x):\n",
958
+ " if 12 <= x <= 29:\n",
959
+ " return \"Gen Z\"\n",
960
+ " if 30 <= x <= 44:\n",
961
+ " return \"Millenials\"\n",
962
+ " if 45 <= x <= 59:\n",
963
+ " return \"Gen X\"\n",
964
+ " \n",
965
+ " def president_vote_f(x):\n",
966
+ " if x == \"1\":\n",
967
+ " return \"Anies Rasyid Baswedan-Muhaimin Iskandar\"\n",
968
+ " if x == \"2\":\n",
969
+ " return \"Prabowo Subianto-Gibran Rakabuming Raka\"\n",
970
+ " if x == \"3\":\n",
971
+ " return \"Ganjar Pranowo-Mahfud MD\"\n",
972
+ " return x \n",
973
+ " \n",
974
+ " annotator_df = pd.read_json(\"hf://datasets/Exqrch/IndoToxic2024/indotoxic2024_annotator_demographic_data_v2_final.jsonl\", lines=True)\n",
975
+ " annotator_df['gender'] = annotator_df['gender'].apply(lambda x: x.strip())\n",
976
+ " annotator_df['age_group'] = annotator_df['age'].astype(int)\n",
977
+ " annotator_df['age_group'] = annotator_df['age_group'].apply(lambda x: age_group_f(x))\n",
978
+ " annotator_df['status pekerjaan'] = annotator_df['status pekerjaan'].apply(lambda x: 'Tidak Bekerja' if x == \"Ibu Rumah Tangga\" else x)\n",
979
+ " annotator_df['president vote leaning'] = annotator_df['president vote leaning'].apply(lambda x: \"Tidak ada\" if x not in [\"1\", \"2\", \"3\"] else x)\n",
980
+ " annotator_df['president vote leaning'] = annotator_df['president vote leaning'].apply(lambda x : president_vote_f(x)) \n",
981
+ " annotator_df['annotator_id'] = annotator_df['annotator_id'].astype(str)\n",
982
+ "\n",
983
+ " columns = [\n",
984
+ " 'is_noise_or_spam_text',\n",
985
+ " 'related_to_election_2024',\n",
986
+ " 'toxicity',\n",
987
+ " 'polarized',\n",
988
+ " 'profanity_obscenity',\n",
989
+ " 'threat_incitement_to_violence',\n",
990
+ " 'insults',\n",
991
+ " 'identity_attack',\n",
992
+ " 'sexually_explicit'\n",
993
+ " ]\n",
994
+ "\n",
995
+ " df['annotators_id'] = df['annotators_id'].apply(lambda x: ast.literal_eval(x))\n",
996
+ " df_exploded = df.explode('annotators_id')\n",
997
+ " df_exploded.rename(columns={\n",
998
+ " 'annotators_id': 'annotator_id'\n",
999
+ " }, inplace=True)\n",
1000
+ " merged_df = df_exploded.merge(annotator_df, on=\"annotator_id\", how=\"inner\")\n",
1001
+ " merged_df['text_id_index'] = merged_df.groupby('text_id').cumcount()\n",
1002
+ " merged_df['text_id_index'] = merged_df['text_id_index'].astype(int)\n",
1003
+ " for col in columns:\n",
1004
+ " merged_df[col] = merged_df[col].apply(lambda x: ast.literal_eval(x))\n",
1005
+ " merged_df[col] = merged_df.apply(lambda row: row[col][row['text_id_index']], axis=1)\n",
1006
+ "\n",
1007
+ " return merged_df\n",
1008
+ " \n",
1009
+ "def exploded_df_train_baseline_bert_pipeline_with_demographic_feature(model_path: str, \n",
1010
+ " merged_df, \n",
1011
+ " output_dir: str,\n",
1012
+ " demographic: List[str] = [], \n",
1013
+ " language: str = \"id\",\n",
1014
+ " raw_test: bool = False):\n",
1015
+ " # Handle texts and labels\n",
1016
+ " original_df, texts, labels = demographic_text_handler(merged_df) # Just using this to ensure replicability with old baseline\n",
1017
+ "\n",
1018
+ " # Create output directory\n",
1019
+ " os.makedirs(output_dir, exist_ok=True)\n",
1020
+ "\n",
1021
+ " skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
1022
+ " metrics_list = []\n",
1023
+ "\n",
1024
+ " for fold, (train_index, test_index) in enumerate(skf.split(texts, labels)):\n",
1025
+ " train_df = original_df.iloc[train_index]\n",
1026
+ " test_df = original_df.iloc[test_index]\n",
1027
+ "\n",
1028
+ " train_df = process_and_explode(train_df)\n",
1029
+ " test_df = process_and_explode(test_df)\n",
1030
+ "\n",
1031
+ " train_texts, train_labels = single_level_demographic_text_handler(train_df, demographic, language)\n",
1032
+ " test_texts, test_labels = single_level_demographic_text_handler(test_df, demographic, language)\n",
1033
+ " \n",
1034
+ " if raw_test:\n",
1035
+ " test_texts = [text.split('[SEP]')[-1].strip() for text in test_texts]\n",
1036
+ "\n",
1037
+ " train_labels = [int(x) for x in train_labels]\n",
1038
+ " test_labels = [int(x) for x in test_labels]\n",
1039
+ "\n",
1040
+ " # Tokenize\n",
1041
+ " tokenizer = BertTokenizer.from_pretrained(model_path)\n",
1042
+ " train_encodings = tokenizer(list(train_texts), truncation=True, padding=True, max_length=512, return_tensors='pt')\n",
1043
+ " test_encodings = tokenizer(list(test_texts), truncation=True, padding=True, max_length=512, return_tensors='pt')\n",
1044
+ "\n",
1045
+ " train_dataset = Dataset(train_encodings, train_labels)\n",
1046
+ " test_dataset = Dataset(test_encodings, test_labels)\n",
1047
+ "\n",
1048
+ " model = BertForSequenceClassification.from_pretrained(model_path, num_labels=len(set(train_labels)))\n",
1049
+ "\n",
1050
+ " training_args = TrainingArguments(\n",
1051
+ " output_dir=os.path.join(output_dir, f\"temp_model_fold_{fold}\"), # Temporary directory for Trainer\n",
1052
+ " evaluation_strategy=\"epoch\",\n",
1053
+ " per_device_train_batch_size=16,\n",
1054
+ " per_device_eval_batch_size=64,\n",
1055
+ " num_train_epochs=3,\n",
1056
+ " logging_dir=os.path.join(output_dir, f\"logs_fold_{fold}\"),\n",
1057
+ " save_strategy=\"no\", # Prevent model saving during fold training\n",
1058
+ " )\n",
1059
+ "\n",
1060
+ " trainer = Trainer(\n",
1061
+ " model=model,\n",
1062
+ " args=training_args,\n",
1063
+ " train_dataset=train_dataset,\n",
1064
+ " eval_dataset=test_dataset,\n",
1065
+ " compute_metrics=compute_metrics,\n",
1066
+ " )\n",
1067
+ "\n",
1068
+ " # Train and evaluate\n",
1069
+ " trainer.train()\n",
1070
+ " metrics = trainer.evaluate()\n",
1071
+ " metrics_list.append(metrics)\n",
1072
+ "\n",
1073
+ " # Save performance report\n",
1074
+ " pd.DataFrame([metrics]).to_csv(os.path.join(output_dir, f\"performance_fold_{fold}.csv\"), index=False)\n",
1075
+ "\n",
1076
+ " # Calculate average performance metrics\n",
1077
+ " avg_metrics = {metric: np.mean([m[metric] for m in metrics_list]) for metric in metrics_list[0]}\n",
1078
+ " pd.DataFrame([avg_metrics]).to_csv(os.path.join(output_dir, \"average_performance.csv\"), index=False)\n",
1079
+ "\n",
1080
+ "# Dataset class to handle encoding\n",
1081
+ "class Dataset(torch.utils.data.Dataset):\n",
1082
+ " def __init__(self, encodings, labels):\n",
1083
+ " self.encodings = encodings\n",
1084
+ " self.labels = [int(label) for label in labels] \n",
1085
+ "\n",
1086
+ " def __getitem__(self, idx):\n",
1087
+ " item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}\n",
1088
+ " item['labels'] = torch.tensor(self.labels[idx])\n",
1089
+ " return item\n",
1090
+ "\n",
1091
+ " def __len__(self):\n",
1092
+ " return len(self.labels)\n"
1093
+ ]
1094
+ },
1095
+ {
1096
+ "cell_type": "markdown",
1097
+ "id": "1c18e970-0af6-495a-afbc-c03a6122ab43",
1098
+ "metadata": {},
1099
+ "source": [
1100
+ "## 5. Combining Polarization and Demographic Information for Toxicity Detection\n",
1101
+ "Main Function: `exploded_df_train_baseline_bert_pipeline_with_polarization_and_demographic_feature`"
1102
+ ]
1103
+ },
1104
+ {
1105
+ "cell_type": "code",
1106
+ "execution_count": null,
1107
+ "id": "65331385-1a47-42b6-b4d2-2e930e045178",
1108
+ "metadata": {},
1109
+ "outputs": [],
1110
+ "source": [
1111
+ "import pandas as pd\n",
1112
+ "import ast\n",
1113
+ "import os\n",
1114
+ "import numpy as np\n",
1115
+ "from typing import List\n",
1116
+ "from sklearn.model_selection import StratifiedKFold\n",
1117
+ "from transformers import Trainer, TrainingArguments, BertForSequenceClassification, BertTokenizer\n",
1118
+ "import torch\n",
1119
+ "\n",
1120
+ "from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, roc_auc_score, average_precision_score\n",
1121
+ "\n",
1122
+ "def compute_metrics(pred):\n",
1123
+ " labels = pred.label_ids\n",
1124
+ " preds = pred.predictions.argmax(-1)\n",
1125
+ "\n",
1126
+ " # Accuracy\n",
1127
+ " accuracy = accuracy_score(labels, preds)\n",
1128
+ "\n",
1129
+ " # Macro F1, Precision, and Recall\n",
1130
+ " macro_f1 = f1_score(labels, preds, average='macro')\n",
1131
+ " precision = precision_score(labels, preds, average='macro')\n",
1132
+ " recall = recall_score(labels, preds, average='macro')\n",
1133
+ "\n",
1134
+ " # Class-1 only metrics (positive class)\n",
1135
+ " precision_class_1 = precision_score(labels, preds, pos_label=1)\n",
1136
+ " recall_class_1 = recall_score(labels, preds, pos_label=1)\n",
1137
+ " f1_class_1 = f1_score(labels, preds, pos_label=1)\n",
1138
+ "\n",
1139
+ " # Class-0 only metrics (negative class)\n",
1140
+ " precision_class_0 = precision_score(labels, preds, pos_label=0)\n",
1141
+ " recall_class_0 = recall_score(labels, preds, pos_label=0)\n",
1142
+ " f1_class_0 = f1_score(labels, preds, pos_label=0)\n",
1143
+ "\n",
1144
+ " # ROC-AUC score for binary classification\n",
1145
+ " try:\n",
1146
+ " # Compute the ROC AUC score for binary classification directly\n",
1147
+ " roc_auc = roc_auc_score(labels, preds)\n",
1148
+ " except ValueError:\n",
1149
+ " # In case there's an issue with the labels or predictions (e.g., all labels are the same)\n",
1150
+ " roc_auc = 0.5 # This would represent random classification if AUC can't be computed\n",
1151
+ "\n",
1152
+ " # Precision-Recall AUC\n",
1153
+ " precision_recall_auc = average_precision_score(labels, preds)\n",
1154
+ "\n",
1155
+ " return {\n",
1156
+ " 'accuracy': accuracy,\n",
1157
+ " 'macro_f1': macro_f1,\n",
1158
+ " 'precision': precision,\n",
1159
+ " 'recall': recall,\n",
1160
+ " 'precision_class_1': precision_class_1,\n",
1161
+ " 'recall_class_1': recall_class_1,\n",
1162
+ " 'f1_class_1': f1_class_1,\n",
1163
+ " 'precision_class_0': precision_class_0,\n",
1164
+ " 'recall_class_0': recall_class_0,\n",
1165
+ " 'f1_class_0': f1_class_0,\n",
1166
+ " 'roc_auc': roc_auc,\n",
1167
+ " 'precision_recall_auc': precision_recall_auc,\n",
1168
+ " }\n",
1169
+ "\n",
1170
+ "def single_level_toxicity_and_demographic_text_handler(df, demographic: List[str] = [], language: str = \"id\"):\n",
1171
+ " \"\"\"\n",
1172
+ " Handles polar and non-polar text datasets for polarity classification, \n",
1173
+ " applying demographic information\n",
1174
+ "\n",
1175
+ " Language options:\n",
1176
+ " 1. id = Indonesian.\n",
1177
+ " 2. en = English.\n",
1178
+ "\n",
1179
+ " Demographic options, may be a list of strings:\n",
1180
+ " 1. ethnicity\n",
1181
+ " 2. religion\n",
1182
+ " 3. disability\n",
1183
+ " 4. lgbt\n",
1184
+ " 5. gender\n",
1185
+ " 6. age_group\n",
1186
+ " 7. domisili\n",
1187
+ " 8. pendidikan terakhir\n",
1188
+ " 9. status pekerjaan\n",
1189
+ " 10. president vote leaning\n",
1190
+ " \"\"\"\n",
1191
+ "\n",
1192
+ " id_demographic_names = {\n",
1193
+ " 'ethnicity': 'etnisitas',\n",
1194
+ " 'religion' : 'agama',\n",
1195
+ " 'disability': 'disabilitas',\n",
1196
+ " 'lgbt' : 'lgbt',\n",
1197
+ " 'gender': 'gender',\n",
1198
+ " 'age_group': 'generasi',\n",
1199
+ " 'domisili': 'domisili',\n",
1200
+ " 'pendidikan terakhir': 'pendidikan terakhir',\n",
1201
+ " 'status pekerjaan': 'status pekerjaan',\n",
1202
+ " 'president vote leaning': 'pilihan presiden'\n",
1203
+ " }\n",
1204
+ "\n",
1205
+ " en_demographic_names = {\n",
1206
+ " 'ethnicity': 'ethnicity',\n",
1207
+ " 'religion': 'religion',\n",
1208
+ " 'disability': 'disability',\n",
1209
+ " 'lgbt': 'lgbt',\n",
1210
+ " 'gender': 'gender',\n",
1211
+ " 'age_group': 'generation',\n",
1212
+ " 'domisili': 'domicile',\n",
1213
+ " 'pendidikan terakhir': 'last education level',\n",
1214
+ " 'status pekerjaan': 'job status',\n",
1215
+ " 'president vote leaning': 'president vote leaning'\n",
1216
+ " \n",
1217
+ " }\n",
1218
+ "\n",
1219
+ " # preprocess toxic dataset\n",
1220
+ " df['label'] = df['toxicity']\n",
1221
+ " \n",
1222
+ " # Format text based on language and add polarization\n",
1223
+ " def format_text(row, language, demographic):\n",
1224
+ " if language == \"id\":\n",
1225
+ " if len(demographic) == 0:\n",
1226
+ " return \"Informasi Demografis dan Toksisitas: Tidak tersedia\"\n",
1227
+ " \n",
1228
+ " input_string = f\"{row['combined_text']}\\nInformasi Demografis:\\n\"\n",
1229
+ " for demo in demographic:\n",
1230
+ " input_string += f\"{id_demographic_names[demo]}: {row[demo]}\\n\"\n",
1231
+ " input_string = input_string.strip(\"\\n\")\n",
1232
+ " input_string = f\"{input_string} [SEP] {row['text']}\"\n",
1233
+ " return input_string\n",
1234
+ " elif language == \"en\":\n",
1235
+ " if len(demographic) == 0:\n",
1236
+ " return \"Demographic Information and Toxicity: Not available\"\n",
1237
+ "\n",
1238
+ " input_string = f\"{row['combined_text']}\\nDemographic Information:\\n\"\n",
1239
+ " for demo in demographic:\n",
1240
+ " input_string += f\"{en_demographic_names[demo]}: {row[demo]}\\n\"\n",
1241
+ " input_string = input_string.strip(\"\\n\")\n",
1242
+ " input_string = f\"{input_string} [SEP] {row['text']}\"\n",
1243
+ " return input_string\n",
1244
+ " else:\n",
1245
+ " raise ValueError(f\"Unsupported language: {language}\")\n",
1246
+ "\n",
1247
+ " df['combined_text'] = df.apply(lambda row: format_text(row, language, demographic), axis=1)\n",
1248
+ " print(df['label'].value_counts())\n",
1249
+ "\n",
1250
+ " # Prepare outputs\n",
1251
+ " texts = df['combined_text'].tolist()\n",
1252
+ " labels = df['label'].tolist()\n",
1253
+ "\n",
1254
+ " return texts, labels\n",
1255
+ "\n",
1256
+ "import pandas as pd\n",
1257
+ "import ast\n",
1258
+ "def process_and_explode(df):\n",
1259
+ " def age_group_f(x):\n",
1260
+ " if 12 <= x <= 29:\n",
1261
+ " return \"Gen Z\"\n",
1262
+ " if 30 <= x <= 44:\n",
1263
+ " return \"Millenials\"\n",
1264
+ " if 45 <= x <= 59:\n",
1265
+ " return \"Gen X\"\n",
1266
+ " \n",
1267
+ " def president_vote_f(x):\n",
1268
+ " if x == \"1\":\n",
1269
+ " return \"Anies Rasyid Baswedan-Muhaimin Iskandar\"\n",
1270
+ " if x == \"2\":\n",
1271
+ " return \"Prabowo Subianto-Gibran Rakabuming Raka\"\n",
1272
+ " if x == \"3\":\n",
1273
+ " return \"Ganjar Pranowo-Mahfud MD\"\n",
1274
+ " return x \n",
1275
+ " \n",
1276
+ " annotator_df = pd.read_json(\"hf://datasets/Exqrch/IndoToxic2024/indotoxic2024_annotator_demographic_data_v2_final.jsonl\", lines=True)\n",
1277
+ " annotator_df['gender'] = annotator_df['gender'].apply(lambda x: x.strip())\n",
1278
+ " annotator_df['age_group'] = annotator_df['age'].astype(int)\n",
1279
+ " annotator_df['age_group'] = annotator_df['age_group'].apply(lambda x: age_group_f(x))\n",
1280
+ " annotator_df['status pekerjaan'] = annotator_df['status pekerjaan'].apply(lambda x: 'Tidak Bekerja' if x == \"Ibu Rumah Tangga\" else x)\n",
1281
+ " annotator_df['president vote leaning'] = annotator_df['president vote leaning'].apply(lambda x: \"Tidak ada\" if x not in [\"1\", \"2\", \"3\"] else x)\n",
1282
+ " annotator_df['president vote leaning'] = annotator_df['president vote leaning'].apply(lambda x : president_vote_f(x)) \n",
1283
+ " annotator_df['annotator_id'] = annotator_df['annotator_id'].astype(str)\n",
1284
+ "\n",
1285
+ " columns = [\n",
1286
+ " 'is_noise_or_spam_text',\n",
1287
+ " 'related_to_election_2024',\n",
1288
+ " 'toxicity',\n",
1289
+ " 'polarized',\n",
1290
+ " 'profanity_obscenity',\n",
1291
+ " 'threat_incitement_to_violence',\n",
1292
+ " 'insults',\n",
1293
+ " 'identity_attack',\n",
1294
+ " 'sexually_explicit'\n",
1295
+ " ]\n",
1296
+ "\n",
1297
+ " df['annotators_id'] = df['annotators_id'].apply(lambda x: ast.literal_eval(x))\n",
1298
+ " df_exploded = df.explode('annotators_id')\n",
1299
+ " df_exploded.rename(columns={\n",
1300
+ " 'annotators_id': 'annotator_id'\n",
1301
+ " }, inplace=True)\n",
1302
+ " merged_df = df_exploded.merge(annotator_df, on=\"annotator_id\", how=\"inner\")\n",
1303
+ " merged_df['text_id_index'] = merged_df.groupby('text_id').cumcount()\n",
1304
+ " merged_df['text_id_index'] = merged_df['text_id_index'].astype(int)\n",
1305
+ " for col in columns:\n",
1306
+ " merged_df[col] = merged_df[col].apply(lambda x: ast.literal_eval(x))\n",
1307
+ " merged_df[col] = merged_df.apply(lambda row: row[col][row['text_id_index']], axis=1)\n",
1308
+ "\n",
1309
+ " return merged_df\n",
1310
+ "\n",
1311
+ "def polarity_text_handler(merged_df, method: str = \"agg\", language: str = \"id\"):\n",
1312
+ " \"\"\"\n",
1313
+ " Handles toxic and non-toxic text datasets for toxicity classification, \n",
1314
+ " applying polarization processing and text formatting.\n",
1315
+ "\n",
1316
+ " Method options:\n",
1317
+ " 1. agg = Aggregate value with a range of [0, 1].\n",
1318
+ " 2. bin = Binarized, values of either 0 or 1 (values of 0.5 converted to 0).\n",
1319
+ " 3. bin-ceil = Binarized, but values of 0.5 converted to 1.\n",
1320
+ " 4. any = Binarized, any value above 0 is converted to 1.\n",
1321
+ "\n",
1322
+ " Language options:\n",
1323
+ " 1. id = Indonesian.\n",
1324
+ " 2. en = English.\n",
1325
+ " \"\"\"\n",
1326
+ " def process_polarized_values(row, method):\n",
1327
+ " \"\"\"Processes the polarization values according to the selected method.\"\"\"\n",
1328
+ " values = ast.literal_eval(row['polarized']) if isinstance(row['polarized'], str) else row['polarized']\n",
1329
+ " values = [int(x) for x in values]\n",
1330
+ " if not values:\n",
1331
+ " return 0 # Default for missing or empty polarization\n",
1332
+ " \n",
1333
+ " agg_value = sum(values) / len(values)\n",
1334
+ " if method == \"agg\":\n",
1335
+ " return agg_value\n",
1336
+ " elif method == \"bin\":\n",
1337
+ " return 1 if agg_value > 0.5 else 0\n",
1338
+ " elif method == \"bin-ceil\":\n",
1339
+ " return 1 if agg_value >= 0.5 else 0\n",
1340
+ " elif method == \"any\":\n",
1341
+ " return 1 if agg_value > 0 else 0\n",
1342
+ " else:\n",
1343
+ " raise ValueError(f\"Unsupported method: {method}\")\n",
1344
+ "\n",
1345
+ " merged_df['polarized'] = merged_df['polarized'].fillna(0)\n",
1346
+ " merged_df['polarized_value'] = merged_df.apply(lambda row: process_polarized_values(row, method), axis=1)\n",
1347
+ "\n",
1348
+ " # Format text based on language and add polarization\n",
1349
+ " def format_text(row, language):\n",
1350
+ " if language == \"id\":\n",
1351
+ " return f\"Nilai polarisasi rata-rata (rentang 0 hingga 1): {row['polarized_value']}\"\n",
1352
+ " elif language == \"en\":\n",
1353
+ " return f\"Average polarization value (range of 0 to 1): {row['polarized_value']}\"\n",
1354
+ " else:\n",
1355
+ " raise ValueError(f\"Unsupported language: {language}\")\n",
1356
+ "\n",
1357
+ " merged_df['combined_text'] = merged_df.apply(lambda row: format_text(row, language), axis=1)\n",
1358
+ "\n",
1359
+ " # Prepare outputs\n",
1360
+ " texts = merged_df['combined_text'].tolist()\n",
1361
+ " labels = merged_df['label'].tolist()\n",
1362
+ "\n",
1363
+ " return merged_df, texts, labels\n",
1364
+ "\n",
1365
+ "\n",
1366
+ "def exploded_df_train_baseline_bert_pipeline_with_polarization_and_demographic_feature(model_path: str, \n",
1367
+ " merged_df, \n",
1368
+ " output_dir: str,\n",
1369
+ " demographic: List[str] = [], \n",
1370
+ " method: str = \"agg\",\n",
1371
+ " language: str = \"id\",\n",
1372
+ " raw_test: bool = False):\n",
1373
+ " # Handle texts and labels\n",
1374
+ " original_df, texts, labels = polarity_text_handler(merged_df, method, language) # Just using this to ensure replicability with old baseline\n",
1375
+ "\n",
1376
+ " # Create output directory\n",
1377
+ " os.makedirs(output_dir, exist_ok=True)\n",
1378
+ "\n",
1379
+ " skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
1380
+ " metrics_list = []\n",
1381
+ "\n",
1382
+ " for fold, (train_index, test_index) in enumerate(skf.split(texts, labels)):\n",
1383
+ " train_df = original_df.iloc[train_index]\n",
1384
+ " test_df = original_df.iloc[test_index]\n",
1385
+ "\n",
1386
+ " train_df = process_and_explode(train_df)\n",
1387
+ " test_df = process_and_explode(test_df)\n",
1388
+ "\n",
1389
+ " train_texts, train_labels = single_level_toxicity_and_demographic_text_handler(train_df, demographic, language)\n",
1390
+ " test_texts, test_labels = single_level_toxicity_and_demographic_text_handler(test_df, demographic, language)\n",
1391
+ " \n",
1392
+ " if raw_test:\n",
1393
+ " test_texts = [text.split('[SEP]')[-1].strip() for text in test_texts]\n",
1394
+ "\n",
1395
+ " train_labels = [int(x) for x in train_labels]\n",
1396
+ " test_labels = [int(x) for x in test_labels]\n",
1397
+ "\n",
1398
+ " # Tokenize\n",
1399
+ " tokenizer = BertTokenizer.from_pretrained(model_path)\n",
1400
+ " train_encodings = tokenizer(list(train_texts), truncation=True, padding=True, max_length=512, return_tensors='pt')\n",
1401
+ " test_encodings = tokenizer(list(test_texts), truncation=True, padding=True, max_length=512, return_tensors='pt')\n",
1402
+ "\n",
1403
+ " train_dataset = Dataset(train_encodings, train_labels)\n",
1404
+ " test_dataset = Dataset(test_encodings, test_labels)\n",
1405
+ "\n",
1406
+ " model = BertForSequenceClassification.from_pretrained(model_path, num_labels=len(set(train_labels)))\n",
1407
+ "\n",
1408
+ " training_args = TrainingArguments(\n",
1409
+ " output_dir=os.path.join(output_dir, f\"temp_model_fold_{fold}\"), # Temporary directory for Trainer\n",
1410
+ " evaluation_strategy=\"epoch\",\n",
1411
+ " per_device_train_batch_size=16,\n",
1412
+ " per_device_eval_batch_size=64,\n",
1413
+ " num_train_epochs=3,\n",
1414
+ " logging_dir=os.path.join(output_dir, f\"logs_fold_{fold}\"),\n",
1415
+ " save_strategy=\"no\", # Prevent model saving during fold training\n",
1416
+ " )\n",
1417
+ "\n",
1418
+ " trainer = Trainer(\n",
1419
+ " model=model,\n",
1420
+ " args=training_args,\n",
1421
+ " train_dataset=train_dataset,\n",
1422
+ " eval_dataset=test_dataset,\n",
1423
+ " compute_metrics=compute_metrics,\n",
1424
+ " )\n",
1425
+ "\n",
1426
+ " # Train and evaluate\n",
1427
+ " trainer.train()\n",
1428
+ " metrics = trainer.evaluate()\n",
1429
+ " metrics_list.append(metrics)\n",
1430
+ "\n",
1431
+ " # Save performance report\n",
1432
+ " pd.DataFrame([metrics]).to_csv(os.path.join(output_dir, f\"performance_fold_{fold}.csv\"), index=False)\n",
1433
+ "\n",
1434
+ " # Calculate average performance metrics\n",
1435
+ " avg_metrics = {metric: np.mean([m[metric] for m in metrics_list]) for metric in metrics_list[0]}\n",
1436
+ " pd.DataFrame([avg_metrics]).to_csv(os.path.join(output_dir, \"average_performance.csv\"), index=False)\n",
1437
+ "\n",
1438
+ "# Dataset class to handle encoding\n",
1439
+ "class Dataset(torch.utils.data.Dataset):\n",
1440
+ " def __init__(self, encodings, labels):\n",
1441
+ " self.encodings = encodings\n",
1442
+ " self.labels = [int(label) for label in labels] \n",
1443
+ "\n",
1444
+ " def __getitem__(self, idx):\n",
1445
+ " item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}\n",
1446
+ " item['labels'] = torch.tensor(self.labels[idx])\n",
1447
+ " return item\n",
1448
+ "\n",
1449
+ " def __len__(self):\n",
1450
+ " return len(self.labels)"
1451
+ ]
1452
+ }
1453
+ ],
1454
+ "metadata": {
1455
+ "kernelspec": {
1456
+ "display_name": "Python 3 (ipykernel)",
1457
+ "language": "python",
1458
+ "name": "python3"
1459
+ },
1460
+ "language_info": {
1461
+ "codemirror_mode": {
1462
+ "name": "ipython",
1463
+ "version": 3
1464
+ },
1465
+ "file_extension": ".py",
1466
+ "mimetype": "text/x-python",
1467
+ "name": "python",
1468
+ "nbconvert_exporter": "python",
1469
+ "pygments_lexer": "ipython3",
1470
+ "version": "3.12.4"
1471
+ }
1472
+ },
1473
+ "nbformat": 4,
1474
+ "nbformat_minor": 5
1475
+ }