File size: 12,976 Bytes
924a4d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "\n",
    "# Check if a GPU is available\n",
    "print(\"GPU Available:\", torch.cuda.is_available())\n",
    "\n",
    "# Check the name of the GPU\n",
    "if torch.cuda.is_available():\n",
    "    print(\"GPU Name:\", torch.cuda.get_device_name(0))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from fastai.vision.all import *\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "### Data Loader\n",
    "path = Path('../Spectrogram_Images')\n",
    "\n",
    "dls = ImageDataLoaders.from_folder(\n",
    "    path,\n",
    "    train = '.',\n",
    "    valid_pct=0.2,  # 20% of data for validation\n",
    "    item_tfms = Resize(224), # Resize images to 224x224 pixels for CNN\n",
    "    batch_tfms=aug_transforms(mult=1.0)  # Apply basic augmentations\n",
    ")\n",
    "\n",
    "# Show a batch of images to verify data loading\n",
    "dls.show_batch(max_n=9, figsize=(8, 8))\n",
    "\n",
    "### CNN\n",
    "from fastai.callback.tracker import EarlyStoppingCallback\n",
    "learn = vision_learner(dls, resnet34, metrics=accuracy,wd=1e-4, cbs=[EarlyStoppingCallback(monitor='valid_loss', patience=3)])\n",
    "\n",
    "\n",
    "\n",
    "lr_steep = learn.lr_find().valley\n",
    "\n",
    "plt.show()\n",
    "\n",
    "learn.model[-1].add_module('dropout', nn.Dropout(p=0.5))\n",
    "learn.fine_tune(10, base_lr=lr_steep)\n",
    "\n",
    "# Fine-tune with early stopping\n",
    "\n",
    "# Plot training and validation loss curves\n",
    "learn.recorder.plot_loss()\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<style>\n",
       "    /* Turns off some styling */\n",
       "    progress {\n",
       "        /* gets rid of default border in Firefox and Opera. */\n",
       "        border: none;\n",
       "        /* Needs to be in here for Safari polyfill so background images work as expected. */\n",
       "        background-size: auto;\n",
       "    }\n",
       "    progress:not([value]), progress:not([value])::-webkit-progress-bar {\n",
       "        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);\n",
       "    }\n",
       "    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {\n",
       "        background: #F44336;\n",
       "    }\n",
       "</style>\n"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Validation Results: [0.3122069239616394, 0.8672986030578613]\n",
      "Validation Loss: 0.3122\n",
      "Validation Accuracy: 0.8673\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "<style>\n",
       "    /* Turns off some styling */\n",
       "    progress {\n",
       "        /* gets rid of default border in Firefox and Opera. */\n",
       "        border: none;\n",
       "        /* Needs to be in here for Safari polyfill so background images work as expected. */\n",
       "        background-size: auto;\n",
       "    }\n",
       "    progress:not([value]), progress:not([value])::-webkit-progress-bar {\n",
       "        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);\n",
       "    }\n",
       "    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {\n",
       "        background: #F44336;\n",
       "    }\n",
       "</style>\n"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training Loss: 0.4510\n",
      "Training Accuracy: 0.8065\n",
      "The model seems to be generalizing well.\n"
     ]
    }
   ],
   "source": [
    "### CNN\n",
    "from fastai.vision.all import *\n",
    "from fastai.callback.tracker import EarlyStoppingCallback\n",
    "path = Path('../Spectrogram_Images/s')\n",
    "set_seed(31)\n",
    "dls = ImageDataLoaders.from_folder(\n",
    "    path,\n",
    "    train = '.',\n",
    "    valid_pct=0.2,  # 20% of data for validation\n",
    "    item_tfms = Resize(224), # Resize images to 224x224 pixels for CNN\n",
    "    batch_tfms=aug_transforms(mult=1.0)  # Apply basic augmentations\n",
    ")\n",
    "learn = vision_learner(dls, resnet34, metrics=accuracy, wd=1e-4 ,cbs=[EarlyStoppingCallback(monitor='valid_loss', patience=3)])\n",
    "\n",
    "learn.load('final_model')\n",
    "learn.model.eval()\n",
    "# Validate the loaded model on the validation dataset\n",
    "validation_results = learn.validate(dl=dls.valid)\n",
    "print(f\"Validation Results: {validation_results}\")\n",
    "\n",
    "# Print the validation results\n",
    "validation_loss, validation_accuracy = validation_results\n",
    "print(f\"Validation Loss: {validation_loss:.4f}\")\n",
    "print(f\"Validation Accuracy: {validation_accuracy:.4f}\")\n",
    "\n",
    "# Compare with training metrics (if available)\n",
    "training_results = learn.validate(dl=dls.train)\n",
    "training_loss, training_accuracy = training_results\n",
    "print(f\"Training Loss: {training_loss:.4f}\")\n",
    "print(f\"Training Accuracy: {training_accuracy:.4f}\")\n",
    "\n",
    "# Check for overfitting\n",
    "if training_accuracy > validation_accuracy + 0.05:\n",
    "    print(\"Warning: The model might be overfitting.\")\n",
    "else:\n",
    "    print(\"The model seems to be generalizing well.\")\n",
    "    \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<style>\n",
       "    /* Turns off some styling */\n",
       "    progress {\n",
       "        /* gets rid of default border in Firefox and Opera. */\n",
       "        border: none;\n",
       "        /* Needs to be in here for Safari polyfill so background images work as expected. */\n",
       "        background-size: auto;\n",
       "    }\n",
       "    progress:not([value]), progress:not([value])::-webkit-progress-bar {\n",
       "        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);\n",
       "    }\n",
       "    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {\n",
       "        background: #F44336;\n",
       "    }\n",
       "</style>\n"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Predictions shape: torch.Size([848, 2])\n",
      "Targets shape: torch.Size([848])\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "<style>\n",
       "    /* Turns off some styling */\n",
       "    progress {\n",
       "        /* gets rid of default border in Firefox and Opera. */\n",
       "        border: none;\n",
       "        /* Needs to be in here for Safari polyfill so background images work as expected. */\n",
       "        background-size: auto;\n",
       "    }\n",
       "    progress:not([value]), progress:not([value])::-webkit-progress-bar {\n",
       "        background: repeating-linear-gradient(45deg, #7e7e7e, #7e7e7e 10px, #5c5c5c 10px, #5c5c5c 20px);\n",
       "    }\n",
       "    .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {\n",
       "        background: #F44336;\n",
       "    }\n",
       "</style>\n"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "ename": "ValueError",
     "evalue": "Predictions or targets are None. Please check the DataLoader and the test data.",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[16], line 25\u001b[0m\n\u001b[1;32m     23\u001b[0m \u001b[38;5;66;03m# Check if preds or targets are None\u001b[39;00m\n\u001b[1;32m     24\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m preds \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mor\u001b[39;00m targets \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[0;32m---> 25\u001b[0m     \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mPredictions or targets are None. Please check the DataLoader and the test data.\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m     27\u001b[0m \u001b[38;5;66;03m# Print the shapes of preds and targets for debugging\u001b[39;00m\n\u001b[1;32m     28\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mPredictions shape: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mpreds\u001b[38;5;241m.\u001b[39mshape\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n",
      "\u001b[0;31mValueError\u001b[0m: Predictions or targets are None. Please check the DataLoader and the test data."
     ]
    }
   ],
   "source": [
    "from sklearn.metrics import classification_report\n",
    "\n",
    "\n",
    "path = Path(\"Test\")\n",
    "\n",
    "learn = load_learner('Test/final_model.pkl')\n",
    "\n",
    "test_dl = learn.dls.test_dl(get_image_files(path))\n",
    "\n",
    "preds, targets  =learn.get_preds(dl=dls.train)\n",
    "\n",
    "# Check if preds or targets are None\n",
    "if preds is None or targets is None:\n",
    "    raise ValueError(\"Predictions or targets are None. Please check the DataLoader and the test data.\")\n",
    "\n",
    "# Print the shapes of preds and targets for debugging\n",
    "print(f\"Predictions shape: {preds.shape}\")\n",
    "print(f\"Targets shape: {targets.shape}\")\n",
    "\n",
    "# Get predictions and targets\n",
    "preds, targets = learn.get_preds(dl=test_dl)\n",
    "\n",
    "# Check if preds or targets are None\n",
    "if preds is None or targets is None:\n",
    "    raise ValueError(\"Predictions or targets are None. Please check the DataLoader and the test data.\")\n",
    "\n",
    "# Print the shapes of preds and targets for debugging\n",
    "print(f\"Predictions shape: {preds.shape}\")\n",
    "print(f\"Targets shape: {targets.shape}\")\n",
    "\n",
    "# Calculate accuracy\n",
    "acc = accuracy(preds, targets)\n",
    "print(f'Accuracy on test set: {acc.item():.4f}')\n",
    "\n",
    "# Plot confusion matrix\n",
    "interp = ClassificationInterpretation.from_learner(learn, dl=test_dl)\n",
    "interp.plot_confusion_matrix()\n",
    "plt.show()\n",
    "\n",
    "# Print classification report\n",
    "y_pred = preds.argmax(dim=1)\n",
    "y_true = targets\n",
    "print(classification_report(y_true, y_pred, target_names=learn.dls.vocab))\n",
    "\n",
    "# Print additional information\n",
    "print(f\"Number of classes: {len(learn.dls.vocab)}\")\n",
    "print(f\"Class names: {learn.dls.vocab}\")\n",
    "print(f\"Number of test images: {len(test_dl.dataset)}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "laugh_detection",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}