{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":22307,"databundleVersionId":1502524,"sourceType":"competition"}],"dockerImageVersionId":30776,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport shutil\nimport pydicom\nimport matplotlib.pyplot as plt\nimport scipy.io\nimport numpy as np\nimport cv2\nfrom PIL import Image\nimport pandas as pd\nimport gc\nfrom tqdm import tqdm\n\n\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import applications\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping, ModelCheckpoint\nfrom tensorflow.keras.layers import Dense, Conv2D , MaxPool2D , Flatten , Dropout , BatchNormalization\n\nfrom sklearn.model_selection import RepeatedKFold, cross_val_score, train_test_split\nfrom sklearn.metrics import confusion_matrix, accuracy_score","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-04-29T19:14:59.176494Z","iopub.execute_input":"2025-04-29T19:14:59.177089Z","iopub.status.idle":"2025-04-29T19:15:20.802398Z","shell.execute_reply.started":"2025-04-29T19:14:59.177048Z","shell.execute_reply":"2025-04-29T19:15:20.801699Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ds = pydicom.dcmread(\"/kaggle/input/rsna-str-pulmonary-embolism-detection/train/0045f113e031/454c8fdfb649/0075a38c1940.dcm\")\ndcm_sample=ds.pixel_array.astype('float32')\nscaled_image = (np.maximum(dcm_sample, 0) / dcm_sample.max())\nplt.imshow(scaled_image)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T19:15:20.80435Z","iopub.execute_input":"2025-04-29T19:15:20.805195Z","iopub.status.idle":"2025-04-29T19:15:21.162933Z","shell.execute_reply.started":"2025-04-29T19:15:20.805153Z","shell.execute_reply":"2025-04-29T19:15:21.162097Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#not_noraml\ndf = pd.read_csv(\"/kaggle/input/rsna-str-pulmonary-embolism-detection/train.csv\")\ndf = df.loc[df[\"pe_present_on_image\"]==1,:].reset_index(drop=True)\nprint(len(df))\ndf.tail()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T19:15:21.164065Z","iopub.execute_input":"2025-04-29T19:15:21.164333Z","iopub.status.idle":"2025-04-29T19:15:24.223874Z","shell.execute_reply.started":"2025-04-29T19:15:21.164307Z","shell.execute_reply":"2025-04-29T19:15:24.223082Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#normal\ndf1 = pd.read_csv(\"/kaggle/input/rsna-str-pulmonary-embolism-detection/train.csv\")\ndf1 = df1.loc[(df1[\"pe_present_on_image\"] == 0) & (df1[\"negative_exam_for_pe\"] == 1) ,:].reset_index(drop=True)\nprint(len(df1))\ndf1.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T19:15:24.225071Z","iopub.execute_input":"2025-04-29T19:15:24.225448Z","iopub.status.idle":"2025-04-29T19:15:26.468065Z","shell.execute_reply.started":"2025-04-29T19:15:24.225409Z","shell.execute_reply":"2025-04-29T19:15:26.467165Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!mkdir /kaggle/data\n\n!mkdir /kaggle/data/train\n!mkdir /kaggle/data/valid\n!mkdir /kaggle/data/test\n\n!mkdir /kaggle/data/train/normal\n!mkdir /kaggle/data/train/not_normal\n\n!mkdir /kaggle/data/valid/normal\n!mkdir /kaggle/data/valid/not_normal\n\n!mkdir /kaggle/data/test/normal\n!mkdir /kaggle/data/test/not_normal","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T19:15:26.470246Z","iopub.execute_input":"2025-04-29T19:15:26.470511Z","iopub.status.idle":"2025-04-29T19:15:36.480588Z","shell.execute_reply.started":"2025-04-29T19:15:26.470485Z","shell.execute_reply":"2025-04-29T19:15:36.479318Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Train not_normal\nfor i in tqdm(range(10000)):\n    dcm = pydicom.dcmread(\"/kaggle/input/rsna-str-pulmonary-embolism-detection/train/\"+df.loc[i,'StudyInstanceUID']+'/'+df.loc[i,'SeriesInstanceUID']+'/'+df.loc[i,'SOPInstanceUID']+'.dcm')\n    dc_image=dcm.pixel_array.astype('float32')\n    #scaled_image = (np.maximum(dc_image, 0) / dc_image.max())\n    #scaled_image = np.reshape(scaled_image,(scaled_image.shape[0], scaled_image.shape[1], 1))\n    im = Image.fromarray(dc_image).convert('RGB').resize((256,256))  \n    im.save(\"/kaggle/data/train/not_normal/\"+str(i)+\".jpg\")\n    del dcm, dc_image, im\n    gc.collect()\n#     #ملخص:\n# الكود يقرأ صور DICOM من ملفات طبية.\n# يحول الصور إلى مصفوفة بكسلات، ثم يعيد تشكيلها وحفظها بصيغة JPEG بحجم 256x256.\n# يتم تحرير الذاكرة بعد معالجة كل صورة للحفاظ على أداء النظام.\n# هذا الكود مناسب للتعامل مع كميات كبيرة من البيانات الطبية وتحويلها إلى صور يمكن استخدامها بسهولة في نماذج الذكاء الاصطناعي مثل الشبكات العصبية.\n    #\n    #\n    #\n    \n    #\n    #\n    #","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T19:15:36.482422Z","iopub.execute_input":"2025-04-29T19:15:36.482736Z","iopub.status.idle":"2025-04-29T19:47:31.737775Z","shell.execute_reply.started":"2025-04-29T19:15:36.482708Z","shell.execute_reply":"2025-04-29T19:47:31.736878Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Train normal\nfrom tqdm import tqdm\nimport pydicom\nfor i in tqdm(range(10000)):\n    dcm = pydicom.dcmread(\"/kaggle/input/rsna-str-pulmonary-embolism-detection/train/\"+df1.loc[i,'StudyInstanceUID']+'/'+df1.loc[i,'SeriesInstanceUID']+'/'+df1.loc[i,'SOPInstanceUID']+'.dcm')\n    dc_image = dcm.pixel_array.astype('float32')\n    #scaled_image = (np.maximum(dc_image, 0) / dc_image.max())\n    #scaled_image = np.reshape(scaled_image,(scaled_image.shape[0], scaled_image.shape[1], 1))\n    im = Image.fromarray(dc_image).convert('RGB').resize((256,256))  \n    im.save(\"/kaggle/data/train/normal/\"+str(i)+\".jpg\")\n    del dcm, dc_image, im\n    gc.collect()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T19:47:31.738966Z","iopub.execute_input":"2025-04-29T19:47:31.739235Z","iopub.status.idle":"2025-04-29T20:20:18.97245Z","shell.execute_reply.started":"2025-04-29T19:47:31.739208Z","shell.execute_reply":"2025-04-29T20:20:18.971584Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Valid not_normal\nfor i in tqdm(range(10000,12000)):\n    dcm = pydicom.dcmread(\"/kaggle/input/rsna-str-pulmonary-embolism-detection/train/\"+df.loc[i,'StudyInstanceUID']+'/'+df.loc[i,'SeriesInstanceUID']+'/'+df.loc[i,'SOPInstanceUID']+'.dcm')\n    dc_image=dcm.pixel_array.astype('float32')\n    #scaled_image = (np.maximum(dc_image, 0) / dc_image.max())\n    #scaled_image = np.reshape(scaled_image,(scaled_image.shape[0], scaled_image.shape[1], 1))\n    im = Image.fromarray(dc_image).convert('RGB').resize((256,256))  \n    im.save(\"/kaggle/data/valid/not_normal/\"+str(i)+\".jpg\")\n    del dcm, dc_image, im\n    gc.collect()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T20:20:18.973499Z","iopub.execute_input":"2025-04-29T20:20:18.973782Z","iopub.status.idle":"2025-04-29T20:26:31.405593Z","shell.execute_reply.started":"2025-04-29T20:20:18.973755Z","shell.execute_reply":"2025-04-29T20:26:31.4048Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Valid normal\nfor i in tqdm(range(10000,12000)):\n    dcm = pydicom.dcmread(\"/kaggle/input/rsna-str-pulmonary-embolism-detection/train/\"+df1.loc[i,'StudyInstanceUID']+'/'+df1.loc[i,'SeriesInstanceUID']+'/'+df1.loc[i,'SOPInstanceUID']+'.dcm')\n    dc_image=dcm.pixel_array.astype('float32')\n    #scaled_image = (np.maximum(dc_image, 0) / dc_image.max())\n    #scaled_image = np.reshape(scaled_image,(scaled_image.shape[0], scaled_image.shape[1], 1))\n    im = Image.fromarray(dc_image).convert('RGB').resize((256,256))  \n    im.save(\"/kaggle/data/valid/normal/\"+str(i)+\".jpg\")\n    del dcm, dc_image, im\n    gc.collect()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T20:26:31.406829Z","iopub.execute_input":"2025-04-29T20:26:31.407098Z","iopub.status.idle":"2025-04-29T20:32:44.009296Z","shell.execute_reply.started":"2025-04-29T20:26:31.407071Z","shell.execute_reply":"2025-04-29T20:32:44.008483Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Test not_normal\nfor i in tqdm(range(12000,14000)):\n    dcm = pydicom.dcmread(\"/kaggle/input/rsna-str-pulmonary-embolism-detection/train/\"+df.loc[i,'StudyInstanceUID']+'/'+df.loc[i,'SeriesInstanceUID']+'/'+df.loc[i,'SOPInstanceUID']+'.dcm')\n    dc_image=dcm.pixel_array.astype('float32')\n    #scaled_image = (np.maximum(dc_image, 0) / dc_image.max())\n    #scaled_image = np.reshape(scaled_image,(scaled_image.shape[0], scaled_image.shape[1], 1))\n    im = Image.fromarray(dc_image).convert('RGB').resize((256,256))  \n    im.save(\"/kaggle/data/test/not_normal/\"+str(i)+\".jpg\")\n    del dcm, dc_image, im\n    gc.collect()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T20:32:44.01063Z","iopub.execute_input":"2025-04-29T20:32:44.011243Z","iopub.status.idle":"2025-04-29T20:39:01.349185Z","shell.execute_reply.started":"2025-04-29T20:32:44.011201Z","shell.execute_reply":"2025-04-29T20:39:01.348292Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Test normal\nfor i in tqdm(range(12000,14000)):\n    dcm = pydicom.dcmread(\"/kaggle/input/rsna-str-pulmonary-embolism-detection/train/\"+df1.loc[i,'StudyInstanceUID']+'/'+df1.loc[i,'SeriesInstanceUID']+'/'+df1.loc[i,'SOPInstanceUID']+'.dcm')\n    dc_image=dcm.pixel_array.astype('float32')\n    #scaled_image = (np.maximum(dc_image, 0) / dc_image.max())\n    #scaled_image = np.reshape(scaled_image,(scaled_image.shape[0], scaled_image.shape[1], 1))\n    im = Image.fromarray(dc_image).convert('RGB').resize((256,256))  \n    im.save(\"/kaggle/data/test/normal/\"+str(i)+\".jpg\")\n    del dcm, dc_image, im\n    gc.collect()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T20:39:01.350224Z","iopub.execute_input":"2025-04-29T20:39:01.350487Z","iopub.status.idle":"2025-04-29T20:45:14.994688Z","shell.execute_reply.started":"2025-04-29T20:39:01.350461Z","shell.execute_reply":"2025-04-29T20:45:14.993865Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\ntrain_datagen = ImageDataGenerator(\n      featurewise_center=False,  \n      samplewise_center=False, \n      featurewise_std_normalization=False,  \n      samplewise_std_normalization=False, \n      rescale=1./255,\n      rotation_range=20,\n      width_shift_range=0.2,\n      height_shift_range=0.2,\n      shear_range=0.2,\n      zoom_range=0.2,\n      horizontal_flip=True,\n      vertical_flip=True,\n      fill_mode='nearest')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T20:45:14.995971Z","iopub.execute_input":"2025-04-29T20:45:14.996343Z","iopub.status.idle":"2025-04-29T20:45:15.002023Z","shell.execute_reply.started":"2025-04-29T20:45:14.996302Z","shell.execute_reply":"2025-04-29T20:45:15.00111Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_generator = train_datagen.flow_from_directory(\n        '/kaggle/data/train',\n        target_size=(256, 256),\n        batch_size=64,\n        class_mode='binary')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T20:45:15.003126Z","iopub.execute_input":"2025-04-29T20:45:15.003371Z","iopub.status.idle":"2025-04-29T20:45:15.307357Z","shell.execute_reply.started":"2025-04-29T20:45:15.003346Z","shell.execute_reply":"2025-04-29T20:45:15.306724Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### valid_datagen = ImageDataGenerator(\n      rescale=1./255)","metadata":{}},{"cell_type":"code","source":"valid_generator = valid_datagen.flow_from_directory(\n        '/kaggle/data/valid',\n        target_size=(256, 256),\n        batch_size=64,\n        class_mode='binary')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T20:45:15.315864Z","iopub.execute_input":"2025-04-29T20:45:15.316118Z","iopub.status.idle":"2025-04-29T20:45:15.38206Z","shell.execute_reply.started":"2025-04-29T20:45:15.316093Z","shell.execute_reply":"2025-04-29T20:45:15.381254Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_datagen = ImageDataGenerator(\n      rescale=1./255)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T20:45:15.383034Z","iopub.execute_input":"2025-04-29T20:45:15.383288Z","iopub.status.idle":"2025-04-29T20:45:15.387143Z","shell.execute_reply.started":"2025-04-29T20:45:15.383263Z","shell.execute_reply":"2025-04-29T20:45:15.386355Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_generator = valid_datagen.flow_from_directory(\n        '/kaggle/data/test',\n        target_size=(256, 256),\n        batch_size=64,\n        class_mode='binary')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T20:45:15.387956Z","iopub.execute_input":"2025-04-29T20:45:15.388181Z","iopub.status.idle":"2025-04-29T20:45:15.450891Z","shell.execute_reply.started":"2025-04-29T20:45:15.388158Z","shell.execute_reply":"2025-04-29T20:45:15.450107Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Sequential()\nmodel.add(Conv2D(32 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu' , input_shape = ( 256, 256, 3)))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))\nmodel.add(Conv2D(64 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))\nmodel.add(Dropout(0.1))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))\nmodel.add(Conv2D(64 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))\nmodel.add(Conv2D(128 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))\nmodel.add(Dropout(0.2))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))\nmodel.add(Conv2D(256 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))\nmodel.add(Dropout(0.2))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))\nmodel.add(Flatten())\nmodel.add(Dense(units = 128 , activation = 'relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(units = 1 , activation = 'sigmoid'))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T20:45:15.451857Z","iopub.execute_input":"2025-04-29T20:45:15.452101Z","iopub.status.idle":"2025-04-29T20:45:16.442686Z","shell.execute_reply.started":"2025-04-29T20:45:15.452077Z","shell.execute_reply":"2025-04-29T20:45:16.441763Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.utils import plot_model\n\n# Plot model architecture to a file\nplot_model(model, to_file='model_architecture.png', show_shapes=True, show_layer_names=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T23:31:48.759593Z","iopub.execute_input":"2025-04-29T23:31:48.759975Z","iopub.status.idle":"2025-04-29T23:31:49.809469Z","shell.execute_reply.started":"2025-04-29T23:31:48.759942Z","shell.execute_reply":"2025-04-29T23:31:49.808503Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!mkdir /kaggle/models","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T20:45:16.443824Z","iopub.execute_input":"2025-04-29T20:45:16.444103Z","iopub.status.idle":"2025-04-29T20:45:17.461936Z","shell.execute_reply.started":"2025-04-29T20:45:16.444076Z","shell.execute_reply":"2025-04-29T20:45:17.460636Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau\n\nloss = tf.keras.losses.BinaryCrossentropy()\nmodel.compile(loss=loss, \n              optimizer='Adam', \n              metrics=['binary_accuracy'])\n\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_binary_accuracy', patience=2, verbose=1, factor=0.3, min_lr=0.000001)\n\n# Update the filepath to end with '.keras'\nfilepath = \"/kaggle/models/saved-model-{epoch:02d}-{val_binary_accuracy:.2f}.keras\"\n\n# Use the updated filepath\ncheckpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, \n                             save_best_only=False, save_freq='epoch')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T20:45:17.46343Z","iopub.execute_input":"2025-04-29T20:45:17.463772Z","iopub.status.idle":"2025-04-29T20:45:17.482183Z","shell.execute_reply.started":"2025-04-29T20:45:17.46374Z","shell.execute_reply":"2025-04-29T20:45:17.481568Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# Assuming train_generator and valid_generator are already defined\nhistory = model.fit(\n      train_generator,\n      epochs=25,\n      validation_data=valid_generator,\n      validation_steps=4,\n      callbacks=[checkpoint, learning_rate_reduction],\n      verbose=1\n)\n ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T20:45:17.48306Z","iopub.execute_input":"2025-04-29T20:45:17.483312Z","iopub.status.idle":"2025-04-29T22:34:53.638693Z","shell.execute_reply.started":"2025-04-29T20:45:17.483287Z","shell.execute_reply":"2025-04-29T22:34:53.637757Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save('model.h5')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T22:34:53.640237Z","iopub.execute_input":"2025-04-29T22:34:53.640997Z","iopub.status.idle":"2025-04-29T22:34:53.75806Z","shell.execute_reply.started":"2025-04-29T22:34:53.640951Z","shell.execute_reply":"2025-04-29T22:34:53.757188Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.plot(history.history['binary_accuracy'], label='The score of correct predictions on the training set')\nplt.plot(history.history['val_binary_accuracy'], label='The score of correct predictions on the val set')\nplt.xlabel('Epoch')\nplt.ylabel('Score correct answers')\nplt.legend()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T22:34:53.759032Z","iopub.execute_input":"2025-04-29T22:34:53.759363Z","iopub.status.idle":"2025-04-29T22:34:53.985099Z","shell.execute_reply.started":"2025-04-29T22:34:53.759335Z","shell.execute_reply":"2025-04-29T22:34:53.98416Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\nbest_acc = 0\nbest_model = \"\"\n\nfor i in os.listdir(\"/kaggle/models\"):\n    model.load_weights(\"/kaggle/models/\" + i)\n    # Use `evaluate` instead of `evaluate_generator`\n    loss, acc = model.evaluate(test_generator, steps=3, verbose=0)\n    if acc > best_acc:\n        best_acc = acc  # Update the best accuracy\n        best_model = i  # Save the current model name\n\nprint(f\"The best model is {best_model} with an accuracy of {best_acc:.2f}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T22:34:53.986284Z","iopub.execute_input":"2025-04-29T22:34:53.986663Z","iopub.status.idle":"2025-04-29T22:35:19.545587Z","shell.execute_reply.started":"2025-04-29T22:34:53.986623Z","shell.execute_reply":"2025-04-29T22:35:19.544688Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\"/kaggle/models/\" + best_model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T23:38:35.691522Z","iopub.execute_input":"2025-04-29T23:38:35.692287Z","iopub.status.idle":"2025-04-29T23:38:35.697727Z","shell.execute_reply.started":"2025-04-29T23:38:35.692253Z","shell.execute_reply":"2025-04-29T23:38:35.696758Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load the best model weights\nmodel.load_weights(\"/kaggle/models/\" + best_model)\n\n# Use `evaluate` instead of `evaluate_generator`\nloss, acc = model.evaluate(test_generator, steps=3, verbose=0)\n\n# Convert accuracy to percentage\nacc = acc * 100\nprint(f\"Accuracy is: {acc:.2f}%\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T23:39:34.079867Z","iopub.execute_input":"2025-04-29T23:39:34.080592Z","iopub.status.idle":"2025-04-29T23:39:35.214268Z","shell.execute_reply.started":"2025-04-29T23:39:34.080559Z","shell.execute_reply":"2025-04-29T23:39:35.213344Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save(\"best-model.keras\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T23:40:41.566409Z","iopub.execute_input":"2025-04-29T23:40:41.567114Z","iopub.status.idle":"2025-04-29T23:40:41.731916Z","shell.execute_reply.started":"2025-04-29T23:40:41.567077Z","shell.execute_reply":"2025-04-29T23:40:41.731193Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.preprocessing.image import load_img, img_to_array\nfrom tensorflow.keras.models import load_model\nimport tensorflow as tf\n\n# Constants\ntest_dir = \"/kaggle/data/test/\"\nimage_size = (256, 256)\nmodel_path = \"/kaggle/models/\" + best_model  # already loaded before\n\n# Load the model weights\nmodel.load_weights(model_path)\n\n# Prepare some sample test data\ncategories = ['normal', 'not_normal']\nsample_images = []\n\n# Get 5 samples from each category\nfor label in categories:\n    path = os.path.join(test_dir, label)\n    images = os.listdir(path)[:5]  # take first 5\n    for img_name in images:\n        img_path = os.path.join(path, img_name)\n        image = load_img(img_path, target_size=image_size)\n        image_array = img_to_array(image) / 255.0  # normalize\n        sample_images.append((image_array, label, img_path))\n\n# Prepare batch for prediction\nX = np.array([img[0] for img in sample_images])\ntrue_labels = [img[1] for img in sample_images]\n\n# Predict\npreds = model.predict(X)\npred_labels = ['not_normal' if p > 0.5 else 'normal' for p in preds.flatten()]\n\n# Plot\nplt.figure(figsize=(12, 6))\nfor i in range(len(sample_images)):\n    plt.subplot(2, 5, i+1)\n    plt.imshow(sample_images[i][0])\n    plt.axis('off')\n    plt.title(f\"True: {true_labels[i]}\\nPred: {pred_labels[i]}\")\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-29T23:28:52.058906Z","iopub.execute_input":"2025-04-29T23:28:52.059285Z","iopub.status.idle":"2025-04-29T23:28:54.242282Z","shell.execute_reply.started":"2025-04-29T23:28:52.059251Z","shell.execute_reply":"2025-04-29T23:28:54.2414Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}