Diff of /vgg16 & vgg19.ipynb [000000] .. [2ed9d9]

Switch to unified view

a b/vgg16 & vgg19.ipynb
1
{
2
 "cells": [
3
  {
4
   "cell_type": "code",
5
   "execution_count": 1,
6
   "id": "37e884ed",
7
   "metadata": {},
8
   "outputs": [],
9
   "source": [
10
    "# Importing necessary libraries\n",
11
    "import os\n",
12
    "import random\n",
13
    "import shutil\n",
14
    "import numpy as np\n",
15
    "import matplotlib.pyplot as plt\n",
16
    "from keras.preprocessing.image import ImageDataGenerator\n",
17
    "from keras.applications import VGG16, VGG19, ResNet50, InceptionV3, Xception\n",
18
    "from keras.models import Model\n",
19
    "from keras.layers import Dense, GlobalAveragePooling2D\n",
20
    "from keras.optimizers import Adam\n",
21
    "from keras.callbacks import ModelCheckpoint\n",
22
    "from sklearn.metrics import classification_report, confusion_matrix\n",
23
    "\n",
24
    "# Setting random seed for reproducibility\n",
25
    "np.random.seed(42)\n",
26
    "random.seed(42)\n",
27
    "\n",
28
    "# Define constants\n",
29
    "NUM_CLASSES = 2\n",
30
    "IMG_SIZE = (224, 224)\n",
31
    "BATCH_SIZE = 32\n",
32
    "TRAIN_DIR = 'train'\n",
33
    "VAL_DIR = 'val'\n",
34
    "TEST_DIR = 'test'\n",
35
    "TRAIN_SPLIT = 0.7\n",
36
    "VAL_SPLIT = 0.1\n",
37
    "TEST_SPLIT = 0.2\n",
38
    "test_samples = 280"
39
   ]
40
  },
41
  {
42
   "cell_type": "code",
43
   "execution_count": 2,
44
   "id": "3a76b0e6",
45
   "metadata": {},
46
   "outputs": [],
47
   "source": [
48
    "# Define the base directory where the image data is located\n",
49
    "BASE_DIR = r\"C:\\Users\\mohit\\Downloads\\DIP Assignment 2\\Data\""
50
   ]
51
  },
52
  {
53
   "cell_type": "code",
54
   "execution_count": 3,
55
   "id": "e3142f03",
56
   "metadata": {},
57
   "outputs": [],
58
   "source": [
59
    "# Set the paths for training, validation, and test data\n",
60
    "TRAIN_DIR = os.path.join(BASE_DIR, 'train')\n",
61
    "VAL_DIR = os.path.join(BASE_DIR, 'val')\n",
62
    "TEST_DIR = os.path.join(BASE_DIR, 'test')"
63
   ]
64
  },
65
  {
66
   "cell_type": "code",
67
   "execution_count": 4,
68
   "id": "0bfbe95a",
69
   "metadata": {},
70
   "outputs": [],
71
   "source": [
72
    "# Load and preprocess the data\n",
73
    "train_datagen = ImageDataGenerator(rescale=1./255,shear_range=0.2,zoom_range=0.2,horizontal_flip=True)\n",
74
    "val_datagen = ImageDataGenerator(rescale=1./255)\n",
75
    "test_datagen = ImageDataGenerator(rescale=1./255)"
76
   ]
77
  },
78
  {
79
   "cell_type": "code",
80
   "execution_count": 5,
81
   "id": "77eeebb9",
82
   "metadata": {},
83
   "outputs": [
84
    {
85
     "name": "stdout",
86
     "output_type": "stream",
87
     "text": [
88
      "Found 980 images belonging to 2 classes.\n",
89
      "Found 140 images belonging to 2 classes.\n",
90
      "Found 280 images belonging to 2 classes.\n"
91
     ]
92
    }
93
   ],
94
   "source": [
95
    "train_generator = train_datagen.flow_from_directory(TRAIN_DIR,target_size=IMG_SIZE,batch_size=BATCH_SIZE,class_mode='categorical')\n",
96
    "\n",
97
    "val_generator = val_datagen.flow_from_directory(VAL_DIR,target_size=IMG_SIZE,batch_size=BATCH_SIZE,class_mode='categorical')\n",
98
    "\n",
99
    "test_generator = test_datagen.flow_from_directory(TEST_DIR,target_size=IMG_SIZE,batch_size=BATCH_SIZE,class_mode='categorical',shuffle=False)"
100
   ]
101
  },
102
  {
103
   "cell_type": "code",
104
   "execution_count": 6,
105
   "id": "221f07fe",
106
   "metadata": {},
107
   "outputs": [],
108
   "source": [
109
    "# Define function for creating transfer learning models\n",
110
    "def create_transfer_model(base_model, num_classes):\n",
111
    "    x = base_model.output\n",
112
    "    x = GlobalAveragePooling2D()(x)\n",
113
    "    x = Dense(1024, activation='relu')(x)\n",
114
    "    predictions = Dense(num_classes, activation='softmax')(x)\n",
115
    "    model = Model(inputs=base_model.input, outputs=predictions)\n",
116
    "    return model\n",
117
    "\n",
118
    "# Define VGG16 model\n",
119
    "vgg16_base = VGG16(include_top=False, weights='imagenet', input_shape=(IMG_SIZE[0], IMG_SIZE[1], 3))\n",
120
    "vgg16_model = create_transfer_model(vgg16_base, NUM_CLASSES)\n",
121
    "\n",
122
    "# Define VGG19 model\n",
123
    "vgg19_base = VGG19(include_top=False, weights='imagenet', input_shape=(IMG_SIZE[0], IMG_SIZE[1], 3))\n",
124
    "vgg19_model = create_transfer_model(vgg19_base, NUM_CLASSES)"
125
   ]
126
  },
127
  {
128
   "cell_type": "code",
129
   "execution_count": 7,
130
   "id": "4c47d0fd",
131
   "metadata": {},
132
   "outputs": [],
133
   "source": [
134
    "# Compile the models\n",
135
    "optimizer = Adam(learning_rate=0.0001)\n",
136
    "vgg16_model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])\n",
137
    "vgg19_model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])"
138
   ]
139
  },
140
  {
141
   "cell_type": "code",
142
   "execution_count": 8,
143
   "id": "b1063daa",
144
   "metadata": {},
145
   "outputs": [],
146
   "source": [
147
    "# Define checkpoint callback to save the best model during training\n",
148
    "checkpoint = ModelCheckpoint('best_model.h5', monitor='val_loss', save_best_only=True)"
149
   ]
150
  },
151
  {
152
   "cell_type": "code",
153
   "execution_count": 9,
154
   "id": "d9c6cb6b",
155
   "metadata": {},
156
   "outputs": [
157
    {
158
     "name": "stderr",
159
     "output_type": "stream",
160
     "text": [
161
      "C:\\Users\\mohit\\AppData\\Local\\Temp\\ipykernel_25572\\2039408895.py:2: UserWarning: `Model.fit_generator` is deprecated and will be removed in a future version. Please use `Model.fit`, which supports generators.\n",
162
      "  vgg16_history = vgg16_model.fit_generator(train_generator, steps_per_epoch=train_generator.n // train_generator.batch_size, epochs=5, validation_data=val_generator, validation_steps=val_generator.n // val_generator.batch_size, callbacks=[checkpoint])\n"
163
     ]
164
    },
165
    {
166
     "name": "stdout",
167
     "output_type": "stream",
168
     "text": [
169
      "Epoch 1/5\n",
170
      "30/30 [==============================] - 269s 9s/step - loss: 0.6998 - accuracy: 0.5190 - val_loss: 0.7125 - val_accuracy: 0.5000\n",
171
      "Epoch 2/5\n",
172
      "30/30 [==============================] - 286s 10s/step - loss: 0.6402 - accuracy: 0.6118 - val_loss: 0.4709 - val_accuracy: 0.8281\n",
173
      "Epoch 3/5\n",
174
      "30/30 [==============================] - 470s 16s/step - loss: 0.2767 - accuracy: 0.9008 - val_loss: 0.1435 - val_accuracy: 0.9531\n",
175
      "Epoch 4/5\n",
176
      "30/30 [==============================] - 503s 17s/step - loss: 0.1493 - accuracy: 0.9473 - val_loss: 0.1466 - val_accuracy: 0.9609\n",
177
      "Epoch 5/5\n",
178
      "30/30 [==============================] - 504s 17s/step - loss: 0.1644 - accuracy: 0.9494 - val_loss: 0.0989 - val_accuracy: 0.9688\n"
179
     ]
180
    },
181
    {
182
     "name": "stderr",
183
     "output_type": "stream",
184
     "text": [
185
      "C:\\Users\\mohit\\AppData\\Local\\Temp\\ipykernel_25572\\2039408895.py:3: UserWarning: `Model.fit_generator` is deprecated and will be removed in a future version. Please use `Model.fit`, which supports generators.\n",
186
      "  vgg19_history = vgg19_model.fit_generator(train_generator, steps_per_epoch=train_generator.n // train_generator.batch_size, epochs=5, validation_data=val_generator, validation_steps=val_generator.n // val_generator.batch_size, callbacks=[checkpoint])\n"
187
     ]
188
    },
189
    {
190
     "name": "stdout",
191
     "output_type": "stream",
192
     "text": [
193
      "Epoch 1/5\n",
194
      "30/30 [==============================] - 570s 19s/step - loss: 0.7282 - accuracy: 0.5042 - val_loss: 0.6897 - val_accuracy: 0.5156\n",
195
      "Epoch 2/5\n",
196
      "30/30 [==============================] - 558s 19s/step - loss: 0.6453 - accuracy: 0.6983 - val_loss: 0.4191 - val_accuracy: 0.8672\n",
197
      "Epoch 3/5\n",
198
      "30/30 [==============================] - 544s 18s/step - loss: 0.3698 - accuracy: 0.8576 - val_loss: 0.1742 - val_accuracy: 0.9297\n",
199
      "Epoch 4/5\n",
200
      "30/30 [==============================] - 547s 18s/step - loss: 0.2672 - accuracy: 0.9040 - val_loss: 0.1718 - val_accuracy: 0.9375\n",
201
      "Epoch 5/5\n",
202
      "30/30 [==============================] - 354s 12s/step - loss: 0.2497 - accuracy: 0.9146 - val_loss: 0.2170 - val_accuracy: 0.8984\n"
203
     ]
204
    }
205
   ],
206
   "source": [
207
    "# Train the models\n",
208
    "vgg16_history = vgg16_model.fit_generator(train_generator, steps_per_epoch=train_generator.n // train_generator.batch_size, epochs=5, validation_data=val_generator, validation_steps=val_generator.n // val_generator.batch_size, callbacks=[checkpoint])\n",
209
    "vgg19_history = vgg19_model.fit_generator(train_generator, steps_per_epoch=train_generator.n // train_generator.batch_size, epochs=5, validation_data=val_generator, validation_steps=val_generator.n // val_generator.batch_size, callbacks=[checkpoint])"
210
   ]
211
  },
212
  {
213
   "cell_type": "code",
214
   "execution_count": 10,
215
   "id": "865704d7",
216
   "metadata": {},
217
   "outputs": [
218
    {
219
     "name": "stderr",
220
     "output_type": "stream",
221
     "text": [
222
      "C:\\Users\\mohit\\AppData\\Local\\Temp\\ipykernel_25572\\1392354301.py:2: UserWarning: `Model.evaluate_generator` is deprecated and will be removed in a future version. Please use `Model.evaluate`, which supports generators.\n",
223
      "  vgg16_scores = vgg16_model.evaluate_generator(test_generator, steps=test_samples // BATCH_SIZE)\n"
224
     ]
225
    },
226
    {
227
     "name": "stdout",
228
     "output_type": "stream",
229
     "text": [
230
      "VGG16 Test Loss: 0.07796119153499603\n",
231
      "VGG16 Test Accuracy: 0.97265625\n"
232
     ]
233
    },
234
    {
235
     "name": "stderr",
236
     "output_type": "stream",
237
     "text": [
238
      "C:\\Users\\mohit\\AppData\\Local\\Temp\\ipykernel_25572\\1392354301.py:6: UserWarning: `Model.evaluate_generator` is deprecated and will be removed in a future version. Please use `Model.evaluate`, which supports generators.\n",
239
      "  vgg19_scores = vgg19_model.evaluate_generator(test_generator, steps=test_samples // BATCH_SIZE)\n"
240
     ]
241
    },
242
    {
243
     "name": "stdout",
244
     "output_type": "stream",
245
     "text": [
246
      "VGG19 Test Loss: 0.14393511414527893\n",
247
      "VGG19 Test Accuracy: 0.94140625\n"
248
     ]
249
    }
250
   ],
251
   "source": [
252
    "# Evaluate the models on test data\n",
253
    "vgg16_scores = vgg16_model.evaluate_generator(test_generator, steps=test_samples // BATCH_SIZE)\n",
254
    "print(\"VGG16 Test Loss:\", vgg16_scores[0])\n",
255
    "print(\"VGG16 Test Accuracy:\", vgg16_scores[1])\n",
256
    "\n",
257
    "vgg19_scores = vgg19_model.evaluate_generator(test_generator, steps=test_samples // BATCH_SIZE)\n",
258
    "print(\"VGG19 Test Loss:\", vgg19_scores[0])\n",
259
    "print(\"VGG19 Test Accuracy:\", vgg19_scores[1])"
260
   ]
261
  },
262
  {
263
   "cell_type": "code",
264
   "execution_count": 15,
265
   "id": "0a38cb63",
266
   "metadata": {},
267
   "outputs": [
268
    {
269
     "name": "stderr",
270
     "output_type": "stream",
271
     "text": [
272
      "C:\\Users\\mohit\\AppData\\Local\\Temp\\ipykernel_25572\\2218791254.py:8: UserWarning: `Model.predict_generator` is deprecated and will be removed in a future version. Please use `Model.predict`, which supports generators.\n",
273
      "  vgg16_predictions = vgg16_model.predict_generator(test_generator, steps=num_prediction_steps, verbose=1)\n"
274
     ]
275
    },
276
    {
277
     "name": "stdout",
278
     "output_type": "stream",
279
     "text": [
280
      "9/9 [==============================] - 23s 3s/step\n"
281
     ]
282
    }
283
   ],
284
   "source": [
285
    "# Get the number of test samples\n",
286
    "num_test_samples = test_generator.n\n",
287
    "\n",
288
    "# Calculate the number of steps for prediction\n",
289
    "num_prediction_steps = num_test_samples // test_generator.batch_size + 1\n",
290
    "\n",
291
    "# Generate predictions for all test samples\n",
292
    "vgg16_predictions = vgg16_model.predict_generator(test_generator, steps=num_prediction_steps, verbose=1)\n",
293
    "\n",
294
    "# Convert predictions to class labels\n",
295
    "vgg16_predicted_labels = np.argmax(vgg16_predictions, axis=1)"
296
   ]
297
  },
298
  {
299
   "cell_type": "code",
300
   "execution_count": 16,
301
   "id": "38f80e7c",
302
   "metadata": {},
303
   "outputs": [
304
    {
305
     "name": "stderr",
306
     "output_type": "stream",
307
     "text": [
308
      "C:\\Users\\mohit\\AppData\\Local\\Temp\\ipykernel_25572\\903632277.py:8: UserWarning: `Model.predict_generator` is deprecated and will be removed in a future version. Please use `Model.predict`, which supports generators.\n",
309
      "  vgg19_predictions = vgg19_model.predict_generator(test_generator, steps=num_prediction_steps, verbose=1)\n"
310
     ]
311
    },
312
    {
313
     "name": "stdout",
314
     "output_type": "stream",
315
     "text": [
316
      "9/9 [==============================] - 30s 3s/step\n"
317
     ]
318
    }
319
   ],
320
   "source": [
321
    "# Get the number of test samples\n",
322
    "num_test_samples = test_generator.n\n",
323
    "\n",
324
    "# Calculate the number of steps for prediction\n",
325
    "num_prediction_steps = num_test_samples // test_generator.batch_size + 1\n",
326
    "\n",
327
    "# Generate predictions for all test samples\n",
328
    "vgg19_predictions = vgg19_model.predict_generator(test_generator, steps=num_prediction_steps, verbose=1)\n",
329
    "\n",
330
    "# Convert predictions to class labels\n",
331
    "vgg19_predicted_labels = np.argmax(vgg19_predictions, axis=1)"
332
   ]
333
  },
334
  {
335
   "cell_type": "code",
336
   "execution_count": 17,
337
   "id": "c1afa985",
338
   "metadata": {},
339
   "outputs": [],
340
   "source": [
341
    "# Get true class labels\n",
342
    "true_labels = test_generator.classes"
343
   ]
344
  },
345
  {
346
   "cell_type": "code",
347
   "execution_count": 18,
348
   "id": "5900fa6e",
349
   "metadata": {},
350
   "outputs": [],
351
   "source": [
352
    "# Calculate classification report\n",
353
    "vgg16_report = classification_report(true_labels, vgg16_predicted_labels)"
354
   ]
355
  },
356
  {
357
   "cell_type": "code",
358
   "execution_count": 19,
359
   "id": "67dfb41f",
360
   "metadata": {},
361
   "outputs": [],
362
   "source": [
363
    "# Calculate classification report\n",
364
    "from sklearn.metrics import classification_report\n",
365
    "\n",
366
    "# Get the ground truth labels\n",
367
    "ground_truth_labels = test_generator.classes\n",
368
    "\n",
369
    "# Get the predicted labels\n",
370
    "vgg19_predicted_labels = np.argmax(vgg19_predictions, axis=1)\n",
371
    "\n",
372
    "# Calculate classification report\n",
373
    "classification_report_vgg19 = classification_report(ground_truth_labels, vgg19_predicted_labels, zero_division=1)"
374
   ]
375
  },
376
  {
377
   "cell_type": "code",
378
   "execution_count": 20,
379
   "id": "3e69c923",
380
   "metadata": {},
381
   "outputs": [
382
    {
383
     "name": "stdout",
384
     "output_type": "stream",
385
     "text": [
386
      "vgg16 Classification Report:\n",
387
      "              precision    recall  f1-score   support\n",
388
      "\n",
389
      "           0       0.95      0.99      0.97       140\n",
390
      "           1       0.99      0.94      0.96       140\n",
391
      "\n",
392
      "    accuracy                           0.96       280\n",
393
      "   macro avg       0.97      0.96      0.96       280\n",
394
      "weighted avg       0.97      0.96      0.96       280\n",
395
      "\n",
396
      "vgg19 Classification Report:\n",
397
      "              precision    recall  f1-score   support\n",
398
      "\n",
399
      "           0       0.87      0.99      0.93       140\n",
400
      "           1       0.98      0.86      0.92       140\n",
401
      "\n",
402
      "    accuracy                           0.92       280\n",
403
      "   macro avg       0.93      0.92      0.92       280\n",
404
      "weighted avg       0.93      0.92      0.92       280\n",
405
      "\n"
406
     ]
407
    }
408
   ],
409
   "source": [
410
    "print(\"vgg16 Classification Report:\")\n",
411
    "print(vgg16_report)\n",
412
    "\n",
413
    "print(\"vgg19 Classification Report:\")\n",
414
    "print(classification_report_vgg19)"
415
   ]
416
  },
417
  {
418
   "cell_type": "code",
419
   "execution_count": null,
420
   "id": "b52bd648",
421
   "metadata": {},
422
   "outputs": [
423
    {
424
     "name": "stdout",
425
     "output_type": "stream",
426
     "text": [
427
      "Epoch 1/5\n",
428
      "30/30 [==============================] - 608s 21s/step - loss: 0.1287 - accuracy: 0.9599\n",
429
      "Epoch 2/5\n",
430
      "30/30 [==============================] - 802s 27s/step - loss: 0.1328 - accuracy: 0.9620\n",
431
      "Epoch 3/5\n",
432
      "15/30 [==============>...............] - ETA: 6:36 - loss: 0.0728 - accuracy: 0.9854"
433
     ]
434
    }
435
   ],
436
   "source": [
437
    "import matplotlib.pyplot as plt\n",
438
    "\n",
439
    "# Train the VGG16 model and obtain the training history\n",
440
    "vgg16_history = vgg16_model.fit(train_generator, steps_per_epoch=train_generator.n // train_generator.batch_size, epochs=5)\n",
441
    "\n",
442
    "# Plot the training loss curve\n",
443
    "plt.plot(vgg16_history.history['loss'])\n",
444
    "plt.title('vgg16 Training Loss')\n",
445
    "plt.xlabel('Epoch')\n",
446
    "plt.ylabel('Loss')\n",
447
    "plt.show()"
448
   ]
449
  },
450
  {
451
   "cell_type": "code",
452
   "execution_count": null,
453
   "id": "5f87edd6",
454
   "metadata": {},
455
   "outputs": [],
456
   "source": [
457
    "import matplotlib.pyplot as plt\n",
458
    "\n",
459
    "# Train the VGG16 model and obtain the training history\n",
460
    "vgg19_history = vgg19_model.fit(train_generator, steps_per_epoch=train_generator.n // train_generator.batch_size, epochs=10)\n",
461
    "\n",
462
    "# Plot the training loss curve\n",
463
    "plt.plot(vgg19_history.history['loss'])\n",
464
    "plt.title('vgg19 Training Loss')\n",
465
    "plt.xlabel('Epoch')\n",
466
    "plt.ylabel('Loss')\n",
467
    "plt.show()"
468
   ]
469
  },
470
  {
471
   "cell_type": "code",
472
   "execution_count": null,
473
   "id": "f66c546c",
474
   "metadata": {},
475
   "outputs": [],
476
   "source": [
477
    "plt.plot(vgg16_history.history['accuracy'])\n",
478
    "plt.title('VGG16 Training Accuracy')\n",
479
    "plt.xlabel('Epoch')\n",
480
    "plt.ylabel('Accuracy')\n",
481
    "plt.show()"
482
   ]
483
  },
484
  {
485
   "cell_type": "code",
486
   "execution_count": null,
487
   "id": "ba32e996",
488
   "metadata": {},
489
   "outputs": [],
490
   "source": [
491
    "plt.plot(vgg19_history.history['accuracy'])\n",
492
    "plt.title('VGG19 Training Accuracy')\n",
493
    "plt.xlabel('Epoch')\n",
494
    "plt.ylabel('Accuracy')\n",
495
    "plt.show()"
496
   ]
497
  },
498
  {
499
   "cell_type": "code",
500
   "execution_count": null,
501
   "id": "b3533667",
502
   "metadata": {},
503
   "outputs": [],
504
   "source": []
505
  }
506
 ],
507
 "metadata": {
508
  "kernelspec": {
509
   "display_name": "Python 3 (ipykernel)",
510
   "language": "python",
511
   "name": "python3"
512
  },
513
  "language_info": {
514
   "codemirror_mode": {
515
    "name": "ipython",
516
    "version": 3
517
   },
518
   "file_extension": ".py",
519
   "mimetype": "text/x-python",
520
   "name": "python",
521
   "nbconvert_exporter": "python",
522
   "pygments_lexer": "ipython3",
523
   "version": "3.9.13"
524
  }
525
 },
526
 "nbformat": 4,
527
 "nbformat_minor": 5
528
}