Datasets:
ArXiv:
DOI:
License:
File size: 29,965 Bytes
0eae2d5 ba37a6c 0eae2d5 ba37a6c 0eae2d5 ba37a6c 0eae2d5 ba37a6c 0eae2d5 ba37a6c 0eae2d5 ba37a6c 0eae2d5 ba37a6c 0eae2d5 ba37a6c 0eae2d5 ba37a6c 0eae2d5 ba37a6c 0eae2d5 ba37a6c 0eae2d5 ba37a6c 0eae2d5 ba37a6c 0eae2d5 ba37a6c 0eae2d5 ba37a6c 0eae2d5 ba37a6c 0eae2d5 ba37a6c 0eae2d5 |
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 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Import Dependencies"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-17T09:41:40.536537Z",
"iopub.status.busy": "2023-04-17T09:41:40.536081Z",
"iopub.status.idle": "2023-04-17T09:41:49.139653Z",
"shell.execute_reply": "2023-04-17T09:41:49.138560Z",
"shell.execute_reply.started": "2023-04-17T09:41:40.536503Z"
}
},
"outputs": [],
"source": [
"import os\n",
"import tensorflow as tf\n",
"from tensorflow.keras.applications.vgg19 import VGG19\n",
"from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2\n",
"from tensorflow.keras.applications.vgg19 import preprocess_input as vgg19_preprocess_input\n",
"from tensorflow.keras.applications.mobilenet_v2 import preprocess_input as mobilenetv2_preprocess_input\n",
"from tensorflow.keras.layers import GlobalAveragePooling2D\n",
"from tensorflow.keras.models import Sequential, Model\n",
"from tensorflow.keras.layers import Dense, Dropout, Flatten, Input, Average, concatenate\n",
"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n",
"from keras.optimizers import Adam\n",
"from keras.callbacks import EarlyStopping, ModelCheckpoint\n",
"\n",
"\n",
"\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from sklearn.metrics import classification_report, confusion_matrix, ConfusionMatrixDisplay, roc_curve, auc\n",
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, matthews_corrcoef"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-17T09:41:57.227573Z",
"iopub.status.busy": "2023-04-17T09:41:57.226671Z",
"iopub.status.idle": "2023-04-17T09:41:57.232218Z",
"shell.execute_reply": "2023-04-17T09:41:57.231311Z",
"shell.execute_reply.started": "2023-04-17T09:41:57.227527Z"
}
},
"outputs": [],
"source": [
"np.random.seed(123)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-17T09:42:04.651926Z",
"iopub.status.busy": "2023-04-17T09:42:04.651342Z",
"iopub.status.idle": "2023-04-17T09:42:04.887346Z",
"shell.execute_reply": "2023-04-17T09:42:04.885924Z",
"shell.execute_reply.started": "2023-04-17T09:42:04.651876Z"
}
},
"outputs": [],
"source": [
"data_dir = 'data_small/CovidDataset_70_30'"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-17T09:42:10.895108Z",
"iopub.status.busy": "2023-04-17T09:42:10.894738Z",
"iopub.status.idle": "2023-04-17T09:42:10.900686Z",
"shell.execute_reply": "2023-04-17T09:42:10.899576Z",
"shell.execute_reply.started": "2023-04-17T09:42:10.895076Z"
}
},
"outputs": [],
"source": [
"batch_size = 32\n",
"input_shape = (224, 224, 3)\n",
"num_classes = 2"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-17T09:42:15.424140Z",
"iopub.status.busy": "2023-04-17T09:42:15.423768Z",
"iopub.status.idle": "2023-04-17T09:42:21.502085Z",
"shell.execute_reply": "2023-04-17T09:42:21.500720Z",
"shell.execute_reply.started": "2023-04-17T09:42:15.424110Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Found 6 images belonging to 2 classes.\n",
"Found 6 images belonging to 2 classes.\n",
"Found 6 images belonging to 2 classes.\n"
]
}
],
"source": [
"train_datagen = ImageDataGenerator(rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True)\n",
"test_datagen = ImageDataGenerator(rescale=1./255)\n",
"validation_datagen = ImageDataGenerator(rescale=1./255)\n",
"\n",
"\n",
"train_generator = train_datagen.flow_from_directory(\n",
" os.path.join(data_dir, 'Train'),\n",
" target_size=input_shape[:2],\n",
" batch_size=batch_size,\n",
" class_mode='categorical')\n",
"\n",
"test_generator = test_datagen.flow_from_directory(\n",
" os.path.join(data_dir, 'Test'),\n",
" target_size=input_shape[:2],\n",
" batch_size=batch_size,\n",
" class_mode='categorical')\n",
"\n",
"validation_generator = validation_datagen.flow_from_directory(\n",
" os.path.join(data_dir, 'Validation'),\n",
" target_size=input_shape[:2],\n",
" batch_size=batch_size,\n",
" class_mode='categorical')"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-17T09:42:26.625792Z",
"iopub.status.busy": "2023-04-17T09:42:26.625206Z",
"iopub.status.idle": "2023-04-17T09:42:30.568898Z",
"shell.execute_reply": "2023-04-17T09:42:30.568063Z",
"shell.execute_reply.started": "2023-04-17T09:42:26.625744Z"
}
},
"outputs": [],
"source": [
"vgg19 = VGG19(weights='imagenet', include_top=False, input_shape=input_shape)\n",
"\n",
"modelV19 = Sequential()\n",
"modelV19.add(vgg19)\n",
"modelV19.add(Flatten())\n",
"modelV19.add(Dense(500, activation='relu'))\n",
"modelV19.add(Dropout(0.5))\n",
"modelV19.add(Dense(300, activation='relu'))\n",
"modelV19.add(Dropout(0.5))\n",
"modelV19.add(Dense(num_classes, activation='softmax'))\n",
"\n",
"for layer in vgg19.layers:\n",
" layer.trainable = False\n",
"# modelV19.summary()"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-17T09:42:34.683488Z",
"iopub.status.busy": "2023-04-17T09:42:34.683094Z",
"iopub.status.idle": "2023-04-17T09:42:36.570959Z",
"shell.execute_reply": "2023-04-17T09:42:36.570095Z",
"shell.execute_reply.started": "2023-04-17T09:42:34.683453Z"
}
},
"outputs": [],
"source": [
"mobilenetv2 = MobileNetV2(weights='imagenet', include_top=False, input_shape=input_shape)\n",
"\n",
"modelM2 = Sequential()\n",
"modelM2.add(mobilenetv2)\n",
"modelM2.add(Flatten())\n",
"modelM2.add(Dense(500, activation='relu'))\n",
"modelM2.add(Dropout(0.5))\n",
"modelM2.add(Dense(300, activation='relu'))\n",
"modelM2.add(Dropout(0.5))\n",
"modelM2.add(Dense(num_classes, activation='softmax'))\n",
"\n",
"for layer in mobilenetv2.layers:\n",
" layer.trainable = False\n",
" \n",
"# modelM2.summary()"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-17T09:43:03.856636Z",
"iopub.status.busy": "2023-04-17T09:43:03.856068Z",
"iopub.status.idle": "2023-04-17T09:43:03.885436Z",
"shell.execute_reply": "2023-04-17T09:43:03.884427Z",
"shell.execute_reply.started": "2023-04-17T09:43:03.856598Z"
}
},
"outputs": [],
"source": [
"opt = Adam(learning_rate=0.0001, beta_1=0.9)\n",
"opt2 = Adam(learning_rate=0.0001, beta_1=0.9) # fix for reproducing and fixing purposes, need a new optimizer instance\n",
"modelV19.compile(\n",
" loss='binary_crossentropy',\n",
" optimizer=opt,\n",
" metrics=['accuracy'])\n",
"\n",
"modelM2.compile(\n",
" loss='binary_crossentropy',\n",
" optimizer=opt2,\n",
" metrics=['accuracy'])\n",
"\n",
"early_stop = EarlyStopping(monitor='val_loss', patience=10)\n",
"filepath_weights_V19 = \"data_small/best_weights_V19-{epoch:02d}-{val_accuracy:.4f}.keras\"\n",
"filepath_weights_M2 = \"data_small/best_weights_M2-{epoch:02d}-{val_accuracy:.4f}.keras\"\n",
"checkpoint_V19 = ModelCheckpoint(filepath_weights_V19, monitor='val_accuracy', mode='max', verbose=1, save_best_only=True)\n",
"checkpoint_M2 = ModelCheckpoint(filepath_weights_M2, monitor='val_accuracy', mode='max', verbose=1, save_best_only=True)\n"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-17T09:43:08.944492Z",
"iopub.status.busy": "2023-04-17T09:43:08.943733Z",
"iopub.status.idle": "2023-04-17T10:48:55.062928Z",
"shell.execute_reply": "2023-04-17T10:48:55.061828Z",
"shell.execute_reply.started": "2023-04-17T09:43:08.944452Z"
}
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/usr/local/lib/python3.10/dist-packages/keras/src/trainers/data_adapters/py_dataset_adapter.py:121: UserWarning: Your `PyDataset` class should call `super().__init__(**kwargs)` in its constructor. `**kwargs` can include `workers`, `use_multiprocessing`, `max_queue_size`. Do not pass these arguments to `fit()`, as they will be ignored.\n",
" self._warn_if_super_not_called()\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[1m1/1\u001b[0m \u001b[32mββββββββββββββββββββ\u001b[0m\u001b[37m\u001b[0m \u001b[1m0s\u001b[0m 3s/step - accuracy: 0.6667 - loss: 0.5391\n",
"Epoch 1: val_accuracy improved from -inf to 0.50000, saving model to data_small/best_weights_V19-01-0.5000.keras\n",
"\u001b[1m1/1\u001b[0m \u001b[32mββββββββββββββββββββ\u001b[0m\u001b[37m\u001b[0m \u001b[1m17s\u001b[0m 17s/step - accuracy: 0.6667 - loss: 0.5391 - val_accuracy: 0.5000 - val_loss: 0.6312\n"
]
}
],
"source": [
"# Dont run again model is saved @ /kaggle/working/save_weights/best_weights_V19-47-0.9566.hdf5\n",
"\n",
"history_V19 = modelV19.fit(train_generator, epochs=1, validation_data=validation_generator, callbacks=[early_stop, checkpoint_V19])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-17T10:54:11.760570Z",
"iopub.status.busy": "2023-04-17T10:54:11.759474Z",
"iopub.status.idle": "2023-04-17T10:54:12.009812Z",
"shell.execute_reply": "2023-04-17T10:54:12.008839Z",
"shell.execute_reply.started": "2023-04-17T10:54:11.760531Z"
}
},
"outputs": [],
"source": [
"plt.plot(history_V19.history['accuracy'])\n",
"plt.plot(history_V19.history['val_accuracy'])\n",
"plt.title('model accuracy')\n",
"plt.ylabel('accuracy')\n",
"plt.xlabel('epoch')\n",
"plt.legend(['Train', 'Validation'], loc='upper left')\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-17T10:54:15.949718Z",
"iopub.status.busy": "2023-04-17T10:54:15.949333Z",
"iopub.status.idle": "2023-04-17T10:54:16.169299Z",
"shell.execute_reply": "2023-04-17T10:54:16.168308Z",
"shell.execute_reply.started": "2023-04-17T10:54:15.949687Z"
}
},
"outputs": [],
"source": [
"plt.plot(history_V19.history['loss'])\n",
"plt.plot(history_V19.history['val_loss'])\n",
"plt.title('model loss')\n",
"plt.ylabel('loss')\n",
"plt.xlabel('epoch')\n",
"plt.legend(['Train', 'Validation'], loc='upper right')\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-17T10:54:22.915426Z",
"iopub.status.busy": "2023-04-17T10:54:22.914443Z",
"iopub.status.idle": "2023-04-17T11:58:44.293631Z",
"shell.execute_reply": "2023-04-17T11:58:44.292681Z",
"shell.execute_reply.started": "2023-04-17T10:54:22.915379Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[1m1/1\u001b[0m \u001b[32mββββββββββββββββββββ\u001b[0m\u001b[37m\u001b[0m \u001b[1m0s\u001b[0m 7s/step - accuracy: 0.6667 - loss: 0.9756\n",
"Epoch 1: val_accuracy improved from -inf to 0.83333, saving model to data_small/best_weights_M2-01-0.8333.keras\n",
"\u001b[1m1/1\u001b[0m \u001b[32mββββββββββββββββββββ\u001b[0m\u001b[37m\u001b[0m \u001b[1m30s\u001b[0m 30s/step - accuracy: 0.6667 - loss: 0.9756 - val_accuracy: 0.8333 - val_loss: 0.5959\n"
]
}
],
"source": [
"# Dont run again model is saved @ /kaggle/working/save_weights/best_weights_M2-49-0.9681.hdf5\n",
"history_M2 = modelM2.fit(train_generator, epochs=1, validation_data=validation_generator, callbacks=[early_stop, checkpoint_M2])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-17T11:58:56.255321Z",
"iopub.status.busy": "2023-04-17T11:58:56.254959Z",
"iopub.status.idle": "2023-04-17T11:58:56.470983Z",
"shell.execute_reply": "2023-04-17T11:58:56.469412Z",
"shell.execute_reply.started": "2023-04-17T11:58:56.255288Z"
}
},
"outputs": [],
"source": [
"plt.plot(history_M2.history['accuracy'])\n",
"plt.plot(history_M2.history['val_accuracy'])\n",
"plt.title('model accuracy')\n",
"plt.ylabel('accuracy')\n",
"plt.xlabel('epoch')\n",
"plt.legend(['Train', 'Validation'], loc='upper left')\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-17T11:59:04.035960Z",
"iopub.status.busy": "2023-04-17T11:59:04.034979Z",
"iopub.status.idle": "2023-04-17T11:59:04.239444Z",
"shell.execute_reply": "2023-04-17T11:59:04.238312Z",
"shell.execute_reply.started": "2023-04-17T11:59:04.035921Z"
}
},
"outputs": [],
"source": [
"plt.plot(history_M2.history['loss'])\n",
"plt.plot(history_M2.history['val_loss'])\n",
"plt.title('model loss')\n",
"plt.ylabel('loss')\n",
"plt.xlabel('epoch')\n",
"plt.legend(['Train', 'Validation'], loc='upper right')\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-17T12:00:59.573944Z",
"iopub.status.busy": "2023-04-17T12:00:59.573208Z",
"iopub.status.idle": "2023-04-17T12:01:03.871274Z",
"shell.execute_reply": "2023-04-17T12:01:03.870051Z",
"shell.execute_reply.started": "2023-04-17T12:00:59.573904Z"
}
},
"outputs": [],
"source": [
"from tensorflow.keras.models import Model, load_model\n",
"from tensorflow.keras.layers import Input, Average\n",
"\n",
"# fix for reproducing and fixing purposes - because the best model names maybe different every running and they are hardcoded now\n",
"# model_1 = load_model('/kaggle/working/save_weights/best_weights_V19-47-0.9566.hdf5')\n",
"# model_2 = load_model('/kaggle/working/save_weights/best_weights_M2-49-0.9681.hdf5')\n",
"\n",
"# # Set layers in model_1 and model_2 to be not trainable\n",
"# for layer in model_1.layers:\n",
"# layer.trainable = False\n",
"\n",
"# for layer in model_2.layers:\n",
"# layer.trainable = False\n",
" \n",
" \n",
"# model_1 = Model(\n",
"# inputs = model_1.inputs,\n",
"# outputs = model_1.outputs,\n",
"# name = \"VGG16\"\n",
"# )\n",
"\n",
"# model_2 = Model(\n",
"# inputs = model_2.inputs,\n",
"# outputs = model_2.outputs,\n",
"# name = \"MobileNetV2\"\n",
"# )\n",
"\n",
"# models = [model_1,model_2]\n",
"models = [modelV19, modelM2]\n",
"# fix ends\n",
"\n",
"model_input = Input(shape=(224, 224, 3))\n",
"model_outputs = [model(model_input) for model in models]\n",
"\n",
"ensemble_output = Average()(model_outputs)\n",
"\n",
"\n",
"ensemble_model = Model(\n",
" inputs = model_input,\n",
" outputs = ensemble_output,\n",
" name = \"Ensemble\"\n",
")\n",
"\n",
"# ensemble_model.summary()"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-17T12:07:00.234155Z",
"iopub.status.busy": "2023-04-17T12:07:00.233683Z",
"iopub.status.idle": "2023-04-17T12:07:00.250703Z",
"shell.execute_reply": "2023-04-17T12:07:00.249691Z",
"shell.execute_reply.started": "2023-04-17T12:07:00.234119Z"
}
},
"outputs": [],
"source": [
"opt3 = Adam(learning_rate=0.0001, beta_1=0.9) # fix for reproducing and fixing purposes, need a new optimizer instance\n",
"# only compile when there are trainable parameters\n",
"ensemble_model.compile(\n",
" loss='binary_crossentropy',\n",
" optimizer=opt3,\n",
" metrics=['accuracy'])\n",
"\n",
"filepath_weights_ensemble = \"data_small/best_weights_ensemble-{epoch:02d}-{val_accuracy:.4f}.keras\"\n",
"checkpoint_ensemble = ModelCheckpoint(filepath_weights_ensemble, monitor='val_accuracy', mode='max', verbose=1, save_best_only=True)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[1m1/1\u001b[0m \u001b[32mββββββββββββββββββββ\u001b[0m\u001b[37m\u001b[0m \u001b[1m0s\u001b[0m 7s/step - accuracy: 0.6667 - loss: 0.0000e+00\n",
"Epoch 1: val_accuracy improved from -inf to 0.83333, saving model to data_small/best_weights_ensemble-01-0.8333.keras\n",
"\u001b[1m1/1\u001b[0m \u001b[32mββββββββββββββββββββ\u001b[0m\u001b[37m\u001b[0m \u001b[1m64s\u001b[0m 64s/step - accuracy: 0.6667 - loss: 0.0000e+00 - val_accuracy: 0.8333 - val_loss: 0.0000e+00\n"
]
}
],
"source": [
"# only fit when there are trainable parameters\n",
"history_ensemble = ensemble_model.fit(train_generator, epochs=1, validation_data=validation_generator, callbacks=[early_stop, checkpoint_ensemble])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.plot(history_ensemble.history['accuracy'])\n",
"plt.plot(history_ensemble.history['val_accuracy'])\n",
"plt.title('model accuracy')\n",
"plt.ylabel('accuracy')\n",
"plt.xlabel('epoch')\n",
"plt.legend(['Train', 'Validation'], loc='upper left')\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-16T20:45:19.559073Z",
"iopub.status.busy": "2023-04-16T20:45:19.558228Z",
"iopub.status.idle": "2023-04-16T20:45:19.791401Z",
"shell.execute_reply": "2023-04-16T20:45:19.790386Z",
"shell.execute_reply.started": "2023-04-16T20:45:19.559021Z"
}
},
"outputs": [],
"source": [
"plt.plot(history_ensemble.history['loss'])\n",
"plt.plot(history_ensemble.history['val_loss'])\n",
"plt.title('model loss')\n",
"plt.ylabel('loss')\n",
"plt.xlabel('epoch')\n",
"plt.legend(['Train', 'Validation'], loc='upper right')\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-17T12:14:59.727959Z",
"iopub.status.busy": "2023-04-17T12:14:59.727593Z",
"iopub.status.idle": "2023-04-17T12:15:21.928598Z",
"shell.execute_reply": "2023-04-17T12:15:21.927416Z",
"shell.execute_reply.started": "2023-04-17T12:14:59.727921Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[1m1/1\u001b[0m \u001b[32mββββββββββββββββββββ\u001b[0m\u001b[37m\u001b[0m \u001b[1m1s\u001b[0m 912ms/step - accuracy: 1.0000 - loss: 0.0000e+00\n"
]
},
{
"data": {
"text/plain": [
"[0.0, 0.0, 1.0, 0.0, 1.0, 1.0]"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# ensemble_model.load_weights('/kaggle/working/save_weights/best_weights_ensemble-01-0.9752.tf')\n",
"# test_loss, test_acc = ensemble_model.evaluate(test_generator)\n",
"# print('Test accuracy:', test_acc)\n",
"ensemble_model.evaluate(test_generator)"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-17T12:20:24.753793Z",
"iopub.status.busy": "2023-04-17T12:20:24.753072Z",
"iopub.status.idle": "2023-04-17T12:20:30.445796Z",
"shell.execute_reply": "2023-04-17T12:20:30.444541Z",
"shell.execute_reply.started": "2023-04-17T12:20:24.753754Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[1m1/1\u001b[0m \u001b[32mββββββββββββββββββββ\u001b[0m\u001b[37m\u001b[0m \u001b[1m2s\u001b[0m 2s/step\n",
"One-hot encoded predicted labels:\n",
"[[0.6766326 0.32336748]\n",
" [0.13196638 0.8680336 ]\n",
" [0.61891085 0.38108918]\n",
" [0.07593525 0.92406476]\n",
" [0.11446559 0.88553447]\n",
" [0.7296946 0.27030542]]\n",
"[0 1 0 1 1 0]\n"
]
}
],
"source": [
"y_pred = ensemble_model.predict(test_generator)\n",
"print(\"One-hot encoded predicted labels:\")\n",
"print(y_pred)\n",
"y_pred_classes = np.argmax(y_pred, axis=1)\n",
"print(y_pred_classes)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-17T12:21:13.115475Z",
"iopub.status.busy": "2023-04-17T12:21:13.114275Z"
}
},
"outputs": [],
"source": [
"y_true_classes = np.argmax(test_generator.classes, axis=1)"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-17T12:16:41.235043Z",
"iopub.status.busy": "2023-04-17T12:16:41.234321Z",
"iopub.status.idle": "2023-04-17T12:16:51.671202Z",
"shell.execute_reply": "2023-04-17T12:16:51.669596Z",
"shell.execute_reply.started": "2023-04-17T12:16:41.235004Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[1m1/1\u001b[0m \u001b[32mββββββββββββββββββββ\u001b[0m\u001b[37m\u001b[0m \u001b[1m1s\u001b[0m 850ms/step\n"
]
}
],
"source": [
"#ensemble_model.load_weights('/kaggle/working/save_weights/best_weights_ensemble-31-0.9690.tf')\n",
"#y_pred = ensemble_model.predict(test_generator)\n",
"#y_pred_classes = np.argmax(y_pred, axis=1)\n",
"#y_true_classes = test_generator.classes\n",
"\n",
"#try this \n",
"# Make predictions on test data\n",
"y_pred = ensemble_model.predict(test_generator)\n",
"y_pred_classes = np.argmax(y_pred, axis=1)\n",
"\n",
"# Convert one-hot encoded labels to integer labels\n",
"y_true_onehot = test_generator.classes\n",
"\n",
"# fix: it is unnessesary to convert once more\n",
"# y_true_classes = np.argmax(y_true_onehot, axis=1)\n",
"y_true_classes = y_true_onehot "
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-16T20:46:57.948345Z",
"iopub.status.busy": "2023-04-16T20:46:57.947965Z",
"iopub.status.idle": "2023-04-16T20:46:57.96196Z",
"shell.execute_reply": "2023-04-16T20:46:57.960524Z",
"shell.execute_reply.started": "2023-04-16T20:46:57.948309Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Classification Report:\n",
" precision recall f1-score support\n",
"\n",
" 0 0.33 0.33 0.33 3\n",
" 1 0.33 0.33 0.33 3\n",
"\n",
" accuracy 0.33 6\n",
" macro avg 0.33 0.33 0.33 6\n",
"weighted avg 0.33 0.33 0.33 6\n",
"\n"
]
}
],
"source": [
"print(\"Classification Report:\\n\",classification_report(y_true_classes, y_pred_classes))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-16T20:47:05.00894Z",
"iopub.status.busy": "2023-04-16T20:47:05.008561Z",
"iopub.status.idle": "2023-04-16T20:47:05.027339Z",
"shell.execute_reply": "2023-04-16T20:47:05.026235Z",
"shell.execute_reply.started": "2023-04-16T20:47:05.008906Z"
}
},
"outputs": [],
"source": [
"# Calculate confusion matrix\n",
"cm = confusion_matrix(y_true_classes, y_pred_classes)\n",
"\n",
"# Extract TP, TN, FP, FN\n",
"TP = cm[1, 1]\n",
"TN = cm[0, 0]\n",
"FP = cm[0, 1]\n",
"FN = cm[1, 0]\n",
"\n",
"# Calculate specificity\n",
"specificity = TN / (TN + FP)\n",
"\n",
"# Calculate sensitivity\n",
"sensitivity = TP / (TP + FN)\n",
"\n",
"# Calculate accuracy\n",
"accuracy = accuracy_score(y_true_classes, y_pred_classes)\n",
"\n",
"# Calculate precision\n",
"precision = precision_score(y_true_classes, y_pred_classes)\n",
"\n",
"# Calculate false positive rate (FPR)\n",
"FPR = FP / (FP + TN)\n",
"\n",
"# Calculate false negative rate (FNR)\n",
"FNR = FN / (FN + TP)\n",
"\n",
"# Calculate negative predictive value (NPV)\n",
"NPV = TN / (TN + FN)\n",
"\n",
"# Calculate false discovery rate (FDR)\n",
"FDR = FP / (FP + TP)\n",
"\n",
"# Calculate F1 score\n",
"f1_score = f1_score(y_true_classes, y_pred_classes)\n",
"\n",
"# Calculate Matthews correlation coefficient (MCC)\n",
"mcc = matthews_corrcoef(y_true_classes, y_pred_classes)\n",
"\n",
"# Print the metrics\n",
"print(\"Evaluation Metrics -\\n\")\n",
"print(\"Specificity: \", specificity)\n",
"print(\"Sensitivity: \", sensitivity)\n",
"print(\"Accuracy: \", accuracy)\n",
"print(\"Precision: \", precision)\n",
"print(\"FPR: \", FPR)\n",
"print(\"FNR: \", FNR)\n",
"print(\"NPV: \", NPV)\n",
"print(\"FDR: \", FDR)\n",
"print(\"F1 Score: \", f1_score)\n",
"print(\"MCC: \", mcc)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-16T20:47:09.888885Z",
"iopub.status.busy": "2023-04-16T20:47:09.887905Z",
"iopub.status.idle": "2023-04-16T20:47:10.150365Z",
"shell.execute_reply": "2023-04-16T20:47:10.148887Z",
"shell.execute_reply.started": "2023-04-16T20:47:09.888846Z"
}
},
"outputs": [],
"source": [
"print(ConfusionMatrixDisplay.from_predictions(y_true_classes, y_pred_classes))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-16T20:47:18.289352Z",
"iopub.status.busy": "2023-04-16T20:47:18.288971Z",
"iopub.status.idle": "2023-04-16T20:47:18.504488Z",
"shell.execute_reply": "2023-04-16T20:47:18.503453Z",
"shell.execute_reply.started": "2023-04-16T20:47:18.289316Z"
}
},
"outputs": [],
"source": [
"# Assuming you have binary classification with two classes, you can adjust accordingly for multi-class\n",
"fpr, tpr, _ = roc_curve(test_generator.classes, y_pred[:, 1]) # Use y_pred[:, 1] for positive class predictions\n",
"roc_auc = auc(fpr, tpr)\n",
"\n",
"# Plot ROC curve for positive class\n",
"plt.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc)\n",
"plt.xlabel('False Positive Rate')\n",
"plt.ylabel('True Positive Rate')\n",
"plt.title('Receiver Operating Characteristic')\n",
"plt.legend(loc=\"lower right\")\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"execution": {
"iopub.execute_input": "2023-04-16T20:47:33.750456Z",
"iopub.status.busy": "2023-04-16T20:47:33.749346Z",
"iopub.status.idle": "2023-04-16T20:47:35.93496Z",
"shell.execute_reply": "2023-04-16T20:47:35.934049Z",
"shell.execute_reply.started": "2023-04-16T20:47:33.750376Z"
}
},
"outputs": [],
"source": [
"test_images, test_labels = next(test_generator)\n",
"test_pred = ensemble_model.predict(test_images)\n",
"\n",
"fig, axes = plt.subplots(nrows=4, ncols=4, figsize=(10,10))\n",
"for i, ax in enumerate(axes.flat):\n",
" # Plot image\n",
" ax.imshow(test_images[i])\n",
"\n",
" # Set the title\n",
" if test_pred[i][0] > 0.5:\n",
" title = f'COVID ({test_pred[i][0]:.2f})'\n",
" else:\n",
" title = f'Non-COVID ({test_pred[i][0]:.2f})'\n",
" ax.set_title(title)\n",
"\n",
" # Remove ticks from the plot\n",
" ax.set_xticks([])\n",
" ax.set_yticks([])"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"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.12"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
|