{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport skimage.io\nimport tensorflow\nimport glob\nimport tqdm\nimport cv2\nfrom tqdm import tqdm\n\nfrom skimage.io import imread, imshow\nfrom skimage.transform import resize\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications.vgg16 import VGG16\nfrom tensorflow.keras.layers import InputLayer, Dense, BatchNormalization, Dropout, Flatten, Activation\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom tensorflow.keras.preprocessing.image import load_img, img_to_array\nimport torch\nfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_report\n%matplotlib inline","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-04-05T10:18:06.607363Z","iopub.execute_input":"2023-04-05T10:18:06.607800Z","iopub.status.idle":"2023-04-05T10:18:17.442048Z","shell.execute_reply.started":"2023-04-05T10:18:06.607708Z","shell.execute_reply":"2023-04-05T10:18:17.440985Z"},"trusted":true},"execution_count":1,"outputs":[]},{"cell_type":"code","source":"train_normal = glob.glob('/kaggle/input/chest-xray-pneumonia/chest_xray/train/NORMAL/*.jpeg')\na = len(train_normal)\n23","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:18:17.444560Z","iopub.execute_input":"2023-04-05T10:18:17.445317Z","iopub.status.idle":"2023-04-05T10:18:17.817676Z","shell.execute_reply.started":"2023-04-05T10:18:17.445259Z","shell.execute_reply":"2023-04-05T10:18:17.816556Z"},"trusted":true},"execution_count":2,"outputs":[{"execution_count":2,"output_type":"execute_result","data":{"text/plain":"23"},"metadata":{}}]},{"cell_type":"markdown","source":"Code other","metadata":{}},{"cell_type":"code","source":"train_pneumonia = glob.glob('/kaggle/input/chest-xray-pneumonia/chest_xray/train/PNEUMONIA/*.jpeg')\nb = len(train_pneumonia)","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:18:17.819570Z","iopub.execute_input":"2023-04-05T10:18:17.820239Z","iopub.status.idle":"2023-04-05T10:18:18.104917Z","shell.execute_reply.started":"2023-04-05T10:18:17.820200Z","shell.execute_reply":"2023-04-05T10:18:18.103937Z"},"trusted":true},"execution_count":3,"outputs":[]},{"cell_type":"code","source":"print(\"Total nos. of training images are: {}\".format(a + b))","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:18:18.107570Z","iopub.execute_input":"2023-04-05T10:18:18.108254Z","iopub.status.idle":"2023-04-05T10:18:18.115183Z","shell.execute_reply.started":"2023-04-05T10:18:18.108213Z","shell.execute_reply":"2023-04-05T10:18:18.114145Z"},"trusted":true},"execution_count":4,"outputs":[{"name":"stdout","text":"Total nos. of training images are: 5216\n","output_type":"stream"}]},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(rescale = 1.0 / 255.0,\n zoom_range = 0.4,\n validation_split = 0.2)\n\nvalid_datagen = ImageDataGenerator(rescale = 1.0 / 255.0,\n validation_split = 0.2)\n\ntest_datagen = ImageDataGenerator(rescale = 1.0 / 255.0)","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:18:18.119787Z","iopub.execute_input":"2023-04-05T10:18:18.120784Z","iopub.status.idle":"2023-04-05T10:18:18.127376Z","shell.execute_reply.started":"2023-04-05T10:18:18.120751Z","shell.execute_reply":"2023-04-05T10:18:18.126331Z"},"trusted":true},"execution_count":5,"outputs":[]},{"cell_type":"code","source":"train_dataset = train_datagen.flow_from_directory(directory = '/kaggle/input/chest-xray-pneumonia/chest_xray/train',\n target_size = (224,224),\n class_mode = 'binary',\n subset = 'training',\n batch_size = 64)","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:18:18.128743Z","iopub.execute_input":"2023-04-05T10:18:18.129958Z","iopub.status.idle":"2023-04-05T10:18:22.573195Z","shell.execute_reply.started":"2023-04-05T10:18:18.129920Z","shell.execute_reply":"2023-04-05T10:18:22.572009Z"},"trusted":true},"execution_count":6,"outputs":[{"name":"stdout","text":"Found 4173 images belonging to 2 classes.\n","output_type":"stream"}]},{"cell_type":"code","source":"valid_dataset = valid_datagen.flow_from_directory(directory = '/kaggle/input/chest-xray-pneumonia/chest_xray/train',\n target_size = (224,224),\n class_mode = 'binary',\n subset = 'validation',\n batch_size = 64)","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:18:22.575200Z","iopub.execute_input":"2023-04-05T10:18:22.576329Z","iopub.status.idle":"2023-04-05T10:18:23.626462Z","shell.execute_reply.started":"2023-04-05T10:18:22.576259Z","shell.execute_reply":"2023-04-05T10:18:23.625318Z"},"trusted":true},"execution_count":7,"outputs":[{"name":"stdout","text":"Found 1043 images belonging to 2 classes.\n","output_type":"stream"}]},{"cell_type":"code","source":"train_dataset.class_indices","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:18:23.628340Z","iopub.execute_input":"2023-04-05T10:18:23.629025Z","iopub.status.idle":"2023-04-05T10:18:23.636803Z","shell.execute_reply.started":"2023-04-05T10:18:23.628982Z","shell.execute_reply":"2023-04-05T10:18:23.635450Z"},"trusted":true},"execution_count":8,"outputs":[{"execution_count":8,"output_type":"execute_result","data":{"text/plain":"{'NORMAL': 0, 'PNEUMONIA': 1}"},"metadata":{}}]},{"cell_type":"code","source":"from pathlib import Path","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:18:23.638869Z","iopub.execute_input":"2023-04-05T10:18:23.639332Z","iopub.status.idle":"2023-04-05T10:18:23.646306Z","shell.execute_reply.started":"2023-04-05T10:18:23.639294Z","shell.execute_reply":"2023-04-05T10:18:23.645111Z"},"trusted":true},"execution_count":9,"outputs":[]},{"cell_type":"code","source":"data_dir = Path('/kaggle/input/chest-xray-pneumonia/chest_xray')\ntest_dir = data_dir / 'test'","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:18:23.647951Z","iopub.execute_input":"2023-04-05T10:18:23.648339Z","iopub.status.idle":"2023-04-05T10:18:23.657485Z","shell.execute_reply.started":"2023-04-05T10:18:23.648302Z","shell.execute_reply":"2023-04-05T10:18:23.656337Z"},"trusted":true},"execution_count":10,"outputs":[]},{"cell_type":"code","source":"\nnormal_cases_dir = test_dir / 'NORMAL'\npneumonia_cases_dir = test_dir / 'PNEUMONIA'\n\nnormal_cases = normal_cases_dir.glob('*.jpeg')\npneumonia_cases = pneumonia_cases_dir.glob('*.jpeg')","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:18:23.659233Z","iopub.execute_input":"2023-04-05T10:18:23.659988Z","iopub.status.idle":"2023-04-05T10:18:23.669765Z","shell.execute_reply.started":"2023-04-05T10:18:23.659953Z","shell.execute_reply":"2023-04-05T10:18:23.668763Z"},"trusted":true},"execution_count":11,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Defining Model\n\nbase_model = VGG16(input_shape=(224,224,3), \n include_top=False,\n weights=\"imagenet\")","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:18:23.671149Z","iopub.execute_input":"2023-04-05T10:18:23.671809Z","iopub.status.idle":"2023-04-05T10:18:32.059237Z","shell.execute_reply.started":"2023-04-05T10:18:23.671775Z","shell.execute_reply":"2023-04-05T10:18:32.058118Z"},"trusted":true},"execution_count":12,"outputs":[{"name":"stdout","text":"Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/vgg16/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5\n58892288/58889256 [==============================] - 0s 0us/step\n58900480/58889256 [==============================] - 0s 0us/step\n","output_type":"stream"}]},{"cell_type":"code","source":"for layer in base_model.layers:\n layer.trainable=False","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:18:32.060675Z","iopub.execute_input":"2023-04-05T10:18:32.061048Z","iopub.status.idle":"2023-04-05T10:18:32.067441Z","shell.execute_reply.started":"2023-04-05T10:18:32.061009Z","shell.execute_reply":"2023-04-05T10:18:32.066183Z"},"trusted":true},"execution_count":13,"outputs":[]},{"cell_type":"code","source":"base_model.summary()","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:18:32.074331Z","iopub.execute_input":"2023-04-05T10:18:32.075338Z","iopub.status.idle":"2023-04-05T10:18:32.085477Z","shell.execute_reply.started":"2023-04-05T10:18:32.075298Z","shell.execute_reply":"2023-04-05T10:18:32.084451Z"},"trusted":true},"execution_count":14,"outputs":[{"name":"stdout","text":"Model: \"vgg16\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_1 (InputLayer) [(None, 224, 224, 3)] 0 \n_________________________________________________________________\nblock1_conv1 (Conv2D) (None, 224, 224, 64) 1792 \n_________________________________________________________________\nblock1_conv2 (Conv2D) (None, 224, 224, 64) 36928 \n_________________________________________________________________\nblock1_pool (MaxPooling2D) (None, 112, 112, 64) 0 \n_________________________________________________________________\nblock2_conv1 (Conv2D) (None, 112, 112, 128) 73856 \n_________________________________________________________________\nblock2_conv2 (Conv2D) (None, 112, 112, 128) 147584 \n_________________________________________________________________\nblock2_pool (MaxPooling2D) (None, 56, 56, 128) 0 \n_________________________________________________________________\nblock3_conv1 (Conv2D) (None, 56, 56, 256) 295168 \n_________________________________________________________________\nblock3_conv2 (Conv2D) (None, 56, 56, 256) 590080 \n_________________________________________________________________\nblock3_conv3 (Conv2D) (None, 56, 56, 256) 590080 \n_________________________________________________________________\nblock3_pool (MaxPooling2D) (None, 28, 28, 256) 0 \n_________________________________________________________________\nblock4_conv1 (Conv2D) (None, 28, 28, 512) 1180160 \n_________________________________________________________________\nblock4_conv2 (Conv2D) (None, 28, 28, 512) 2359808 \n_________________________________________________________________\nblock4_conv3 (Conv2D) (None, 28, 28, 512) 2359808 \n_________________________________________________________________\nblock4_pool (MaxPooling2D) (None, 14, 14, 512) 0 \n_________________________________________________________________\nblock5_conv1 (Conv2D) (None, 14, 14, 512) 2359808 \n_________________________________________________________________\nblock5_conv2 (Conv2D) (None, 14, 14, 512) 2359808 \n_________________________________________________________________\nblock5_conv3 (Conv2D) (None, 14, 14, 512) 2359808 \n_________________________________________________________________\nblock5_pool (MaxPooling2D) (None, 7, 7, 512) 0 \n=================================================================\nTotal params: 14,714,688\nTrainable params: 0\nNon-trainable params: 14,714,688\n_________________________________________________________________\n","output_type":"stream"}]},{"cell_type":"code","source":"# Defining Layers\n\nmodel=Sequential()\nmodel.add(base_model)\nmodel.add(Dropout(0.2))\nmodel.add(Flatten())\nmodel.add(BatchNormalization())\nmodel.add(Dense(1024,kernel_initializer='he_uniform'))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(1024,kernel_initializer='he_uniform'))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.2))\n\nmodel.add(Dense(1,activation='sigmoid'))","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:18:32.087063Z","iopub.execute_input":"2023-04-05T10:18:32.087621Z","iopub.status.idle":"2023-04-05T10:18:32.225814Z","shell.execute_reply.started":"2023-04-05T10:18:32.087580Z","shell.execute_reply":"2023-04-05T10:18:32.224768Z"},"trusted":true},"execution_count":15,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:18:32.227448Z","iopub.execute_input":"2023-04-05T10:18:32.227852Z","iopub.status.idle":"2023-04-05T10:18:32.236828Z","shell.execute_reply.started":"2023-04-05T10:18:32.227804Z","shell.execute_reply":"2023-04-05T10:18:32.235608Z"},"trusted":true},"execution_count":16,"outputs":[{"name":"stdout","text":"Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nvgg16 (Functional) (None, 7, 7, 512) 14714688 \n_________________________________________________________________\ndropout (Dropout) (None, 7, 7, 512) 0 \n_________________________________________________________________\nflatten (Flatten) (None, 25088) 0 \n_________________________________________________________________\nbatch_normalization (BatchNo (None, 25088) 100352 \n_________________________________________________________________\ndense (Dense) (None, 1024) 25691136 \n_________________________________________________________________\nbatch_normalization_1 (Batch (None, 1024) 4096 \n_________________________________________________________________\nactivation (Activation) (None, 1024) 0 \n_________________________________________________________________\ndropout_1 (Dropout) (None, 1024) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 1024) 1049600 \n_________________________________________________________________\nbatch_normalization_2 (Batch (None, 1024) 4096 \n_________________________________________________________________\nactivation_1 (Activation) (None, 1024) 0 \n_________________________________________________________________\ndropout_2 (Dropout) (None, 1024) 0 \n_________________________________________________________________\ndense_2 (Dense) (None, 1) 1025 \n=================================================================\nTotal params: 41,564,993\nTrainable params: 26,796,033\nNon-trainable params: 14,768,960\n_________________________________________________________________\n","output_type":"stream"}]},{"cell_type":"code","source":"# Model Compile \n\nOPT = tensorflow.keras.optimizers.Adam(learning_rate=0.001)\n\nmodel.compile(loss='binary_crossentropy',\n metrics=[tensorflow.keras.metrics.AUC(name = 'auc')],\n optimizer=OPT)","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:18:32.238822Z","iopub.execute_input":"2023-04-05T10:18:32.239629Z","iopub.status.idle":"2023-04-05T10:18:32.259834Z","shell.execute_reply.started":"2023-04-05T10:18:32.239593Z","shell.execute_reply":"2023-04-05T10:18:32.258924Z"},"trusted":true},"execution_count":17,"outputs":[]},{"cell_type":"code","source":"# Defining Callbacks\n\nfilepath = './best_weights.hdf5'\n\nearlystopping = EarlyStopping(monitor = 'val_auc', \n mode = 'max' , \n patience = 3,\n verbose = 1)\n\ncheckpoint = ModelCheckpoint(filepath, \n monitor = 'val_auc', \n mode='max', \n save_best_only=True, \n verbose = 1)\n\n\ncallback_list = [earlystopping, checkpoint]","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:18:32.262172Z","iopub.execute_input":"2023-04-05T10:18:32.262881Z","iopub.status.idle":"2023-04-05T10:18:32.269164Z","shell.execute_reply.started":"2023-04-05T10:18:32.262846Z","shell.execute_reply":"2023-04-05T10:18:32.267925Z"},"trusted":true},"execution_count":18,"outputs":[]},{"cell_type":"markdown","source":" model_history = model.load('Janos_Scan')","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nmodel_history=model.fit(train_dataset,\n validation_data=valid_dataset,\n epochs = 1,\n callbacks = callback_list,\n verbose = 1)","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:18:32.270637Z","iopub.execute_input":"2023-04-05T10:18:32.271157Z","iopub.status.idle":"2023-04-05T10:21:23.872556Z","shell.execute_reply.started":"2023-04-05T10:18:32.271122Z","shell.execute_reply":"2023-04-05T10:21:23.871478Z"},"trusted":true},"execution_count":19,"outputs":[{"name":"stdout","text":"66/66 [==============================] - 169s 2s/step - loss: 0.2360 - auc: 0.9619 - val_loss: 0.1553 - val_auc: 0.9911\n\nEpoch 00001: val_auc improved from -inf to 0.99106, saving model to ./best_weights.hdf5\n","output_type":"stream"}]},{"cell_type":"code","source":"class_names = ['PNEUMONIA','NORMAL']","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:21:23.874599Z","iopub.execute_input":"2023-04-05T10:21:23.875033Z","iopub.status.idle":"2023-04-05T10:21:23.882659Z","shell.execute_reply.started":"2023-04-05T10:21:23.874990Z","shell.execute_reply":"2023-04-05T10:21:23.881414Z"},"trusted":true},"execution_count":20,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import classification_report, confusion_matrix\nimport seaborn as sns\n\nprediction_classes = np.array([])\ntrue_classes = np.array([])\n\nfor x, y in valid_dataset:\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\nprint(classification_report(true_classes, prediction_classes, target_names=class_names, digits=4))","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:32:34.304982Z","iopub.execute_input":"2023-04-05T10:32:34.305363Z","iopub.status.idle":"2023-04-05T10:32:35.479938Z","shell.execute_reply.started":"2023-04-05T10:32:34.305331Z","shell.execute_reply":"2023-04-05T10:32:35.476824Z"},"trusted":true},"execution_count":25,"outputs":[{"traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)","\u001b[0;32m/tmp/ipykernel_23/3824881073.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 8\u001b[0m prediction_classes = np.concatenate([prediction_classes,\n\u001b[1;32m 9\u001b[0m np.argmax(model.predict(x), axis = -1)])\n\u001b[0;32m---> 10\u001b[0;31m \u001b[0mtrue_classes\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mconcatenate\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mtrue_classes\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0margmax\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0my\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mnparray\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0maxis\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 11\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 12\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;31mAttributeError\u001b[0m: 'numpy.ndarray' object has no attribute 'nparray'"],"ename":"AttributeError","evalue":"'numpy.ndarray' object has no attribute 'nparray'","output_type":"error"}]},{"cell_type":"code","source":"from keras.utils.vis_utils import plot_model","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:21:24.245188Z","iopub.status.idle":"2023-04-05T10:21:24.246046Z","shell.execute_reply.started":"2023-04-05T10:21:24.245758Z","shell.execute_reply":"2023-04-05T10:21:24.245788Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_model(model, to_file='model_plot.png', show_shapes=True, show_layer_names=True)","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:21:24.247585Z","iopub.status.idle":"2023-04-05T10:21:24.248394Z","shell.execute_reply.started":"2023-04-05T10:21:24.248086Z","shell.execute_reply":"2023-04-05T10:21:24.248114Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nplt.plot(model_history.history['loss'])\nplt.plot(model_history.history['val_loss'])\nplt.title('Model Loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Validation'], loc='upper left', bbox_to_anchor=(1,1))\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:21:24.249866Z","iopub.status.idle":"2023-04-05T10:21:24.250685Z","shell.execute_reply.started":"2023-04-05T10:21:24.250384Z","shell.execute_reply":"2023-04-05T10:21:24.250412Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(model_history.history['auc'])\nplt.plot(model_history.history['val_auc'])\nplt.title('Model AUC')\nplt.ylabel('AUC')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Validation'], loc='upper left', bbox_to_anchor=(1,1))\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:21:24.252178Z","iopub.status.idle":"2023-04-05T10:21:24.253051Z","shell.execute_reply.started":"2023-04-05T10:21:24.252702Z","shell.execute_reply":"2023-04-05T10:21:24.252731Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_dataset = test_datagen.flow_from_directory(directory = '/kaggle/input/chest-xray-pneumonia/chest_xray/test',\n target_size = (224,224),\n class_mode = 'binary',\n batch_size = 64)","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:21:24.254567Z","iopub.status.idle":"2023-04-05T10:21:24.255417Z","shell.execute_reply.started":"2023-04-05T10:21:24.255090Z","shell.execute_reply":"2023-04-05T10:21:24.255118Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nnormal_cases_dir = test_dir / 'NORMAL'\npneumonia_cases_dir = test_dir / 'PNEUMONIA'\n\nnormal_cases = normal_cases_dir.glob('*.jpeg')\npneumonia_cases = pneumonia_cases_dir.glob('*.jpeg')\ntest_labels=[]\ntest_data= []\nfor 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)\nfor 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 \ntest_data = np.array(test_data)\ntest_labels = np.array(test_labels)\nprint(test_data.shape)\nprint(test_labels.shape)","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:21:24.256869Z","iopub.status.idle":"2023-04-05T10:21:24.257685Z","shell.execute_reply.started":"2023-04-05T10:21:24.257356Z","shell.execute_reply":"2023-04-05T10:21:24.257383Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_loss, test_score = model.evaluate(test_data, test_labels, batch_size=16)\nprint(test_loss)\nprint(test_score)","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:21:24.259124Z","iopub.status.idle":"2023-04-05T10:21:24.259883Z","shell.execute_reply.started":"2023-04-05T10:21:24.259617Z","shell.execute_reply":"2023-04-05T10:21:24.259643Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"preds = model.predict(test_data,batch_size=16)\npreds = np.argmax(preds,axis=-1)\n\norig_test_labels= np.argmax(test_labels,axis=-1)","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:21:24.261323Z","iopub.status.idle":"2023-04-05T10:21:24.262137Z","shell.execute_reply.started":"2023-04-05T10:21:24.261850Z","shell.execute_reply":"2023-04-05T10:21:24.261878Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(orig_test_labels.shape)\nprint(preds.shape)","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:21:24.263594Z","iopub.status.idle":"2023-04-05T10:21:24.264368Z","shell.execute_reply.started":"2023-04-05T10:21:24.264062Z","shell.execute_reply":"2023-04-05T10:21:24.264088Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_score =model.evaluate(test_dataset)","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:21:24.265811Z","iopub.status.idle":"2023-04-05T10:21:24.266536Z","shell.execute_reply.started":"2023-04-05T10:21:24.266257Z","shell.execute_reply":"2023-04-05T10:21:24.266296Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from mlxtend.plotting import plot_confusion_matrix","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:21:24.267868Z","iopub.status.idle":"2023-04-05T10:21:24.268636Z","shell.execute_reply.started":"2023-04-05T10:21:24.268357Z","shell.execute_reply":"2023-04-05T10:21:24.268382Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cm = confusion_matrix(orig_test_labels, preds)\nplt.figure()\nplot_confusion_matrix(cm, figsize = (12,8),hide_ticks = True,cmap = plt.cm.Blues)\nplt.xticks(range(2),['Normal','Pneumonia'],fontsize=16)\nplt.yticks(range(2),['Normal','Pneumonia'],fontsize=16)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:21:24.270000Z","iopub.status.idle":"2023-04-05T10:21:24.270780Z","shell.execute_reply.started":"2023-04-05T10:21:24.270493Z","shell.execute_reply":"2023-04-05T10:21:24.270518Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Test Case 1: NORMAL\n\ndic = test_dataset.class_indices\nidc = {k:v for v, k in dic.items()}\n\nimg = load_img('/kaggle/input/chest-xray-pneumonia/chest_xray/test/NORMAL/IM-0033-0001.jpeg', target_size=(224,224))\nimg = img_to_array(img)\nimg = img/255\nimshow(img)\nplt.axis('off')\nimg = np.expand_dims(img,axis=0)\npredict_prob=model.predict(img)\nprint(model.predict(img))\nprint(predict_prob)\n\n\nif predict_prob.all()> 0.5:\n print(\"The X-Ray belongs to PNEUMONIA person\")\nelse:\n print(\"The X-RAY belongs to NORMAL person\")","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:21:24.272213Z","iopub.status.idle":"2023-04-05T10:21:24.272977Z","shell.execute_reply.started":"2023-04-05T10:21:24.272712Z","shell.execute_reply":"2023-04-05T10:21:24.272737Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Test Case 2: PNEUMONIA\n\ndic = test_dataset.class_indices\nidc = {k:v for v, k in dic.items()}\n\nimg = load_img('/kaggle/input/chest-xray-pneumonia/chest_xray/test/PNEUMONIA/person100_bacteria_475.jpeg', target_size=(224,224))\nimg = img_to_array(img)\nimg = img/255\nimshow(img)\nplt.axis('off')\nimg = np.expand_dims(img,axis=0)\npredict_prob=model.predict(img)\nprint(predict_prob)\n\n\nif predict_prob> 0.5:\n print(\"The X-Ray belongs to PNEUMONIA person\")\nelse:\n print(\"The X-RAY belongs to NORMAL person\")","metadata":{"execution":{"iopub.status.busy":"2023-04-05T10:21:24.274451Z","iopub.status.idle":"2023-04-05T10:21:24.275264Z","shell.execute_reply.started":"2023-04-05T10:21:24.274973Z","shell.execute_reply":"2023-04-05T10:21:24.275001Z"},"trusted":true},"execution_count":null,"outputs":[]}]}