Kingston Yip commited on
Commit
ee73edc
1 Parent(s): 9bceaae
Files changed (1) hide show
  1. finetune_toxictweets.ipynb +0 -557
finetune_toxictweets.ipynb DELETED
@@ -1,557 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "attachments": {},
5
- "cell_type": "markdown",
6
- "metadata": {},
7
- "source": [
8
- "## Toxic Tweets Finetuning\n",
9
- "\n",
10
- "This code is run on colab and finetunes tweets according to the toxic tweets kaggle dataset"
11
- ]
12
- },
13
- {
14
- "cell_type": "code",
15
- "execution_count": null,
16
- "metadata": {
17
- "colab": {
18
- "base_uri": "https://localhost:8080/"
19
- },
20
- "id": "YQqdqC2IJ6mZ",
21
- "outputId": "0cee2ef3-14ed-4c8b-ad27-4e30d84b1c56"
22
- },
23
- "outputs": [
24
- {
25
- "name": "stdout",
26
- "output_type": "stream",
27
- "text": [
28
- "Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n",
29
- "Requirement already satisfied: transformers in /usr/local/lib/python3.9/dist-packages (4.28.1)\n",
30
- "Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.9/dist-packages (from transformers) (2022.10.31)\n",
31
- "Requirement already satisfied: requests in /usr/local/lib/python3.9/dist-packages (from transformers) (2.27.1)\n",
32
- "Requirement already satisfied: tokenizers!=0.11.3,<0.14,>=0.11.1 in /usr/local/lib/python3.9/dist-packages (from transformers) (0.13.3)\n",
33
- "Requirement already satisfied: pyyaml>=5.1 in /usr/local/lib/python3.9/dist-packages (from transformers) (6.0)\n",
34
- "Requirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.9/dist-packages (from transformers) (4.65.0)\n",
35
- "Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.9/dist-packages (from transformers) (23.1)\n",
36
- "Requirement already satisfied: huggingface-hub<1.0,>=0.11.0 in /usr/local/lib/python3.9/dist-packages (from transformers) (0.13.4)\n",
37
- "Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.9/dist-packages (from transformers) (1.22.4)\n",
38
- "Requirement already satisfied: filelock in /usr/local/lib/python3.9/dist-packages (from transformers) (3.11.0)\n",
39
- "Requirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.9/dist-packages (from huggingface-hub<1.0,>=0.11.0->transformers) (4.5.0)\n",
40
- "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.9/dist-packages (from requests->transformers) (2022.12.7)\n",
41
- "Requirement already satisfied: charset-normalizer~=2.0.0 in /usr/local/lib/python3.9/dist-packages (from requests->transformers) (2.0.12)\n",
42
- "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.9/dist-packages (from requests->transformers) (3.4)\n",
43
- "Requirement already satisfied: urllib3<1.27,>=1.21.1 in /usr/local/lib/python3.9/dist-packages (from requests->transformers) (1.26.15)\n"
44
- ]
45
- }
46
- ],
47
- "source": [
48
- "# !ls\n",
49
- "# !pip install transformers"
50
- ]
51
- },
52
- {
53
- "cell_type": "code",
54
- "execution_count": null,
55
- "metadata": {
56
- "colab": {
57
- "base_uri": "https://localhost:8080/"
58
- },
59
- "id": "EbJOwNb7UTVf",
60
- "outputId": "b9b072d4-9a32-4a9e-899d-ffbd80bb8b6e"
61
- },
62
- "outputs": [
63
- {
64
- "name": "stdout",
65
- "output_type": "stream",
66
- "text": [
67
- "Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n"
68
- ]
69
- }
70
- ],
71
- "source": [
72
- "from google.colab import drive\n",
73
- "drive.mount('/content/drive')\n",
74
- "# PATH = \"/content/drive/MyDrive/data\""
75
- ]
76
- },
77
- {
78
- "cell_type": "code",
79
- "execution_count": null,
80
- "metadata": {
81
- "id": "AbuSkKXDKoJ7"
82
- },
83
- "outputs": [],
84
- "source": [
85
- "import torch\n",
86
- "import pandas as pd\n",
87
- "from torch.utils.data import Dataset, DataLoader\n",
88
- "from transformers import DistilBertTokenizerFast, DistilBertForSequenceClassification"
89
- ]
90
- },
91
- {
92
- "attachments": {},
93
- "cell_type": "markdown",
94
- "metadata": {},
95
- "source": [
96
- "The below defines a custom dataset class ToxicCommentsDataset that inherits from torch.utils.data.Dataset. It takes in the following arguments:\n",
97
- "\n",
98
- "comments: The list of comments to be used as input\n",
99
- "labels: The list of labels corresponding to each comment\n",
100
- "tokenizer: The tokenizer to be used to preprocess the comments\n",
101
- "max_length: The maximum length of the tokenized comments\n",
102
- "The class implements the __len__ and __getitem__ methods required for PyTorch datasets. In the __getitem__ method, each comment is tokenized using the provided tokenizer, truncated to max_length, and padded to max_length using the padding argument. The resulting token IDs, attention mask, and label are returned as a dictionary with keys 'input_ids', 'attention_mask', and 'labels', respectively."
103
- ]
104
- },
105
- {
106
- "cell_type": "code",
107
- "execution_count": null,
108
- "metadata": {
109
- "id": "AO-AiK4aNBgh"
110
- },
111
- "outputs": [],
112
- "source": [
113
- "# Create a custom dataset class for the comments and labels\n",
114
- "class ToxicCommentsDataset(torch.utils.data.Dataset):\n",
115
- " def __init__(self, comments, labels, tokenizer, max_length):\n",
116
- " self.comments = comments\n",
117
- " self.labels = labels\n",
118
- " self.tokenizer = tokenizer\n",
119
- " self.max_length = max_length\n",
120
- "\n",
121
- " def __len__(self):\n",
122
- " return len(self.comments)\n",
123
- "\n",
124
- " def __getitem__(self, index):\n",
125
- " comment = str(self.comments[index])\n",
126
- " label = self.labels[index]\n",
127
- "\n",
128
- " encoding = self.tokenizer.encode_plus(\n",
129
- " comment,\n",
130
- " add_special_tokens=True,\n",
131
- " truncation=True,\n",
132
- " max_length=self.max_length,\n",
133
- " return_token_type_ids=False,\n",
134
- " padding='max_length',\n",
135
- " return_attention_mask=True,\n",
136
- " return_tensors='pt'\n",
137
- " )\n",
138
- "\n",
139
- " return {\n",
140
- " 'input_ids': encoding['input_ids'].flatten(),\n",
141
- " 'attention_mask': encoding['attention_mask'].flatten(),\n",
142
- " 'labels': torch.tensor(label, dtype=torch.float32)\n",
143
- " }"
144
- ]
145
- },
146
- {
147
- "cell_type": "markdown",
148
- "metadata": {
149
- "id": "nGmuzGHQXEeX"
150
- },
151
- "source": [
152
- "### loading train and test"
153
- ]
154
- },
155
- {
156
- "cell_type": "code",
157
- "execution_count": null,
158
- "metadata": {
159
- "id": "JPbtgyxsZKlD"
160
- },
161
- "outputs": [],
162
- "source": [
163
- "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
164
- "\n",
165
- "# training parameters\n",
166
- "batch_size = 8\n",
167
- "num_epochs = 10\n",
168
- "learning_rate = 0.0001\n",
169
- "max_length = 512"
170
- ]
171
- },
172
- {
173
- "attachments": {},
174
- "cell_type": "markdown",
175
- "metadata": {},
176
- "source": [
177
- "Load training from a CSV file located at /content/drive/MyDrive/data/train.csv into a pandas DataFrame train_texts_df. It then randomly samples 80% of the rows from the DataFrame using sample method and sets them as the training data.\n",
178
- "\n",
179
- "Next, the code sets the training labels by extracting the 'toxic', 'severe_toxic', 'obscene', 'threat', 'insult', 'identity_hate' columns from train_texts_df and converting them to a list using the values.tolist() method. The comments are also extracted from the 'comment_text' column of train_texts_df and stored in train_comments.\n",
180
- "\n",
181
- "The code then loads the pre-trained DistilBERT model and tokenizer from the Hugging Face Transformers library using the DistilBertForSequenceClassification.from_pretrained and DistilBertTokenizerFast.from_pretrained methods, respectively. The num_labels argument is set to 6 to indicate that the model should be trained for multi-label classification.\n",
182
- "\n",
183
- "Finally, the train_comments and train_labels lists, along with the tokenizer and max_length, are passed to the ToxicCommentsDataset class to create the train_dataset."
184
- ]
185
- },
186
- {
187
- "cell_type": "code",
188
- "execution_count": null,
189
- "metadata": {
190
- "colab": {
191
- "base_uri": "https://localhost:8080/"
192
- },
193
- "id": "dYhlIni5XA2y",
194
- "outputId": "b0edeae3-8871-4fa7-ebd8-7ec2591faa5e"
195
- },
196
- "outputs": [
197
- {
198
- "name": "stderr",
199
- "output_type": "stream",
200
- "text": [
201
- "Some weights of the model checkpoint at distilbert-base-uncased were not used when initializing DistilBertForSequenceClassification: ['vocab_projector.weight', 'vocab_layer_norm.bias', 'vocab_layer_norm.weight', 'vocab_transform.weight', 'vocab_projector.bias', 'vocab_transform.bias']\n",
202
- "- This IS expected if you are initializing DistilBertForSequenceClassification from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n",
203
- "- This IS NOT expected if you are initializing DistilBertForSequenceClassification from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n",
204
- "Some weights of DistilBertForSequenceClassification were not initialized from the model checkpoint at distilbert-base-uncased and are newly initialized: ['pre_classifier.weight', 'classifier.bias', 'classifier.weight', 'pre_classifier.bias']\n",
205
- "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n"
206
- ]
207
- }
208
- ],
209
- "source": [
210
- "train_texts_df = pd.read_csv('/content/drive/MyDrive/data/train.csv')\n",
211
- "\n",
212
- "train_texts_df = train_texts_df.sample(frac=0.8, random_state=42)\n",
213
- "\n",
214
- "# set the training labels:\n",
215
- "train_labels = train_texts_df[['toxic', 'severe_toxic', 'obscene', 'threat', 'insult', 'identity_hate']].values.tolist()\n",
216
- "train_comments = train_texts_df['comment_text'].tolist()\n",
217
- "\n",
218
- "# Load the pre-trained DistilBERT model and tokenizer\n",
219
- "model = DistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased', num_labels=6)\n",
220
- "tokenizer = DistilBertTokenizerFast.from_pretrained('distilbert-base-uncased')\n",
221
- "\n",
222
- "train_dataset = ToxicCommentsDataset(train_comments, train_labels, tokenizer, max_length=512)"
223
- ]
224
- },
225
- {
226
- "attachments": {},
227
- "cell_type": "markdown",
228
- "metadata": {},
229
- "source": [
230
- "Then you loads the test data from two CSV files located at /content/drive/MyDrive/data/test_labels.csv and /content/drive/MyDrive/data/test.csv into pandas DataFrames test_labels and test_data, respectively.\n",
231
- "\n",
232
- "Next, the code filters out any rows in test_labels that contain -1 using the any method and creates a boolean mask for those rows using the ~ operator. The filtered test_labels DataFrame is created by applying the mask using the loc method.\n",
233
- "\n",
234
- "The code then modifies test_data to only include rows where the id column exists in test_labels_filtered. This is done using the isin method on the id column of test_data.\n",
235
- "\n",
236
- "After that, the code randomly samples 50% of the rows from test_data_filtered and test_labels_filtered using the sample method with frac=0.5 and random_state=33.\n",
237
- "\n",
238
- "Finally, the toxic, severe_toxic, obscene, threat, insult, and identity_hate columns are extracted from test_labels_filtered and converted to a list of lists using the values.tolist() method. The comments are extracted from the comment_text column of test_data_filtered and stored in test_comments."
239
- ]
240
- },
241
- {
242
- "cell_type": "code",
243
- "execution_count": null,
244
- "metadata": {
245
- "colab": {
246
- "base_uri": "https://localhost:8080/"
247
- },
248
- "id": "iqnX6265NGW2",
249
- "outputId": "dcbda026-1793-4323-e000-6122a8aa615b"
250
- },
251
- "outputs": [
252
- {
253
- "name": "stdout",
254
- "output_type": "stream",
255
- "text": [
256
- " id toxic severe_toxic obscene threat insult \\\n",
257
- "128700 d718f29ed43fa5e7 1 0 0 0 0 \n",
258
- "23627 27661a70fa723a71 0 0 0 0 0 \n",
259
- "7664 0cd773ed62c92549 0 0 0 0 0 \n",
260
- "110519 b854eec6e725eb7b 0 0 0 0 0 \n",
261
- "66792 6f3502e118fb6d0e 0 0 0 0 0 \n",
262
- "\n",
263
- " identity_hate \n",
264
- "128700 0 \n",
265
- "23627 0 \n",
266
- "7664 0 \n",
267
- "110519 0 \n",
268
- "66792 0 \n",
269
- " id comment_text\n",
270
- "128700 d718f29ed43fa5e7 == I Hope You Die == \\n\\n :)\n",
271
- "23627 27661a70fa723a71 *Support as long as Cheyenne (Jason Derulo son...\n",
272
- "7664 0cd773ed62c92549 :::Consensus has not yet been established.\n",
273
- "110519 b854eec6e725eb7b \" \\n :Heh, this is one of those weird things w...\n",
274
- "66792 6f3502e118fb6d0e ::I'm concerned about some of the above. For...\n"
275
- ]
276
- }
277
- ],
278
- "source": [
279
- "test_labels = pd.read_csv('/content/drive/MyDrive/data/test_labels.csv')\n",
280
- "test_data = pd.read_csv('/content/drive/MyDrive/data/test.csv')\n",
281
- "\n",
282
- "# Filter out rows with -1 in test_labels\n",
283
- "mask = ~(test_labels == -1).any(axis=1)\n",
284
- "test_labels_filtered = test_labels.loc[mask]\n",
285
- "\n",
286
- "# modify test_data to only include data in which id also exists in test_labels_filtered\n",
287
- "test_data_filtered = test_data[test_data['id'].isin(test_labels_filtered['id'])]\n",
288
- "\n",
289
- "\n",
290
- "# randomly sample 10% of the data\n",
291
- "test_data_filtered = test_data_filtered.sample(frac=0.5, random_state=33)\n",
292
- "test_labels_filtered = test_labels_filtered.sample(frac=0.5, random_state=33)\n",
293
- "\n",
294
- "print(test_labels_filtered.head())\n",
295
- "print(test_data_filtered.head())\n",
296
- "\n",
297
- "# set the test labels:\n",
298
- "test_labels = test_labels_filtered[['toxic', 'severe_toxic', 'obscene', 'threat', 'insult', 'identity_hate']].values.tolist()\n",
299
- "test_comments = test_data_filtered['comment_text'].tolist()\n",
300
- "\n"
301
- ]
302
- },
303
- {
304
- "cell_type": "markdown",
305
- "metadata": {
306
- "id": "7YzsITMNXG4i"
307
- },
308
- "source": [
309
- "### Setting the model up"
310
- ]
311
- },
312
- {
313
- "cell_type": "code",
314
- "execution_count": null,
315
- "metadata": {
316
- "id": "CzPtlnoiLmWo"
317
- },
318
- "outputs": [],
319
- "source": [
320
- "# Define the optimizer and the loss function\n",
321
- "optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)\n",
322
- "loss_fn = torch.nn.BCEWithLogitsLoss()"
323
- ]
324
- },
325
- {
326
- "cell_type": "code",
327
- "execution_count": null,
328
- "metadata": {
329
- "id": "JYhXkBWjpSvu"
330
- },
331
- "outputs": [],
332
- "source": [
333
- "from torch.cuda.amp import autocast\n",
334
- "import matplotlib.pyplot as plt\n",
335
- "from tqdm import tqdm"
336
- ]
337
- },
338
- {
339
- "attachments": {},
340
- "cell_type": "markdown",
341
- "metadata": {},
342
- "source": [
343
- "This code trains a toxicity classification model using a custom dataset class called ToxicCommentsDataset and the pre-trained DistilBERT model and tokenizer. The model is trained on a training set and the training process is displayed using a plot of the loss function. The trained model is saved to disk. The code also prepares a filtered test set for evaluation of the trained model."
344
- ]
345
- },
346
- {
347
- "cell_type": "code",
348
- "execution_count": null,
349
- "metadata": {},
350
- "outputs": [],
351
- "source": [
352
- "# Train the model\n",
353
- "train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\n",
354
- "\n",
355
- "# set device again just in case\n",
356
- "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
357
- "model.to(device)\n",
358
- "\n",
359
- "# losses to plot\n",
360
- "train_losses = []\n",
361
- "\n",
362
- "for epoch in range(num_epochs):\n",
363
- " running_loss = 0.0\n",
364
- " stop = int(0.4*len(train_loader))\n",
365
- " for i, batch in enumerate(tqdm(train_loader)):\n",
366
- " # early stoppping\n",
367
- " if i == stop: break\n",
368
- " # move tensors to gpu\n",
369
- " input_ids = batch['input_ids'].to(device)\n",
370
- " attention_mask = batch['attention_mask'].to(device)\n",
371
- " labels = batch['labels'].to(device)\n",
372
- "\n",
373
- " # zero grads\n",
374
- " optimizer.zero_grad()\n",
375
- "\n",
376
- " # use autocast for mixed precision\n",
377
- " with autocast():\n",
378
- " outputs = model(input_ids.to(device), attention_mask=attention_mask.to(device), labels=labels.to(device))\n",
379
- " loss = loss_fn(outputs.logits, labels)\n",
380
- "\n",
381
- " loss.backward()\n",
382
- " optimizer.step()\n",
383
- "\n",
384
- " running_loss += loss.item()\n",
385
- " train_losses.append((i, loss.item()))\n",
386
- "\n",
387
- " if (i+1) % (stop//20) == 0:\n",
388
- " print(f'batch {i+1}/{len(train_loader)}, loss: {loss.item():.4f}, running loss: {running_loss:.4f}')\n",
389
- " plt.title(f\"epoch:{epoch}, iter:{i}\")\n",
390
- " plt.plot(*zip(*train_losses))\n",
391
- " plt.ylabel(\"Loss\")\n",
392
- " plt.xlabel(\"iter\")\n",
393
- " plt.show()\n",
394
- " # plt.savefig(f\"/content/drive/MyDrive/data/training_loss_dinner_{epoch}.png\")\n",
395
- "\n",
396
- " torch.save(model.state_dict(), f\"/content/drive/MyDrive/data/toxicity_classifier_dinner_epoch_{epoch+1}.pt\")\n",
397
- " \n",
398
- " print(f'Epoch {epoch+1}/{num_epochs}, Loss: {loss.item():.4f}, Running Loss {running_loss:.4f}')\n",
399
- "\n",
400
- "# Save the trained model\n",
401
- "model.save_pretrained('/content/drive/MyDrive/data/toxicity_classifier_dinner')"
402
- ]
403
- },
404
- {
405
- "cell_type": "markdown",
406
- "metadata": {
407
- "id": "grWMy6_zOBrC"
408
- },
409
- "source": [
410
- "## test Model eval"
411
- ]
412
- },
413
- {
414
- "cell_type": "code",
415
- "execution_count": null,
416
- "metadata": {
417
- "id": "lSYV8E76O1hY"
418
- },
419
- "outputs": [],
420
- "source": [
421
- "print(len(test_labels), len(test_comments))"
422
- ]
423
- },
424
- {
425
- "attachments": {},
426
- "cell_type": "markdown",
427
- "metadata": {},
428
- "source": [
429
- "In this code block, the saved pretrained model is loaded using the DistilBertForSequenceClassification class from the transformers library. The DistilBertTokenizerFast tokenizer is set up to tokenize the input data. A ToxicCommentsDataset is created using the test comments, test labels, tokenizer, and maximum sequence length. A DataLoader is created using the test dataset and batch size. The model is set to evaluation mode. Lists are created to store the predicted probabilities and true labels for each batch of data. The code iterates over the batches in the test data loader, moving the tensors to the device and disabling gradient computation. The forward pass is performed on the model, and the predicted probabilities are extracted using the sigmoid function. The probabilities and true labels are then appended to the respective lists. A progress update is printed every 20 batches."
430
- ]
431
- },
432
- {
433
- "cell_type": "code",
434
- "execution_count": null,
435
- "metadata": {
436
- "id": "BP_G1GB0y9ae"
437
- },
438
- "outputs": [],
439
- "source": [
440
- "# Load the saved pretrained model\n",
441
- "model = DistilBertForSequenceClassification.from_pretrained('/content/drive/MyDrive/data/toxicity_classifier')\n",
442
- "\n",
443
- "# Set the tokenizer\n",
444
- "tokenizer = DistilBertTokenizerFast.from_pretrained('distilbert-base-uncased')\n",
445
- "\n",
446
- "# Create test dataset\n",
447
- "test_dataset = ToxicCommentsDataset(test_comments, test_labels, tokenizer, max_length)\n",
448
- "\n",
449
- "# Create test data loader\n",
450
- "test_loader = DataLoader(test_dataset, batch_size=batch_size)\n",
451
- "\n",
452
- "# Set model to eval mode\n",
453
- "model.eval()\n",
454
- "\n",
455
- "# Create lists to store predictions and true labels\n",
456
- "preds = []\n",
457
- "true_labels = []\n",
458
- "\n",
459
- "model.to(device)\n",
460
- "\n",
461
- "# Iterate over batches in test data loader\n",
462
- "for i, batch in enumerate(tqdm(test_loader)):\n",
463
- " if not (i % 2 == 0):\n",
464
- " continue\n",
465
- "\n",
466
- " # Move tensors to device\n",
467
- " input_ids = batch['input_ids'].to(device)\n",
468
- " attention_mask = batch['attention_mask'].to(device)\n",
469
- " labels = batch['labels'].to(device)\n",
470
- "\n",
471
- " # Disable gradient computation\n",
472
- " with torch.no_grad():\n",
473
- " # Forward pass\n",
474
- " outputs = model(input_ids, attention_mask=attention_mask)\n",
475
- "\n",
476
- " # Get predicted probabilities\n",
477
- " probs = torch.sigmoid(outputs.logits)\n",
478
- "\n",
479
- " # Append probabilities and true labels to lists\n",
480
- " preds += probs.cpu().numpy().tolist()\n",
481
- " true_labels += labels.cpu().numpy().tolist()\n",
482
- "\n",
483
- " if i % 20 == 0:\n",
484
- " print(f\"Processed {i}/{len(test_loader)} batches\")"
485
- ]
486
- },
487
- {
488
- "attachments": {},
489
- "cell_type": "markdown",
490
- "metadata": {},
491
- "source": [
492
- "This code snippet calculates several evaluation metrics for a toxicity classifier model trained on a dataset of toxic and non-toxic comments. The evaluation metrics calculated are accuracy, precision, recall, and F1 score.\n",
493
- "\n",
494
- "First, the predicted probabilities and true labels are flattened into 1D arrays using list comprehensions. Then, a binary label is assigned to each prediction based on a given threshold. If the predicted probability is greater than or equal to the threshold, the label is set to 1, otherwise, it is set to 0.\n",
495
- "\n"
496
- ]
497
- },
498
- {
499
- "cell_type": "code",
500
- "execution_count": null,
501
- "metadata": {
502
- "id": "HPP5iHgd57ag"
503
- },
504
- "outputs": [],
505
- "source": [
506
- "# !pip install scikit-learn\n",
507
- "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score\n",
508
- "\n",
509
- "print(preds)\n",
510
- "\n",
511
- "# Calculate metrics\n",
512
- "# Flatten the predictions and true labels to 1D arrays\n",
513
- "flat_preds = [p for sublist in preds for p in sublist]\n",
514
- "flat_true_labels = [l for sublist in true_labels for l in sublist]\n",
515
- "print(len(flat_true_labels), len(flat_preds))\n",
516
- "\n",
517
- "# Convert predicted probabilities to binary labels based on threshold\n",
518
- "threshold = 0.66666 # Thresholds for class 0 and class 1\n",
519
- "preds_binary = []\n",
520
- "for id in preds:\n",
521
- " for prob in id:\n",
522
- " if prob >= threshold: preds_binary.append(1)\n",
523
- " else: preds_binary.append(0)\n",
524
- "\n",
525
- "print(preds_binary)\n",
526
- "\n",
527
- "# Calculate metrics for binary predictions\n",
528
- "accuracy = accuracy_score(flat_true_labels, preds_binary)\n",
529
- "precision = precision_score(flat_true_labels, preds_binary)\n",
530
- "recall = recall_score(flat_true_labels, preds_binary)\n",
531
- "f1 = f1_score(flat_true_labels, preds_binary)\n",
532
- "\n",
533
- "print('Accuracy: ', accuracy)\n",
534
- "print('Precision: ', precision)\n",
535
- "print('Recall: ', recall)\n",
536
- "print('F1: ', f1)\n",
537
- "\n"
538
- ]
539
- }
540
- ],
541
- "metadata": {
542
- "accelerator": "GPU",
543
- "colab": {
544
- "provenance": []
545
- },
546
- "gpuClass": "standard",
547
- "kernelspec": {
548
- "display_name": "Python 3",
549
- "name": "python3"
550
- },
551
- "language_info": {
552
- "name": "python"
553
- }
554
- },
555
- "nbformat": 4,
556
- "nbformat_minor": 0
557
- }