{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": { "_cell_guid": "b1076dfc-b9ad-4769-8c92-a6c4dae69d19", "_uuid": "8f2839f25d086af736a60e9eeb907d3b93b6e0e5", "execution": { "iopub.execute_input": "2023-04-05T10:18:06.607800Z", "iopub.status.busy": "2023-04-05T10:18:06.607363Z", "iopub.status.idle": "2023-04-05T10:18:17.442048Z", "shell.execute_reply": "2023-04-05T10:18:17.440985Z", "shell.execute_reply.started": "2023-04-05T10:18:06.607708Z" } }, "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd\n", "import matplotlib.pyplot as plt\n", "import seaborn as sns\n", "import skimage.io\n", "import tensorflow\n", "import glob\n", "import tqdm\n", "import cv2\n", "from tqdm import tqdm\n", "\n", "from skimage.io import imread, imshow\n", "from skimage.transform import resize\n", "\n", "from tensorflow.keras.preprocessing.image import ImageDataGenerator\n", "from tensorflow.keras.applications.vgg16 import VGG16\n", "from tensorflow.keras.layers import InputLayer, Dense, BatchNormalization, Dropout, Flatten, Activation\n", "from tensorflow.keras.models import Sequential\n", "from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint\n", "from tensorflow.keras.preprocessing.image import load_img, img_to_array\n", "import torch\n", "from sklearn.metrics import accuracy_score, confusion_matrix, classification_report\n", "%matplotlib inline" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-04-05T10:18:17.445317Z", "iopub.status.busy": "2023-04-05T10:18:17.444560Z", "iopub.status.idle": "2023-04-05T10:18:17.817676Z", "shell.execute_reply": "2023-04-05T10:18:17.816556Z", "shell.execute_reply.started": "2023-04-05T10:18:17.445259Z" } }, "outputs": [], "source": [ "train_normal = glob.glob('data_small/chest-xray-pneumonia/chest_xray/train/NORMAL/*.jpeg')\n", "a = len(train_normal)\n", "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Code other" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-04-05T10:18:17.820239Z", "iopub.status.busy": "2023-04-05T10:18:17.819570Z", "iopub.status.idle": "2023-04-05T10:18:18.104917Z", "shell.execute_reply": "2023-04-05T10:18:18.103937Z", "shell.execute_reply.started": "2023-04-05T10:18:17.820200Z" } }, "outputs": [], "source": [ "train_pneumonia = glob.glob('data_small/chest-xray-pneumonia/chest_xray/train/PNEUMONIA/*.jpeg')\n", "b = len(train_pneumonia)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-04-05T10:18:18.108254Z", "iopub.status.busy": "2023-04-05T10:18:18.107570Z", "iopub.status.idle": "2023-04-05T10:18:18.115183Z", "shell.execute_reply": "2023-04-05T10:18:18.114145Z", "shell.execute_reply.started": "2023-04-05T10:18:18.108213Z" } }, "outputs": [], "source": [ "print(\"Total nos. of training images are: {}\".format(a + b))" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "execution": { "iopub.execute_input": "2023-04-05T10:18:18.120784Z", "iopub.status.busy": "2023-04-05T10:18:18.119787Z", "iopub.status.idle": "2023-04-05T10:18:18.127376Z", "shell.execute_reply": "2023-04-05T10:18:18.126331Z", "shell.execute_reply.started": "2023-04-05T10:18:18.120751Z" } }, "outputs": [], "source": [ "train_datagen = ImageDataGenerator(rescale = 1.0 / 255.0,\n", " zoom_range = 0.4,\n", " validation_split = 0.2)\n", "\n", "valid_datagen = ImageDataGenerator(rescale = 1.0 / 255.0,\n", " validation_split = 0.2)\n", "\n", "test_datagen = ImageDataGenerator(rescale = 1.0 / 255.0)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "execution": { "iopub.execute_input": "2023-04-05T10:18:18.129958Z", "iopub.status.busy": "2023-04-05T10:18:18.128743Z", "iopub.status.idle": "2023-04-05T10:18:22.573195Z", "shell.execute_reply": "2023-04-05T10:18:22.572009Z", "shell.execute_reply.started": "2023-04-05T10:18:18.129920Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found 422 images belonging to 2 classes.\n" ] } ], "source": [ "train_dataset = train_datagen.flow_from_directory(directory = 'data_small/chest-xray-pneumonia/chest_xray/train',\n", " target_size = (224,224),\n", " class_mode = 'binary',\n", " subset = 'training',\n", " batch_size = 64)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "execution": { "iopub.execute_input": "2023-04-05T10:18:22.576329Z", "iopub.status.busy": "2023-04-05T10:18:22.575200Z", "iopub.status.idle": "2023-04-05T10:18:23.626462Z", "shell.execute_reply": "2023-04-05T10:18:23.625318Z", "shell.execute_reply.started": "2023-04-05T10:18:22.576259Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found 105 images belonging to 2 classes.\n" ] } ], "source": [ "valid_dataset = valid_datagen.flow_from_directory(directory = 'data_small/chest-xray-pneumonia/chest_xray/train',\n", " target_size = (224,224),\n", " class_mode = 'binary',\n", " subset = 'validation',\n", " batch_size = 64)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-04-05T10:18:23.629025Z", "iopub.status.busy": "2023-04-05T10:18:23.628340Z", "iopub.status.idle": "2023-04-05T10:18:23.636803Z", "shell.execute_reply": "2023-04-05T10:18:23.635450Z", "shell.execute_reply.started": "2023-04-05T10:18:23.628982Z" } }, "outputs": [], "source": [ "train_dataset.class_indices" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-04-05T10:18:23.639332Z", "iopub.status.busy": "2023-04-05T10:18:23.638869Z", "iopub.status.idle": "2023-04-05T10:18:23.646306Z", "shell.execute_reply": "2023-04-05T10:18:23.645111Z", "shell.execute_reply.started": "2023-04-05T10:18:23.639294Z" } }, "outputs": [], "source": [ "from pathlib import Path" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-04-05T10:18:23.648339Z", "iopub.status.busy": "2023-04-05T10:18:23.647951Z", "iopub.status.idle": "2023-04-05T10:18:23.657485Z", "shell.execute_reply": "2023-04-05T10:18:23.656337Z", "shell.execute_reply.started": "2023-04-05T10:18:23.648302Z" } }, "outputs": [], "source": [ "data_dir = Path('data_small/chest-xray-pneumonia/chest_xray')\n", "test_dir = data_dir / 'test'" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-04-05T10:18:23.659988Z", "iopub.status.busy": "2023-04-05T10:18:23.659233Z", "iopub.status.idle": "2023-04-05T10:18:23.669765Z", "shell.execute_reply": "2023-04-05T10:18:23.668763Z", "shell.execute_reply.started": "2023-04-05T10:18:23.659953Z" } }, "outputs": [], "source": [ "\n", "normal_cases_dir = test_dir / 'NORMAL'\n", "pneumonia_cases_dir = test_dir / 'PNEUMONIA'\n", "\n", "normal_cases = normal_cases_dir.glob('*.jpeg')\n", "pneumonia_cases = pneumonia_cases_dir.glob('*.jpeg')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 5, "metadata": { "execution": { "iopub.execute_input": "2023-04-05T10:18:23.671809Z", "iopub.status.busy": "2023-04-05T10:18:23.671149Z", "iopub.status.idle": "2023-04-05T10:18:32.059237Z", "shell.execute_reply": "2023-04-05T10:18:32.058118Z", "shell.execute_reply.started": "2023-04-05T10:18:23.671775Z" } }, "outputs": [], "source": [ "# Defining Model\n", "\n", "base_model = VGG16(input_shape=(224,224,3), \n", " include_top=False,\n", " weights=\"imagenet\")" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "execution": { "iopub.execute_input": "2023-04-05T10:18:32.061048Z", "iopub.status.busy": "2023-04-05T10:18:32.060675Z", "iopub.status.idle": "2023-04-05T10:18:32.067441Z", "shell.execute_reply": "2023-04-05T10:18:32.066183Z", "shell.execute_reply.started": "2023-04-05T10:18:32.061009Z" } }, "outputs": [], "source": [ "for layer in base_model.layers:\n", " layer.trainable=False" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-04-05T10:18:32.075338Z", "iopub.status.busy": "2023-04-05T10:18:32.074331Z", "iopub.status.idle": "2023-04-05T10:18:32.085477Z", "shell.execute_reply": "2023-04-05T10:18:32.084451Z", "shell.execute_reply.started": "2023-04-05T10:18:32.075298Z" } }, "outputs": [], "source": [ "base_model.summary()" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "execution": { "iopub.execute_input": "2023-04-05T10:18:32.087621Z", "iopub.status.busy": "2023-04-05T10:18:32.087063Z", "iopub.status.idle": "2023-04-05T10:18:32.225814Z", "shell.execute_reply": "2023-04-05T10:18:32.224768Z", "shell.execute_reply.started": "2023-04-05T10:18:32.087580Z" } }, "outputs": [], "source": [ "# Defining Layers\n", "\n", "model=Sequential()\n", "model.add(base_model)\n", "model.add(Dropout(0.2))\n", "model.add(Flatten())\n", "model.add(BatchNormalization())\n", "model.add(Dense(1024,kernel_initializer='he_uniform'))\n", "model.add(BatchNormalization())\n", "model.add(Activation('relu'))\n", "model.add(Dropout(0.2))\n", "model.add(Dense(1024,kernel_initializer='he_uniform'))\n", "model.add(BatchNormalization())\n", "model.add(Activation('relu'))\n", "model.add(Dropout(0.2))\n", "\n", "model.add(Dense(1,activation='sigmoid'))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-04-05T10:18:32.227852Z", "iopub.status.busy": "2023-04-05T10:18:32.227448Z", "iopub.status.idle": "2023-04-05T10:18:32.236828Z", "shell.execute_reply": "2023-04-05T10:18:32.235608Z", "shell.execute_reply.started": "2023-04-05T10:18:32.227804Z" } }, "outputs": [], "source": [ "model.summary()" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "execution": { "iopub.execute_input": "2023-04-05T10:18:32.239629Z", "iopub.status.busy": "2023-04-05T10:18:32.238822Z", "iopub.status.idle": "2023-04-05T10:18:32.259834Z", "shell.execute_reply": "2023-04-05T10:18:32.258924Z", "shell.execute_reply.started": "2023-04-05T10:18:32.239593Z" } }, "outputs": [], "source": [ "# Model Compile \n", "\n", "OPT = tensorflow.keras.optimizers.Adam(learning_rate=0.001)\n", "\n", "model.compile(loss='binary_crossentropy',\n", " metrics=[tensorflow.keras.metrics.AUC(name = 'auc')],\n", " optimizer=OPT)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "execution": { "iopub.execute_input": "2023-04-05T10:18:32.262881Z", "iopub.status.busy": "2023-04-05T10:18:32.262172Z", "iopub.status.idle": "2023-04-05T10:18:32.269164Z", "shell.execute_reply": "2023-04-05T10:18:32.267925Z", "shell.execute_reply.started": "2023-04-05T10:18:32.262846Z" } }, "outputs": [], "source": [ "# Defining Callbacks\n", "\n", "filepath = 'data_small/best_weights.keras'\n", "\n", "earlystopping = EarlyStopping(monitor = 'val_auc', \n", " mode = 'max' , \n", " patience = 3,\n", " verbose = 1)\n", "\n", "checkpoint = ModelCheckpoint(filepath, \n", " monitor = 'val_auc', \n", " mode='max', \n", " save_best_only=True, \n", " verbose = 1)\n", "\n", "\n", "callback_list = [earlystopping, checkpoint]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " model_history = model.load('Janos_Scan')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 10, "metadata": { "execution": { "iopub.execute_input": "2023-04-05T10:18:32.271157Z", "iopub.status.busy": "2023-04-05T10:18:32.270637Z", "iopub.status.idle": "2023-04-05T10:21:23.872556Z", "shell.execute_reply": "2023-04-05T10:21:23.871478Z", "shell.execute_reply.started": "2023-04-05T10:18:32.271122Z" } }, "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[1m7/7\u001b[0m \u001b[32m━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[37m\u001b[0m \u001b[1m0s\u001b[0m 6s/step - auc: 0.8211 - loss: 0.5703\n", "Epoch 1: val_auc improved from -inf to 0.97200, saving model to data_small/best_weights.keras\n", "\u001b[1m7/7\u001b[0m \u001b[32m━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[37m\u001b[0m \u001b[1m92s\u001b[0m 12s/step - auc: 0.8283 - loss: 0.5611 - val_auc: 0.9720 - val_loss: 0.5673\n" ] } ], "source": [ "\n", "model_history=model.fit(train_dataset,\n", " validation_data=valid_dataset,\n", " epochs = 1,\n", " callbacks = callback_list,\n", " verbose = 1)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "execution": { "iopub.execute_input": "2023-04-05T10:21:23.875033Z", "iopub.status.busy": "2023-04-05T10:21:23.874599Z", "iopub.status.idle": "2023-04-05T10:21:23.882659Z", "shell.execute_reply": "2023-04-05T10:21:23.881414Z", "shell.execute_reply.started": "2023-04-05T10:21:23.874990Z" } }, "outputs": [], "source": [ "class_names = ['PNEUMONIA','NORMAL']" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "execution": { "iopub.execute_input": "2023-04-05T10:32:34.305363Z", "iopub.status.busy": "2023-04-05T10:32:34.304982Z", "iopub.status.idle": "2023-04-05T10:32:35.479938Z", "shell.execute_reply": "2023-04-05T10:32:35.476824Z", "shell.execute_reply.started": "2023-04-05T10:32:34.305331Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\u001b[1m2/2\u001b[0m \u001b[32m━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[37m\u001b[0m \u001b[1m7s\u001b[0m 3s/step\n", " precision recall f1-score support\n", "\n", " PNEUMONIA 0.2656 1.0000 0.4198 17\n", " NORMAL 0.0000 0.0000 0.0000 47\n", "\n", " accuracy 0.2656 64\n", " macro avg 0.1328 0.5000 0.2099 64\n", "weighted avg 0.0706 0.2656 0.1115 64\n", "\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/usr/local/lib/python3.10/dist-packages/sklearn/metrics/_classification.py:1344: UndefinedMetricWarning: Precision and F-score are ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n", " _warn_prf(average, modifier, msg_start, len(result))\n", "/usr/local/lib/python3.10/dist-packages/sklearn/metrics/_classification.py:1344: UndefinedMetricWarning: Precision and F-score are ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n", " _warn_prf(average, modifier, msg_start, len(result))\n", "/usr/local/lib/python3.10/dist-packages/sklearn/metrics/_classification.py:1344: UndefinedMetricWarning: Precision and F-score are ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.\n", " _warn_prf(average, modifier, msg_start, len(result))\n" ] } ], "source": [ "from sklearn.metrics import classification_report, confusion_matrix\n", "import seaborn as sns\n", "\n", "prediction_classes = np.array([])\n", "true_classes = np.array([])\n", "\n", "# for x, y in valid_dataset:\n", "for i, (x, y) in enumerate(valid_dataset):\n", " if i >= 1: # stop after 1 batch\n", " break\n", " \n", " # fix ---- type and shape mismatch\n", "# prediction_classes = np.concatenate([prediction_classes,\n", "# np.argmax(model.predict(x), axis = -1)])\n", "# true_classes = np.concatenate([true_classes, np.argmax(y.numpy(), axis=-1)])\n", "\n", " prediction_classes = np.concatenate([prediction_classes, \n", " np.atleast_1d(np.argmax(model.predict(x), axis=-1))])\n", " true_classes = np.concatenate([true_classes, y])\n", "\n", "print(classification_report(true_classes, prediction_classes, target_names=class_names, digits=4))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.status.busy": "2023-04-05T10:21:24.245188Z", "iopub.status.idle": "2023-04-05T10:21:24.246046Z", "shell.execute_reply": "2023-04-05T10:21:24.245788Z", "shell.execute_reply.started": "2023-04-05T10:21:24.245758Z" } }, "outputs": [], "source": [ "from keras.utils import plot_model" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.status.busy": "2023-04-05T10:21:24.247585Z", "iopub.status.idle": "2023-04-05T10:21:24.248394Z", "shell.execute_reply": "2023-04-05T10:21:24.248114Z", "shell.execute_reply.started": "2023-04-05T10:21:24.248086Z" } }, "outputs": [], "source": [ "plot_model(model, to_file='model_plot.png', show_shapes=True, show_layer_names=True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.status.busy": "2023-04-05T10:21:24.249866Z", "iopub.status.idle": "2023-04-05T10:21:24.250685Z", "shell.execute_reply": "2023-04-05T10:21:24.250412Z", "shell.execute_reply.started": "2023-04-05T10:21:24.250384Z" } }, "outputs": [], "source": [ "\n", "plt.plot(model_history.history['loss'])\n", "plt.plot(model_history.history['val_loss'])\n", "plt.title('Model Loss')\n", "plt.ylabel('Loss')\n", "plt.xlabel('Epoch')\n", "plt.legend(['Train', 'Validation'], loc='upper left', bbox_to_anchor=(1,1))\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.status.busy": "2023-04-05T10:21:24.252178Z", "iopub.status.idle": "2023-04-05T10:21:24.253051Z", "shell.execute_reply": "2023-04-05T10:21:24.252731Z", "shell.execute_reply.started": "2023-04-05T10:21:24.252702Z" } }, "outputs": [], "source": [ "plt.plot(model_history.history['auc'])\n", "plt.plot(model_history.history['val_auc'])\n", "plt.title('Model AUC')\n", "plt.ylabel('AUC')\n", "plt.xlabel('Epoch')\n", "plt.legend(['Train', 'Validation'], loc='upper left', bbox_to_anchor=(1,1))\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.status.busy": "2023-04-05T10:21:24.254567Z", "iopub.status.idle": "2023-04-05T10:21:24.255417Z", "shell.execute_reply": "2023-04-05T10:21:24.255118Z", "shell.execute_reply.started": "2023-04-05T10:21:24.255090Z" } }, "outputs": [], "source": [ "test_dataset = test_datagen.flow_from_directory(directory = 'data_small/chest-xray-pneumonia/chest_xray/test',\n", " target_size = (224,224),\n", " class_mode = 'binary',\n", " batch_size = 64)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.status.busy": "2023-04-05T10:21:24.256869Z", "iopub.status.idle": "2023-04-05T10:21:24.257685Z", "shell.execute_reply": "2023-04-05T10:21:24.257383Z", "shell.execute_reply.started": "2023-04-05T10:21:24.257356Z" } }, "outputs": [], "source": [ "\n", "normal_cases_dir = test_dir / 'NORMAL'\n", "pneumonia_cases_dir = test_dir / 'PNEUMONIA'\n", "\n", "normal_cases = normal_cases_dir.glob('*.jpeg')\n", "pneumonia_cases = pneumonia_cases_dir.glob('*.jpeg')\n", "test_labels=[]\n", "test_data= []\n", "for img in normal_cases:\n", " img = cv2.imread(str(img))\n", " img = cv2.resize(img, (224,224))\n", " if img.shape[2]==1:\n", " img = np.dstack([img,img,img])\n", " else:\n", " img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n", " img = img.astype(np.float32)/225.\n", " \n", " label = tensorflow.keras.utils.to_categorical(0,num_classes=2)\n", " test_labels.append(label)\n", " test_data.append(img)\n", "for img in pneumonia_cases:\n", " \n", " img = cv2.imread(str(img))\n", " img = cv2.resize(img, (224,224))\n", " if img.shape[2]==1:\n", " img = np.dstack([img,img,img])\n", " else:\n", " img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n", " img = img.astype(np.float32)/225.\n", " \n", " label = tensorflow.keras.utils.to_categorical(1,num_classes=2)\n", " test_labels.append(label)\n", " test_data.append(img)\n", " \n", "test_data = np.array(test_data)\n", "test_labels = np.array(test_labels)\n", "print(test_data.shape)\n", "print(test_labels.shape)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.status.busy": "2023-04-05T10:21:24.259124Z", "iopub.status.idle": "2023-04-05T10:21:24.259883Z", "shell.execute_reply": "2023-04-05T10:21:24.259643Z", "shell.execute_reply.started": "2023-04-05T10:21:24.259617Z" } }, "outputs": [], "source": [ "test_loss, test_score = model.evaluate(test_data, test_labels, batch_size=16)\n", "print(test_loss)\n", "print(test_score)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.status.busy": "2023-04-05T10:21:24.261323Z", "iopub.status.idle": "2023-04-05T10:21:24.262137Z", "shell.execute_reply": "2023-04-05T10:21:24.261878Z", "shell.execute_reply.started": "2023-04-05T10:21:24.261850Z" } }, "outputs": [], "source": [ "preds = model.predict(test_data,batch_size=16)\n", "preds = np.argmax(preds,axis=-1)\n", "\n", "orig_test_labels= np.argmax(test_labels,axis=-1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.status.busy": "2023-04-05T10:21:24.263594Z", "iopub.status.idle": "2023-04-05T10:21:24.264368Z", "shell.execute_reply": "2023-04-05T10:21:24.264088Z", "shell.execute_reply.started": "2023-04-05T10:21:24.264062Z" } }, "outputs": [], "source": [ "print(orig_test_labels.shape)\n", "print(preds.shape)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.status.busy": "2023-04-05T10:21:24.265811Z", "iopub.status.idle": "2023-04-05T10:21:24.266536Z", "shell.execute_reply": "2023-04-05T10:21:24.266296Z", "shell.execute_reply.started": "2023-04-05T10:21:24.266257Z" } }, "outputs": [], "source": [ "test_score =model.evaluate(test_dataset)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.status.busy": "2023-04-05T10:21:24.267868Z", "iopub.status.idle": "2023-04-05T10:21:24.268636Z", "shell.execute_reply": "2023-04-05T10:21:24.268382Z", "shell.execute_reply.started": "2023-04-05T10:21:24.268357Z" } }, "outputs": [], "source": [ "from mlxtend.plotting import plot_confusion_matrix" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.status.busy": "2023-04-05T10:21:24.270000Z", "iopub.status.idle": "2023-04-05T10:21:24.270780Z", "shell.execute_reply": "2023-04-05T10:21:24.270518Z", "shell.execute_reply.started": "2023-04-05T10:21:24.270493Z" } }, "outputs": [], "source": [ "cm = confusion_matrix(orig_test_labels, preds)\n", "plt.figure()\n", "plot_confusion_matrix(cm, figsize = (12,8),hide_ticks = True,cmap = plt.cm.Blues)\n", "plt.xticks(range(2),['Normal','Pneumonia'],fontsize=16)\n", "plt.yticks(range(2),['Normal','Pneumonia'],fontsize=16)\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "cm" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.status.busy": "2023-04-05T10:21:24.272213Z", "iopub.status.idle": "2023-04-05T10:21:24.272977Z", "shell.execute_reply": "2023-04-05T10:21:24.272737Z", "shell.execute_reply.started": "2023-04-05T10:21:24.272712Z" } }, "outputs": [], "source": [ "# Test Case 1: NORMAL\n", "\n", "dic = test_dataset.class_indices\n", "idc = {k:v for v, k in dic.items()}\n", "\n", "img = load_img('data_small/chest-xray-pneumonia/chest_xray/test/NORMAL/IM-0035-0001.jpeg', target_size=(224,224))\n", "img = img_to_array(img)\n", "img = img/255\n", "imshow(img)\n", "plt.axis('off')\n", "img = np.expand_dims(img,axis=0)\n", "predict_prob=model.predict(img)\n", "print(model.predict(img))\n", "print(predict_prob)\n", "\n", "\n", "if predict_prob.all()> 0.5:\n", " print(\"The X-Ray belongs to PNEUMONIA person\")\n", "else:\n", " print(\"The X-RAY belongs to NORMAL person\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.status.busy": "2023-04-05T10:21:24.274451Z", "iopub.status.idle": "2023-04-05T10:21:24.275264Z", "shell.execute_reply": "2023-04-05T10:21:24.275001Z", "shell.execute_reply.started": "2023-04-05T10:21:24.274973Z" } }, "outputs": [], "source": [ "# Test Case 2: PNEUMONIA\n", "\n", "dic = test_dataset.class_indices\n", "idc = {k:v for v, k in dic.items()}\n", "\n", "img = load_img('data_small/chest-xray-pneumonia/chest_xray/test/PNEUMONIA/person91_bacteria_449.jpeg', target_size=(224,224))\n", "img = img_to_array(img)\n", "img = img/255\n", "imshow(img)\n", "plt.axis('off')\n", "img = np.expand_dims(img,axis=0)\n", "predict_prob=model.predict(img)\n", "print(predict_prob)\n", "\n", "\n", "if predict_prob> 0.5:\n", " print(\"The X-Ray belongs to PNEUMONIA person\")\n", "else:\n", " print(\"The X-RAY belongs to NORMAL person\")" ] } ], "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 }