Spaces:
Running
Running
JKJanosko
commited on
Commit
•
66cc6bb
1
Parent(s):
8565f82
Add files via upload
Browse files- milestone-3/toxicityclassification.ipynb +422 -356
milestone-3/toxicityclassification.ipynb
CHANGED
@@ -1,367 +1,433 @@
|
|
1 |
{
|
2 |
-
|
3 |
-
{
|
4 |
-
"cell_type": "code",
|
5 |
-
"execution_count": 1,
|
6 |
-
"metadata": {},
|
7 |
-
"outputs": [],
|
8 |
-
"source": [
|
9 |
-
"import pandas as pd\n",
|
10 |
-
"import numpy as np\n",
|
11 |
-
"\n",
|
12 |
-
"train_data=pd.read_csv(\"data/train.csv\", engine=\"python\")"
|
13 |
-
]
|
14 |
-
},
|
15 |
-
{
|
16 |
-
"cell_type": "code",
|
17 |
-
"execution_count": 2,
|
18 |
-
"metadata": {},
|
19 |
-
"outputs": [],
|
20 |
-
"source": [
|
21 |
-
"attributes=[\"toxic\",\"severe_toxic\",\"obscene\",\"threat\",\"insult\",\"identity_hate\"]\n",
|
22 |
-
"#train_data[attributes].sum().plot.bar()"
|
23 |
-
]
|
24 |
-
},
|
25 |
-
{
|
26 |
-
"cell_type": "code",
|
27 |
-
"execution_count": 3,
|
28 |
-
"metadata": {},
|
29 |
-
"outputs": [],
|
30 |
-
"source": [
|
31 |
-
"from torch.utils.data import Dataset\n",
|
32 |
-
"import torch\n",
|
33 |
-
"\n",
|
34 |
-
"class toxicity_dataset(Dataset):\n",
|
35 |
-
" def __init__(self,data_path,tokenizer,attributes,max_token_len= 128,sample = 5000):\n",
|
36 |
-
" self.data_path=data_path\n",
|
37 |
-
" self.tokenizer=tokenizer\n",
|
38 |
-
" self.attributes=attributes\n",
|
39 |
-
" self.max_token_len=max_token_len\n",
|
40 |
-
" self.sample=sample\n",
|
41 |
-
" self._prepare_data()\n",
|
42 |
-
" def _prepare_data(self):\n",
|
43 |
-
" data=pd.read_csv(self.data_path)\n",
|
44 |
-
" if self.sample is not None:\n",
|
45 |
-
" self.data=data.sample(self.sample,random_state=7)\n",
|
46 |
-
" else:\n",
|
47 |
-
" self.data=data\n",
|
48 |
-
" def __len__(self):\n",
|
49 |
-
" return(len(self.data))\n",
|
50 |
-
" def __getitem__(self,index):\n",
|
51 |
-
" item = self.data.iloc[index]\n",
|
52 |
-
" comment = str(item.comment_text)\n",
|
53 |
-
" attributes = torch.FloatTensor(item[self.attributes])\n",
|
54 |
-
" tokens = self.tokenizer.encode_plus(comment,add_special_tokens=True,return_tensors=\"pt\",truncation=True,max_length=self.max_token_len,padding=\"max_length\",return_attention_mask=True)\n",
|
55 |
-
" return{'input_ids':tokens.input_ids.flatten(),\"attention_mask\":tokens.attention_mask.flatten(),\"labels\":attributes}\n"
|
56 |
-
]
|
57 |
-
},
|
58 |
-
{
|
59 |
-
"cell_type": "code",
|
60 |
-
"execution_count": 4,
|
61 |
-
"metadata": {},
|
62 |
-
"outputs": [
|
63 |
{
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
"
|
69 |
-
|
|
|
70 |
},
|
71 |
{
|
72 |
-
|
73 |
-
"
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
" 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
|
83 |
-
" 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
|
84 |
-
" 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
|
85 |
-
" 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
|
86 |
-
" 1, 1, 1, 1, 1, 1, 1, 1]),\n",
|
87 |
-
" 'attention_mask': tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
|
88 |
-
" 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
|
89 |
-
" 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,\n",
|
90 |
-
" 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
|
91 |
-
" 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
|
92 |
-
" 0, 0, 0, 0, 0, 0, 0, 0]),\n",
|
93 |
-
" 'labels': tensor([0., 0., 0., 0., 0., 0.])}"
|
94 |
]
|
95 |
-
|
96 |
-
"execution_count": 4,
|
97 |
-
"metadata": {},
|
98 |
-
"output_type": "execute_result"
|
99 |
-
}
|
100 |
-
],
|
101 |
-
"source": [
|
102 |
-
"from transformers import AutoTokenizer\n",
|
103 |
-
"model_name=\"roberta-base\"\n",
|
104 |
-
"tokenizer=AutoTokenizer.from_pretrained(model_name)\n",
|
105 |
-
"toxic_comments_dataset=toxicity_dataset(\"data/train.csv\",tokenizer,attributes)\n",
|
106 |
-
"toxic_comments_dataset.__getitem__(0)\n"
|
107 |
-
]
|
108 |
-
},
|
109 |
-
{
|
110 |
-
"cell_type": "code",
|
111 |
-
"execution_count": 5,
|
112 |
-
"metadata": {},
|
113 |
-
"outputs": [],
|
114 |
-
"source": [
|
115 |
-
"import pytorch_lightning as pl\n",
|
116 |
-
"from torch.utils.data import DataLoader"
|
117 |
-
]
|
118 |
-
},
|
119 |
-
{
|
120 |
-
"cell_type": "code",
|
121 |
-
"execution_count": 6,
|
122 |
-
"metadata": {},
|
123 |
-
"outputs": [],
|
124 |
-
"source": [
|
125 |
-
"class Toxcity_Data_Module(pl.LightningDataModule):\n",
|
126 |
-
" def __init__(self,train_path,test_path,attributes,batch_size = 16, max_token_len = 128, model_name=\"roberta-base\"):\n",
|
127 |
-
" super().__init__()\n",
|
128 |
-
" self.train_path=train_path\n",
|
129 |
-
" self.test_path=test_path\n",
|
130 |
-
" self.attributes=attributes\n",
|
131 |
-
" self.batch_size=batch_size\n",
|
132 |
-
" self.max_token_len=max_token_len\n",
|
133 |
-
" self.model_name=model_name\n",
|
134 |
-
" self.tokenizer = AutoTokenizer.from_pretrained(model_name)\n",
|
135 |
-
" def setup(self, stage = None):\n",
|
136 |
-
" if stage in (None, \"fit\"):\n",
|
137 |
-
" self.train_dataset=toxicity_dataset(self.train_path,self.tokenizer,self.attributes)\n",
|
138 |
-
" self.test_dataset=toxicity_dataset(self.test_path,self.tokenizer,self.attributes, sample=None)\n",
|
139 |
-
" if stage == \"predict\":\n",
|
140 |
-
" self.val_dataset=toxicity_dataset(self.test_path,self.tokenizer,self.attributes)\n",
|
141 |
-
" def train_dataloader(self):\n",
|
142 |
-
" return DataLoader(self.train_dataset,batch_size=self.batch_size,num_workers=4,shuffle=True)\n",
|
143 |
-
" def val_dataloader(self):\n",
|
144 |
-
" return DataLoader(self.test_dataset,batch_size=self.batch_size,num_workers=4,shuffle=False)\n",
|
145 |
-
" def predict_dataloader(self):\n",
|
146 |
-
" return DataLoader(self.test_dataset,batch_size=self.batch_size,num_workers=4,shuffle=False)\n",
|
147 |
-
" "
|
148 |
-
]
|
149 |
-
},
|
150 |
-
{
|
151 |
-
"cell_type": "code",
|
152 |
-
"execution_count": 7,
|
153 |
-
"metadata": {},
|
154 |
-
"outputs": [
|
155 |
{
|
156 |
-
|
157 |
-
"
|
158 |
-
|
|
|
|
|
|
|
159 |
]
|
160 |
-
|
161 |
-
"execution_count": 7,
|
162 |
-
"metadata": {},
|
163 |
-
"output_type": "execute_result"
|
164 |
-
}
|
165 |
-
],
|
166 |
-
"source": [
|
167 |
-
"toxicity_data_module=Toxcity_Data_Module(\"data/train.csv\",\"data/test.csv\",attributes)\n",
|
168 |
-
"\n",
|
169 |
-
"toxicity_data_module.setup()\n",
|
170 |
-
"dataloader=toxicity_data_module.train_dataloader()\n",
|
171 |
-
"dataloader"
|
172 |
-
]
|
173 |
-
},
|
174 |
-
{
|
175 |
-
"cell_type": "code",
|
176 |
-
"execution_count": 8,
|
177 |
-
"metadata": {},
|
178 |
-
"outputs": [],
|
179 |
-
"source": [
|
180 |
-
"from transformers import AutoModel, AdamW, get_cosine_schedule_with_warmup\n",
|
181 |
-
"import torch.nn as nn\n",
|
182 |
-
"import math\n",
|
183 |
-
"from torchmetrics.functional.classification import auroc\n",
|
184 |
-
"import torch.nn.functional as F"
|
185 |
-
]
|
186 |
-
},
|
187 |
-
{
|
188 |
-
"cell_type": "code",
|
189 |
-
"execution_count": 9,
|
190 |
-
"metadata": {},
|
191 |
-
"outputs": [],
|
192 |
-
"source": [
|
193 |
-
"class Toxic_Comment_Classifier(pl.LightningModule):\n",
|
194 |
-
" def __init__(self,config:dict):\n",
|
195 |
-
" super().__init__()\n",
|
196 |
-
" self.config=config\n",
|
197 |
-
" self.pretrained_model = AutoModel.from_pretrained(config['model_name'],return_dict=True)\n",
|
198 |
-
" self.hidden = nn.Linear(self.pretrained_model.config.hidden_size, self.pretrained_model.config.hidden_size)\n",
|
199 |
-
" self.classifier = nn.Linear(self.pretrained_model.config.hidden_size, self.config['n_labels'])\n",
|
200 |
-
" torch.nn.init.xavier_uniform_(self.hidden.weight)\n",
|
201 |
-
" torch.nn.init.xavier_uniform_(self.classifier.weight)\n",
|
202 |
-
" self.loss_func=nn.BCEWithLogitsLoss(reduction='mean')\n",
|
203 |
-
" self.dropout = nn.Dropout()\n",
|
204 |
-
"\n",
|
205 |
-
" def forward(self, input_ids,attention_mask,labels=None):\n",
|
206 |
-
" output = self.pretrained_model(input_ids=input_ids,attention_mask=attention_mask)\n",
|
207 |
-
" pooled_output=torch.mean(output.last_hidden_state, 1)\n",
|
208 |
-
" #nn classification\n",
|
209 |
-
" pooled_output=self.hidden(pooled_output)\n",
|
210 |
-
" pooled_output=self.dropout(pooled_output)\n",
|
211 |
-
" pooled_output=F.relu(pooled_output)\n",
|
212 |
-
" logits=self.classifier(pooled_output)\n",
|
213 |
-
" #loss\n",
|
214 |
-
" loss = 0\n",
|
215 |
-
" if labels is not None:\n",
|
216 |
-
" loss = self.loss_func(logits.view(-1,self.config['n_labels']), labels.view(-1,self.config['n_labels']))\n",
|
217 |
-
" return loss, logits\n",
|
218 |
-
" \n",
|
219 |
-
" def training_step(self, batch, batch_index):\n",
|
220 |
-
" loss, logits = self(**batch)\n",
|
221 |
-
" self.log(\"train loss\", loss, prog_bar=True, logger=True)\n",
|
222 |
-
" return{'loss':loss,'predictions':logits,'labels':batch['labels']}\n",
|
223 |
-
" def validation_step(self, batch, batch_index):\n",
|
224 |
-
" loss, logits = self(**batch)\n",
|
225 |
-
" self.log(\"validation loss\", loss, prog_bar=True, logger=True)\n",
|
226 |
-
" return{'val_loss':loss,'predictions':logits,'labels':batch['labels']}\n",
|
227 |
-
" def prediction_step(self, batch, batch_index):\n",
|
228 |
-
" logits = self(**batch)\n",
|
229 |
-
" return logits\n",
|
230 |
-
" \n",
|
231 |
-
" def configure_optimizers(self):\n",
|
232 |
-
" optimizer = AdamW(self.parameters(), lr=self.config['lr'], weight_decay=self.config['w_decay'])\n",
|
233 |
-
" total_steps = self.config['train_size']/self.config['bs']\n",
|
234 |
-
" warmup_steps = math.floor(total_steps*self.config['warmup'])\n",
|
235 |
-
" scheduler = get_cosine_schedule_with_warmup(optimizer,warmup_steps,total_steps)\n",
|
236 |
-
" return [optimizer],[scheduler]"
|
237 |
-
]
|
238 |
-
},
|
239 |
-
{
|
240 |
-
"cell_type": "code",
|
241 |
-
"execution_count": 10,
|
242 |
-
"metadata": {},
|
243 |
-
"outputs": [
|
244 |
{
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
"
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
287 |
{
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
"
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
"
|
298 |
-
"
|
299 |
-
"
|
300 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
301 |
}
|
302 |
-
],
|
303 |
-
"source": [
|
304 |
-
"toxicity_data_module=Toxcity_Data_Module(\"data/train.csv\",\"data/test.csv\",attributes,batch_size=config['bs'])\n",
|
305 |
-
"toxicity_data_module.setup()\n",
|
306 |
-
"model = Toxic_Comment_Classifier(config)\n",
|
307 |
-
"\n",
|
308 |
-
"trainer = pl.Trainer(max_epochs=config['n_epochs'],num_sanity_val_steps=50)\n",
|
309 |
-
"#device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
310 |
-
"#print(torch.cuda.get_device_name())\n",
|
311 |
-
"#trainer.fit(model,toxicity_data_module)"
|
312 |
-
]
|
313 |
-
},
|
314 |
-
{
|
315 |
-
"cell_type": "code",
|
316 |
-
"execution_count": 13,
|
317 |
-
"metadata": {},
|
318 |
-
"outputs": [],
|
319 |
-
"source": [
|
320 |
-
"model = torch.load(\"ToxicityClassificationModel.pt\")"
|
321 |
-
]
|
322 |
-
},
|
323 |
-
{
|
324 |
-
"cell_type": "code",
|
325 |
-
"execution_count": 14,
|
326 |
-
"metadata": {},
|
327 |
-
"outputs": [],
|
328 |
-
"source": [
|
329 |
-
"def predict_raw_comments(model, dm):\n",
|
330 |
-
" predictions = trainer.predict(model,datamodule=dm)\n",
|
331 |
-
" flattened_predictions = np.stack([torch.sigmoid(torch.Tensor(p)) for batch in predictions for p in batch])\n",
|
332 |
-
" return flattened_predictions"
|
333 |
-
]
|
334 |
-
},
|
335 |
-
{
|
336 |
-
"cell_type": "code",
|
337 |
-
"execution_count": 15,
|
338 |
-
"metadata": {},
|
339 |
-
"outputs": [],
|
340 |
-
"source": [
|
341 |
-
"predictions = predict_raw_comments(model=model,dm=toxicity_data_module)"
|
342 |
-
]
|
343 |
-
}
|
344 |
-
],
|
345 |
-
"metadata": {
|
346 |
-
"kernelspec": {
|
347 |
-
"display_name": "Python 3",
|
348 |
-
"language": "python",
|
349 |
-
"name": "python3"
|
350 |
-
},
|
351 |
-
"language_info": {
|
352 |
-
"codemirror_mode": {
|
353 |
-
"name": "ipython",
|
354 |
-
"version": 3
|
355 |
-
},
|
356 |
-
"file_extension": ".py",
|
357 |
-
"mimetype": "text/x-python",
|
358 |
-
"name": "python",
|
359 |
-
"nbconvert_exporter": "python",
|
360 |
-
"pygments_lexer": "ipython3",
|
361 |
-
"version": "3.11.3"
|
362 |
},
|
363 |
-
"
|
364 |
-
|
365 |
-
|
366 |
-
"nbformat_minor": 2
|
367 |
-
}
|
|
|
1 |
{
|
2 |
+
"cells": [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
{
|
4 |
+
"cell_type": "markdown",
|
5 |
+
"metadata": {
|
6 |
+
"id": "eUS7fBrdXj9A"
|
7 |
+
},
|
8 |
+
"source": [
|
9 |
+
"Ensures that Transformers and pytorch_lightning libraries are installed in the runtime."
|
10 |
+
]
|
11 |
},
|
12 |
{
|
13 |
+
"cell_type": "code",
|
14 |
+
"execution_count": 2,
|
15 |
+
"metadata": {
|
16 |
+
"id": "LF6cf_ijDNhp"
|
17 |
+
},
|
18 |
+
"outputs": [],
|
19 |
+
"source": [
|
20 |
+
"%%capture\n",
|
21 |
+
"%pip install transformers\n",
|
22 |
+
"%pip install pytorch_lightning\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
]
|
24 |
+
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
{
|
26 |
+
"cell_type": "markdown",
|
27 |
+
"metadata": {
|
28 |
+
"id": "pf4Ch2xaXszi"
|
29 |
+
},
|
30 |
+
"source": [
|
31 |
+
"Imports everything needed for creating the model"
|
32 |
]
|
33 |
+
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
{
|
35 |
+
"cell_type": "code",
|
36 |
+
"execution_count": 3,
|
37 |
+
"metadata": {
|
38 |
+
"id": "pmd3-0J4_rnp"
|
39 |
+
},
|
40 |
+
"outputs": [],
|
41 |
+
"source": [
|
42 |
+
"import pandas as pd\n",
|
43 |
+
"import numpy as np\n",
|
44 |
+
"from torch.utils.data import Dataset\n",
|
45 |
+
"import torch\n",
|
46 |
+
"from transformers import AutoTokenizer\n",
|
47 |
+
"import pytorch_lightning as pl\n",
|
48 |
+
"from torch.utils.data import DataLoader\n",
|
49 |
+
"from transformers import AutoModel, AdamW, get_cosine_schedule_with_warmup\n",
|
50 |
+
"import torch.nn as nn\n",
|
51 |
+
"import math\n",
|
52 |
+
"from torchmetrics.functional.classification import auroc\n",
|
53 |
+
"import torch.nn.functional as F\n",
|
54 |
+
"from transformers import BertForMaskedLM, TFBertForMaskedLM"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "markdown",
|
59 |
+
"metadata": {
|
60 |
+
"id": "EyhmDzknX2k8"
|
61 |
+
},
|
62 |
+
"source": [
|
63 |
+
"Defines class toxicity_dataset, which extends Dataset. __init__ takes a path to the csv file, a tokenizer, a list of attributes, a maximum length for the token which defaults to 128, and a size for sampling the data which defaults to 5000.\n",
|
64 |
+
"\n",
|
65 |
+
"The toxicity_dataset class prepares the data by sampling the csv file in _prepare_data, returns the length of the dataset with __len__, and can acess an item with an index and return its input ids, its attention mask, and its labels.\n",
|
66 |
+
"\n",
|
67 |
+
"\n"
|
68 |
+
]
|
69 |
+
},
|
70 |
+
{
|
71 |
+
"cell_type": "code",
|
72 |
+
"execution_count": 4,
|
73 |
+
"metadata": {
|
74 |
+
"id": "vS6DHv5k_xZ5"
|
75 |
+
},
|
76 |
+
"outputs": [],
|
77 |
+
"source": [
|
78 |
+
"class toxicity_dataset(Dataset):\n",
|
79 |
+
" def __init__(self,data_path,tokenizer,attributes,max_token_len= 128,sample = 5000):\n",
|
80 |
+
" self.data_path=data_path\n",
|
81 |
+
" self.tokenizer=tokenizer\n",
|
82 |
+
" self.attributes=attributes\n",
|
83 |
+
" self.max_token_len=max_token_len\n",
|
84 |
+
" self.sample=sample\n",
|
85 |
+
" self._prepare_data()\n",
|
86 |
+
" def _prepare_data(self):\n",
|
87 |
+
" data=pd.read_csv(self.data_path)\n",
|
88 |
+
" if self.sample is not None:\n",
|
89 |
+
" self.data=data.sample(self.sample,random_state=7)\n",
|
90 |
+
" else:\n",
|
91 |
+
" self.data=data\n",
|
92 |
+
" def __len__(self):\n",
|
93 |
+
" return(len(self.data))\n",
|
94 |
+
" def __getitem__(self,index):\n",
|
95 |
+
" item = self.data.iloc[index]\n",
|
96 |
+
" comment = str(item.comment_text)\n",
|
97 |
+
" attributes = torch.FloatTensor(item[self.attributes])\n",
|
98 |
+
" tokens = self.tokenizer.encode_plus(comment,add_special_tokens=True,return_tensors=\"pt\",truncation=True,max_length=self.max_token_len,padding=\"max_length\",return_attention_mask=True)\n",
|
99 |
+
" return{'input_ids':tokens.input_ids.flatten(),\"attention_mask\":tokens.attention_mask.flatten(),\"labels\":attributes}\n"
|
100 |
+
]
|
101 |
+
},
|
102 |
{
|
103 |
+
"cell_type": "markdown",
|
104 |
+
"metadata": {
|
105 |
+
"id": "w-Kmud4YZXH2"
|
106 |
+
},
|
107 |
+
"source": [
|
108 |
+
"Defines Toxicity_Data_Module, which extends pytorch_lightnign.LightningDataModule.__init__ takes a path to the training data set and a testing set, a list of attributes, batch size, tax token length, and the name of the model. It has methods to create and return a dataloader for training, validation, and prediciton."
|
109 |
+
]
|
110 |
+
},
|
111 |
+
{
|
112 |
+
"cell_type": "code",
|
113 |
+
"execution_count": 5,
|
114 |
+
"metadata": {
|
115 |
+
"id": "Txrjrl1d_6UN"
|
116 |
+
},
|
117 |
+
"outputs": [],
|
118 |
+
"source": [
|
119 |
+
"class Toxcity_Data_Module(pl.LightningDataModule):\n",
|
120 |
+
" def __init__(self,train_path,test_path,attributes,batch_size = 16, max_token_len = 128, model_name=\"roberta-base\"):\n",
|
121 |
+
" super().__init__()\n",
|
122 |
+
" self.train_path=train_path\n",
|
123 |
+
" self.test_path=test_path\n",
|
124 |
+
" self.attributes=attributes\n",
|
125 |
+
" self.batch_size=batch_size\n",
|
126 |
+
" self.max_token_len=max_token_len\n",
|
127 |
+
" self.model_name=model_name\n",
|
128 |
+
" self.tokenizer = AutoTokenizer.from_pretrained(model_name)\n",
|
129 |
+
" def setup(self, stage = None):\n",
|
130 |
+
" if stage in (None, \"fit\"):\n",
|
131 |
+
" self.train_dataset=toxicity_dataset(self.train_path,self.tokenizer,self.attributes)\n",
|
132 |
+
" self.test_dataset=toxicity_dataset(self.test_path,self.tokenizer,self.attributes, sample=None)\n",
|
133 |
+
" if stage == \"predict\":\n",
|
134 |
+
" self.val_dataset=toxicity_dataset(self.test_path,self.tokenizer,self.attributes)\n",
|
135 |
+
" def train_dataloader(self):\n",
|
136 |
+
" return DataLoader(self.train_dataset,batch_size=self.batch_size,shuffle=True, num_workers=12)\n",
|
137 |
+
" def val_dataloader(self):\n",
|
138 |
+
" return DataLoader(self.train_dataset,batch_size=self.batch_size,shuffle=False, num_workers=12)\n",
|
139 |
+
" def predict_dataloader(self):\n",
|
140 |
+
" return DataLoader(self.test_dataset,batch_size=self.batch_size,shuffle=False, num_workers=12)\n",
|
141 |
+
" "
|
142 |
+
]
|
143 |
+
},
|
144 |
+
{
|
145 |
+
"cell_type": "markdown",
|
146 |
+
"source": [
|
147 |
+
"Defines Toxic_Comment_Classifier, which is the actual model we are fine tuning, and extends pl.LightningModule. __init__ takes a dictionary storing model name, number of labels, batch size, learning rate, warmup, the size of the training set, weighted decay, and number of epochs. It's methods are never called explicitly in the code, and the class is instead used by a pytorch_lightning Trainer object."
|
148 |
+
],
|
149 |
+
"metadata": {
|
150 |
+
"id": "2XqQMdp1YahZ"
|
151 |
+
}
|
152 |
+
},
|
153 |
+
{
|
154 |
+
"cell_type": "code",
|
155 |
+
"execution_count": 6,
|
156 |
+
"metadata": {
|
157 |
+
"id": "7AhJvpKyADHJ"
|
158 |
+
},
|
159 |
+
"outputs": [],
|
160 |
+
"source": [
|
161 |
+
"class Toxic_Comment_Classifier(pl.LightningModule):\n",
|
162 |
+
" def __init__(self, config: dict):\n",
|
163 |
+
" super().__init__()\n",
|
164 |
+
" self.config = config\n",
|
165 |
+
" self.pretrained_model = AutoModel.from_pretrained(config['model_name'], return_dict = True)\n",
|
166 |
+
" self.hidden = torch.nn.Linear(self.pretrained_model.config.hidden_size, self.pretrained_model.config.hidden_size)\n",
|
167 |
+
" self.classifier = torch.nn.Linear(self.pretrained_model.config.hidden_size, self.config['n_labels'])\n",
|
168 |
+
" torch.nn.init.xavier_uniform_(self.classifier.weight)\n",
|
169 |
+
" self.loss_func = nn.BCEWithLogitsLoss(reduction='mean')\n",
|
170 |
+
" self.dropout = nn.Dropout()\n",
|
171 |
+
" \n",
|
172 |
+
" def forward(self, input_ids, attention_mask=None, labels=None):\n",
|
173 |
+
" # roberta layer\n",
|
174 |
+
" output = self.pretrained_model(input_ids=input_ids, attention_mask=attention_mask)\n",
|
175 |
+
" pooled_output = torch.mean(output.last_hidden_state, 1)\n",
|
176 |
+
" # final logits\n",
|
177 |
+
" pooled_output = self.dropout(pooled_output)\n",
|
178 |
+
" pooled_output = self.hidden(pooled_output)\n",
|
179 |
+
" pooled_output = F.relu(pooled_output)\n",
|
180 |
+
" pooled_output = self.dropout(pooled_output)\n",
|
181 |
+
" logits = self.classifier(pooled_output)\n",
|
182 |
+
" # calculate loss\n",
|
183 |
+
" loss = 0\n",
|
184 |
+
" if labels is not None:\n",
|
185 |
+
" loss = self.loss_func(logits.view(-1, self.config['n_labels']), labels.view(-1, self.config['n_labels']))\n",
|
186 |
+
" return loss, logits\n",
|
187 |
+
"\n",
|
188 |
+
" def training_step(self, batch, batch_index):\n",
|
189 |
+
" loss, outputs = self(**batch)\n",
|
190 |
+
" self.log(\"train loss \", loss, prog_bar = True, logger=True)\n",
|
191 |
+
" return {\"loss\":loss, \"predictions\":outputs, \"labels\": batch[\"labels\"]}\n",
|
192 |
+
"\n",
|
193 |
+
" def validation_step(self, batch, batch_index):\n",
|
194 |
+
" loss, outputs = self(**batch)\n",
|
195 |
+
" self.log(\"validation loss \", loss, prog_bar = True, logger=True)\n",
|
196 |
+
" return {\"val_loss\": loss, \"predictions\":outputs, \"labels\": batch[\"labels\"]}\n",
|
197 |
+
"\n",
|
198 |
+
" def predict_step(self, batch, batch_index):\n",
|
199 |
+
" loss, outputs = self(**batch)\n",
|
200 |
+
" return outputs\n",
|
201 |
+
"\n",
|
202 |
+
" def configure_optimizers(self):\n",
|
203 |
+
" optimizer = AdamW(self.parameters(), lr=self.config['lr'], weight_decay=self.config['w_decay'])\n",
|
204 |
+
" total_steps = self.config['train_size']/self.config['bs']\n",
|
205 |
+
" warmup_steps = math.floor(total_steps * self.config['warmup'])\n",
|
206 |
+
" warmup_steps = math.floor(total_steps * self.config['warmup'])\n",
|
207 |
+
" scheduler = get_cosine_schedule_with_warmup(optimizer, warmup_steps, total_steps)\n",
|
208 |
+
" return [optimizer],[scheduler]"
|
209 |
+
]
|
210 |
+
},
|
211 |
+
{
|
212 |
+
"cell_type": "markdown",
|
213 |
+
"source": [
|
214 |
+
"The variable, attributes, stores the list of labels used to classify the comments. toxicity_data_module is created and setup for later use."
|
215 |
+
],
|
216 |
+
"metadata": {
|
217 |
+
"id": "CRZVlU89boV5"
|
218 |
+
}
|
219 |
+
},
|
220 |
+
{
|
221 |
+
"cell_type": "code",
|
222 |
+
"execution_count": null,
|
223 |
+
"metadata": {
|
224 |
+
"id": "VQwXmUnn_-co"
|
225 |
+
},
|
226 |
+
"outputs": [],
|
227 |
+
"source": [
|
228 |
+
"attributes=[\"toxic\",\"severe_toxic\",\"obscene\",\"threat\",\"insult\",\"identity_hate\"]\n",
|
229 |
+
"\n",
|
230 |
+
"toxicity_data_module=Toxcity_Data_Module(\"/content/sample_data/train.csv\",\"/content/sample_data/train.csv\",attributes)\n",
|
231 |
+
"toxicity_data_module.setup()"
|
232 |
+
]
|
233 |
+
},
|
234 |
+
{
|
235 |
+
"cell_type": "markdown",
|
236 |
+
"source": [
|
237 |
+
"Here, we define the config dictionary. the model we are fine tuning is the distilroberta-base model. We use attributes to get the number of labels. the batch size is 128, the learning rate is 0.0000015, and we're using 80 epochs for training."
|
238 |
+
],
|
239 |
+
"metadata": {
|
240 |
+
"id": "OTumKddHb6wB"
|
241 |
+
}
|
242 |
+
},
|
243 |
+
{
|
244 |
+
"cell_type": "code",
|
245 |
+
"execution_count": null,
|
246 |
+
"metadata": {
|
247 |
+
"id": "Q77QTZpUAFAS"
|
248 |
+
},
|
249 |
+
"outputs": [],
|
250 |
+
"source": [
|
251 |
+
"config = {\n",
|
252 |
+
" 'model_name':\"distilroberta-base\",\n",
|
253 |
+
" 'n_labels':len(attributes),\n",
|
254 |
+
" 'bs':128,\n",
|
255 |
+
" 'lr':1.5e-6,\n",
|
256 |
+
" 'warmup':0.2,\n",
|
257 |
+
" \"train_size\":len(toxicity_data_module.train_dataloader()),\n",
|
258 |
+
" 'w_decay':0.001,\n",
|
259 |
+
" 'n_epochs':80\n",
|
260 |
+
"}\n"
|
261 |
+
]
|
262 |
+
},
|
263 |
+
{
|
264 |
+
"cell_type": "markdown",
|
265 |
+
"source": [
|
266 |
+
"We recreated toxicity_data_module using the batch size from the config file, and set it up again. The variable trainer is created as a pytorch_lightning.Trainer object, taking the number of epochs and a number of sanity validation steps. The trainer object then fits the model using the model we created and the data module. torch.save() is called to save the model into a file called model.pt, which can be loaded for later use. This is how the model was loaded into the streamlit app without having to retrain it by scratch."
|
267 |
+
],
|
268 |
+
"metadata": {
|
269 |
+
"id": "raqYuS_Vepj1"
|
270 |
+
}
|
271 |
+
},
|
272 |
+
{
|
273 |
+
"cell_type": "code",
|
274 |
+
"execution_count": null,
|
275 |
+
"metadata": {
|
276 |
+
"id": "Mhk8fhgFAJNJ"
|
277 |
+
},
|
278 |
+
"outputs": [],
|
279 |
+
"source": [
|
280 |
+
"toxicity_data_module=Toxcity_Data_Module(\"/content/sample_data/train.csv\",\"/content/sample_data/test.csv\",attributes,batch_size=config['bs'])\n",
|
281 |
+
"toxicity_data_module.setup()\n",
|
282 |
+
"model = Toxic_Comment_Classifier(config)\n",
|
283 |
+
"\n",
|
284 |
+
"trainer = pl.Trainer(max_epochs=config['n_epochs'],num_sanity_val_steps=50)\n",
|
285 |
+
"trainer.fit(model,toxicity_data_module)\n",
|
286 |
+
"torch.save(model, \"/content/sample_data/model.pt\")"
|
287 |
+
]
|
288 |
+
},
|
289 |
+
{
|
290 |
+
"cell_type": "markdown",
|
291 |
+
"source": [
|
292 |
+
"After all 80 epochs, the training and validatin loss are all very low, under 0.05. This shows that the model is pretty effective at determining the labels, and is not overfitting."
|
293 |
+
],
|
294 |
+
"metadata": {
|
295 |
+
"id": "pt-FyfFVqRdS"
|
296 |
+
}
|
297 |
+
},
|
298 |
+
{
|
299 |
+
"cell_type": "markdown",
|
300 |
+
"source": [
|
301 |
+
"Here we load the model file back into the model variable."
|
302 |
+
],
|
303 |
+
"metadata": {
|
304 |
+
"id": "3h4j9aqTgL1Q"
|
305 |
+
}
|
306 |
+
},
|
307 |
+
{
|
308 |
+
"cell_type": "code",
|
309 |
+
"execution_count": 11,
|
310 |
+
"metadata": {
|
311 |
+
"id": "dG_Z30QlQfSP"
|
312 |
+
},
|
313 |
+
"outputs": [],
|
314 |
+
"source": [
|
315 |
+
"model = torch.load(\"/content/sample_data/model.pt\")\n"
|
316 |
+
]
|
317 |
+
},
|
318 |
+
{
|
319 |
+
"cell_type": "markdown",
|
320 |
+
"source": [
|
321 |
+
"The function predict_raw_comments() takes the model, and the data module, and gets predictions from the trainer in the form of logits."
|
322 |
+
],
|
323 |
+
"metadata": {
|
324 |
+
"id": "WxJWKhnViQjE"
|
325 |
+
}
|
326 |
+
},
|
327 |
+
{
|
328 |
+
"cell_type": "code",
|
329 |
+
"execution_count": 12,
|
330 |
+
"metadata": {
|
331 |
+
"id": "TiXWsKFZQmQs"
|
332 |
+
},
|
333 |
+
"outputs": [],
|
334 |
+
"source": [
|
335 |
+
"def predict_raw_comments(model, dm):\n",
|
336 |
+
" predictions = trainer.predict(model,dm)\n",
|
337 |
+
" logits = np.stack([torch.sigmoid(torch.Tensor(p)) for batch in predictions for p in batch])\n",
|
338 |
+
" return logits"
|
339 |
+
]
|
340 |
+
},
|
341 |
+
{
|
342 |
+
"cell_type": "markdown",
|
343 |
+
"source": [
|
344 |
+
"Below, we use the predict_raw_comments() function to get the predicted logits."
|
345 |
+
],
|
346 |
+
"metadata": {
|
347 |
+
"id": "ihy78y__iyQL"
|
348 |
+
}
|
349 |
+
},
|
350 |
+
{
|
351 |
+
"cell_type": "code",
|
352 |
+
"execution_count": null,
|
353 |
+
"metadata": {
|
354 |
+
"id": "8ZkNo8u4Qmd7"
|
355 |
+
},
|
356 |
+
"outputs": [],
|
357 |
+
"source": [
|
358 |
+
"logits = predict_raw_comments(model,toxicity_data_module)\n"
|
359 |
+
]
|
360 |
+
},
|
361 |
+
{
|
362 |
+
"cell_type": "markdown",
|
363 |
+
"source": [
|
364 |
+
"below, we convert the numpy array of logits retrieved into torch logits using torch.from_numpy(logits). We then use a softmax function to find the softmax probabilities for each label, and convert it back into a numpy array. "
|
365 |
+
],
|
366 |
+
"metadata": {
|
367 |
+
"id": "vk7FQY7ajCUJ"
|
368 |
+
}
|
369 |
+
},
|
370 |
+
{
|
371 |
+
"cell_type": "code",
|
372 |
+
"execution_count": null,
|
373 |
+
"metadata": {
|
374 |
+
"id": "Znq6JcNS8P7Z"
|
375 |
+
},
|
376 |
+
"outputs": [],
|
377 |
+
"source": [
|
378 |
+
"torch_logits = torch.from_numpy(logits)\n",
|
379 |
+
"probabilities = F.softmax(torch_logits, dim = -1).numpy()\n"
|
380 |
+
]
|
381 |
+
},
|
382 |
+
{
|
383 |
+
"cell_type": "markdown",
|
384 |
+
"source": [
|
385 |
+
"We can then load our testing data into a dataframe, and use a nested loop to loop through both the input dataframe and the probabilities dataframe to find the label with the maximum probability. We can store the comment, the most likely labe, and the probability of that label into a new dataframe called results_df."
|
386 |
+
],
|
387 |
+
"metadata": {
|
388 |
+
"id": "S7Ixxgo5jj00"
|
389 |
+
}
|
390 |
+
},
|
391 |
+
{
|
392 |
+
"cell_type": "code",
|
393 |
+
"execution_count": null,
|
394 |
+
"metadata": {
|
395 |
+
"id": "KabNY9yrxsGn"
|
396 |
+
},
|
397 |
+
"outputs": [],
|
398 |
+
"source": [
|
399 |
+
"inputs=pd.read_csv(\"/content/sample_data/test.csv\")\n",
|
400 |
+
"data=[]\n",
|
401 |
+
"for i in range(20):\n",
|
402 |
+
" max_prob = 0\n",
|
403 |
+
" max_cat = 6\n",
|
404 |
+
" \n",
|
405 |
+
" prob=0\n",
|
406 |
+
" for j in range(6):\n",
|
407 |
+
" prob=probabilities[i][j]\n",
|
408 |
+
" if(prob >= max_prob): \n",
|
409 |
+
" max_prob = prob \n",
|
410 |
+
" max_cat = j\n",
|
411 |
+
" data.append([inputs[\"comment_text\"][i],attributes[max_cat],max_prob])\n",
|
412 |
+
"results_df=pd.DataFrame(data,columns=[\"Comment Text\",\"Most Likely Classification\",\"Classification Probability\"])"
|
413 |
+
]
|
414 |
+
}
|
415 |
+
],
|
416 |
+
"metadata": {
|
417 |
+
"accelerator": "GPU",
|
418 |
+
"colab": {
|
419 |
+
"machine_shape": "hm",
|
420 |
+
"provenance": []
|
421 |
+
},
|
422 |
+
"gpuClass": "standard",
|
423 |
+
"kernelspec": {
|
424 |
+
"display_name": "Python 3",
|
425 |
+
"name": "python3"
|
426 |
+
},
|
427 |
+
"language_info": {
|
428 |
+
"name": "python"
|
429 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
430 |
},
|
431 |
+
"nbformat": 4,
|
432 |
+
"nbformat_minor": 0
|
433 |
+
}
|
|
|
|