{"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"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":7311243,"sourceType":"datasetVersion","datasetId":4242441},{"sourceId":2822650,"sourceType":"datasetVersion","datasetId":1715304}],"dockerImageVersionId":30301,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"from keras.layers import Conv2D,Conv2DTranspose,MaxPooling2D,Dropout,Concatenate,Input\nfrom keras import Model","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-06-05T21:05:59.918971Z","iopub.execute_input":"2024-06-05T21:05:59.919314Z","iopub.status.idle":"2024-06-05T21:06:05.264078Z","shell.execute_reply.started":"2024-06-05T21:05:59.919233Z","shell.execute_reply":"2024-06-05T21:06:05.263183Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport os","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:05.266126Z","iopub.execute_input":"2024-06-05T21:06:05.266913Z","iopub.status.idle":"2024-06-05T21:06:05.272366Z","shell.execute_reply.started":"2024-06-05T21:06:05.266871Z","shell.execute_reply":"2024-06-05T21:06:05.271056Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def double_conv_block(prev_layer, filter_count):\n   new_layer = Conv2D(filter_count, 3, padding = \"same\", activation = \"relu\", kernel_initializer = \"he_normal\")(prev_layer)\n   new_layer = Conv2D(filter_count, 3, padding = \"same\", activation = \"relu\", kernel_initializer = \"he_normal\")(new_layer)\n   return new_layer","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:05.273509Z","iopub.execute_input":"2024-06-05T21:06:05.273810Z","iopub.status.idle":"2024-06-05T21:06:05.284762Z","shell.execute_reply.started":"2024-06-05T21:06:05.273783Z","shell.execute_reply":"2024-06-05T21:06:05.283755Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def downsample_block(prev_layer, filter_count):\n   skip_features = double_conv_block(prev_layer, filter_count)\n   down_sampled = MaxPooling2D(2)(skip_features)\n   down_sampled = Dropout(0.3)(down_sampled)\n   return skip_features, down_sampled","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:05.286848Z","iopub.execute_input":"2024-06-05T21:06:05.287149Z","iopub.status.idle":"2024-06-05T21:06:05.294755Z","shell.execute_reply.started":"2024-06-05T21:06:05.287117Z","shell.execute_reply":"2024-06-05T21:06:05.293897Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def upsample_block(prev_layer, skipped_features, n_filters):\n   upsampled = Conv2DTranspose(n_filters, 3, 2, padding=\"same\")(prev_layer)\n   upsampled = Concatenate()([upsampled, skipped_features])\n   upsampled = Dropout(0.3)(upsampled)\n   upsampled = double_conv_block(upsampled, n_filters)\n   return upsampled","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:05.295892Z","iopub.execute_input":"2024-06-05T21:06:05.296172Z","iopub.status.idle":"2024-06-05T21:06:05.304922Z","shell.execute_reply.started":"2024-06-05T21:06:05.296147Z","shell.execute_reply":"2024-06-05T21:06:05.304084Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nimport keras as kl \ndef make_unet():\n   inputs = kl.Input(shape=(128,128,1))\n\n\n   skipped_fmaps_1, downsample_1 = downsample_block(inputs, 64)\n   skipped_fmaps_2, downsample_2 = downsample_block(downsample_1, 128)\n   skipped_fmaps_3, downsample_3 = downsample_block(downsample_2, 256)\n   skipped_fmaps_4, downsample_4 = downsample_block(downsample_3, 512)\n\n   bottleneck = double_conv_block(downsample_4, 1024)\n   \n   upsample_1 = upsample_block(bottleneck, skipped_fmaps_4, 512)\n   upsample_2 = upsample_block(upsample_1, skipped_fmaps_3, 256)\n   upsample_3 = upsample_block(upsample_2, skipped_fmaps_2, 128)\n   upsample_4 = upsample_block(upsample_3, skipped_fmaps_1, 64)\n\n\n   outputs = Conv2D(1, 1, padding=\"same\", activation = \"sigmoid\")(upsample_4)\n\n   unet_model = Model(inputs, outputs, name=\"U-Net\")\n\n   return unet_model","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:05.306131Z","iopub.execute_input":"2024-06-05T21:06:05.306483Z","iopub.status.idle":"2024-06-05T21:06:05.315727Z","shell.execute_reply.started":"2024-06-05T21:06:05.306449Z","shell.execute_reply":"2024-06-05T21:06:05.314908Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.utils import plot_model\nfrom matplotlib.pyplot import figure\n\ndef model_plotter(model):\n  plot_model(\n      model,\n      to_file=\"model.png\",\n      show_shapes=True,\n      show_dtype=True,\n      show_layer_names=True,\n      rankdir=\"TB\",\n      expand_nested=True,\n      dpi=96,\n      layer_range=None,  )\n  figure(figsize=(100,100))\n  plt.imshow(np.asarray(Image.open(\"model.png\")))\n  plt.axis(\"off\")\n  plt.show()  ","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:05.316775Z","iopub.execute_input":"2024-06-05T21:06:05.317089Z","iopub.status.idle":"2024-06-05T21:06:05.607683Z","shell.execute_reply.started":"2024-06-05T21:06:05.317063Z","shell.execute_reply":"2024-06-05T21:06:05.606897Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nu_net = make_unet()","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:05.608778Z","iopub.execute_input":"2024-06-05T21:06:05.609117Z","iopub.status.idle":"2024-06-05T21:06:08.561540Z","shell.execute_reply.started":"2024-06-05T21:06:05.609089Z","shell.execute_reply":"2024-06-05T21:06:08.560653Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_plotter(u_net)","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:08.562637Z","iopub.execute_input":"2024-06-05T21:06:08.562956Z","iopub.status.idle":"2024-06-05T21:06:13.781258Z","shell.execute_reply.started":"2024-06-05T21:06:08.562928Z","shell.execute_reply":"2024-06-05T21:06:13.779537Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Code**","metadata":{}},{"cell_type":"code","source":"images = os.listdir(\"/kaggle/input/dataset-ph2/trainx\")\nmasks = os.listdir(\"/kaggle/input/dataset-ph2/trainy\")","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:13.786461Z","iopub.execute_input":"2024-06-05T21:06:13.787213Z","iopub.status.idle":"2024-06-05T21:06:13.902589Z","shell.execute_reply.started":"2024-06-05T21:06:13.787171Z","shell.execute_reply":"2024-06-05T21:06:13.901730Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"v_images = os.listdir(\"/kaggle/input/dataset-ph2/ph2_resized2/trainx\")\nv_masks = os.listdir(\"/kaggle/input/dataset-ph2/ph2_resized2/trainy\")","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:13.903596Z","iopub.execute_input":"2024-06-05T21:06:13.903889Z","iopub.status.idle":"2024-06-05T21:06:14.048954Z","shell.execute_reply.started":"2024-06-05T21:06:13.903847Z","shell.execute_reply":"2024-06-05T21:06:14.048166Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(images)==len(masks))\nprint(len(v_images)==len(v_masks))","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:14.050211Z","iopub.execute_input":"2024-06-05T21:06:14.051060Z","iopub.status.idle":"2024-06-05T21:06:14.056631Z","shell.execute_reply.started":"2024-06-05T21:06:14.051016Z","shell.execute_reply":"2024-06-05T21:06:14.055776Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"masks[:10]","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:14.057961Z","iopub.execute_input":"2024-06-05T21:06:14.058328Z","iopub.status.idle":"2024-06-05T21:06:14.069178Z","shell.execute_reply.started":"2024-06-05T21:06:14.058284Z","shell.execute_reply":"2024-06-05T21:06:14.068274Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"images[:10]","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:14.070365Z","iopub.execute_input":"2024-06-05T21:06:14.070653Z","iopub.status.idle":"2024-06-05T21:06:14.080001Z","shell.execute_reply.started":"2024-06-05T21:06:14.070628Z","shell.execute_reply":"2024-06-05T21:06:14.079062Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"masks.sort()\nimages.sort()\nv_masks.sort()\nv_images.sort()","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:14.081158Z","iopub.execute_input":"2024-06-05T21:06:14.081524Z","iopub.status.idle":"2024-06-05T21:06:14.089736Z","shell.execute_reply.started":"2024-06-05T21:06:14.081488Z","shell.execute_reply":"2024-06-05T21:06:14.088841Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"temp = 0\nwhile temp<20:\n  print(images[temp].split(\"_\")[1].split(\".\")[0] == masks[temp].split(\"_\")[1].split(\".\")[0])\n  temp+=1","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:14.091314Z","iopub.execute_input":"2024-06-05T21:06:14.092212Z","iopub.status.idle":"2024-06-05T21:06:14.100331Z","shell.execute_reply.started":"2024-06-05T21:06:14.092162Z","shell.execute_reply":"2024-06-05T21:06:14.099407Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import random\n\ni = random.randint(0,len(images)-1)\nimg = np.asarray(Image.open(os.path.join(\"/kaggle/input/dataset-ph2/trainx\",images[i])))\nmask = np.asarray(Image.open(os.path.join(\"/kaggle/input/dataset-ph2/trainy\",masks[i])))\nprint(img.shape,mask.shape)","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:14.101521Z","iopub.execute_input":"2024-06-05T21:06:14.101817Z","iopub.status.idle":"2024-06-05T21:06:14.122151Z","shell.execute_reply.started":"2024-06-05T21:06:14.101790Z","shell.execute_reply":"2024-06-05T21:06:14.121080Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(images)","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:14.123241Z","iopub.execute_input":"2024-06-05T21:06:14.123507Z","iopub.status.idle":"2024-06-05T21:06:14.129335Z","shell.execute_reply.started":"2024-06-05T21:06:14.123482Z","shell.execute_reply":"2024-06-05T21:06:14.128360Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.subplot(1,2,1)\nplt.imshow(img[:,:,:3]) #rgba to rgb\n\nplt.subplot(1,2,2)\nplt.imshow(mask)\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:14.130665Z","iopub.execute_input":"2024-06-05T21:06:14.131349Z","iopub.status.idle":"2024-06-05T21:06:14.438126Z","shell.execute_reply.started":"2024-06-05T21:06:14.131319Z","shell.execute_reply":"2024-06-05T21:06:14.437177Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ndef make_dataset(validation=False):\n  x = []\n  y = []\n  if(validation):\n    for i,(image,mask) in enumerate(zip(v_images[:1500],v_masks[:1500])):\n      print(\"\\r\"+str(i+1)+\"/\"+str(len(v_images)),end=\"\")\n\n      image = Image.open(os.path.join(\"/kaggle/input/dataset-ph2/ph2_resized2/trainx\",image)).convert('L')\n      mask = Image.open(os.path.join(\"/kaggle/input/dataset-ph2/ph2_resized2/trainy\",mask)).convert('L')\n\n      image = np.asarray(image.resize((128,128)))/255.\n      mask = np.asarray(mask.resize((128,128)))/255.\n\n      x.append(image)\n      y.append(mask)\n  else:\n    for i,(image,mask) in enumerate(zip(images[:3500],masks[:3500])):\n      print(\"\\r\"+str(i+1)+\"/\"+str(len(images)),end=\"\")\n      \n      image = Image.open(os.path.join(\"/kaggle/input/dataset-ph2/trainx\",image)).convert('L')\n      mask = Image.open(os.path.join(\"/kaggle/input/dataset-ph2/trainy\",mask)).convert('L')\n\n      image = np.asarray(image.resize((128,128)))/255.\n      mask = np.asarray(mask.resize((128,128)))/255.\n\n      x.append(image)\n      y.append(mask)\n\n  return np.array(x),np.array(y)","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:14.439390Z","iopub.execute_input":"2024-06-05T21:06:14.439698Z","iopub.status.idle":"2024-06-05T21:06:14.452535Z","shell.execute_reply.started":"2024-06-05T21:06:14.439669Z","shell.execute_reply":"2024-06-05T21:06:14.451471Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x,y = make_dataset()","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:14.453687Z","iopub.execute_input":"2024-06-05T21:06:14.454066Z","iopub.status.idle":"2024-06-05T21:06:16.698530Z","shell.execute_reply.started":"2024-06-05T21:06:14.454039Z","shell.execute_reply":"2024-06-05T21:06:16.697473Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"v_x,v_y = make_dataset(True)","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:16.700158Z","iopub.execute_input":"2024-06-05T21:06:16.700920Z","iopub.status.idle":"2024-06-05T21:06:18.887707Z","shell.execute_reply.started":"2024-06-05T21:06:16.700822Z","shell.execute_reply":"2024-06-05T21:06:18.886643Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x,y = np.expand_dims(x,axis=-1),np.expand_dims(y,axis=-1)\nv_x,v_y = np.expand_dims(v_x,axis=-1),np.expand_dims(v_y,axis=-1)","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:18.888845Z","iopub.execute_input":"2024-06-05T21:06:18.889155Z","iopub.status.idle":"2024-06-05T21:06:18.895393Z","shell.execute_reply.started":"2024-06-05T21:06:18.889128Z","shell.execute_reply":"2024-06-05T21:06:18.894323Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ndata_gen_args = dict(\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    fill_mode=\"nearest\",\n    horizontal_flip=True,\n    vertical_flip=True,\n)\n\nimage_datagen = ImageDataGenerator(**data_gen_args)\nmask_datagen = ImageDataGenerator(**data_gen_args)\n\nseed = 1\n\nimage_generator = image_datagen.flow(\n    x,\n    batch_size=16,\n    seed=seed)\n\nmask_generator = mask_datagen.flow(\n    y,\n    batch_size=16,\n    seed=seed)\n\ntrain_generator = zip(image_generator, mask_generator)","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:18.896821Z","iopub.execute_input":"2024-06-05T21:06:18.897314Z","iopub.status.idle":"2024-06-05T21:06:18.915705Z","shell.execute_reply.started":"2024-06-05T21:06:18.897269Z","shell.execute_reply":"2024-06-05T21:06:18.914781Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\nimage_test_datagen = ImageDataGenerator()\nmask_test_datagen = ImageDataGenerator()\n\nseed = 1\n\nimage_test_generator = image_test_datagen.flow(\n    v_x,\n    batch_size=16,\n    seed=seed)\n\nmask_test_generator = mask_test_datagen.flow(\n    v_y,\n    batch_size=16,\n    seed=seed)\n\nvalid_generator = zip(image_test_generator, mask_test_generator)","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:18.916839Z","iopub.execute_input":"2024-06-05T21:06:18.917138Z","iopub.status.idle":"2024-06-05T21:06:18.932184Z","shell.execute_reply.started":"2024-06-05T21:06:18.917111Z","shell.execute_reply":"2024-06-05T21:06:18.931305Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"i = random.randint(0,len(x))\n\nimg = x[i]\nmask = y[i]\n\nplt.subplot(1,2,1)\nplt.imshow(np.squeeze(img))\n\nplt.subplot(1,2,2)\nplt.imshow(np.squeeze(mask))\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:18.933367Z","iopub.execute_input":"2024-06-05T21:06:18.933642Z","iopub.status.idle":"2024-06-05T21:06:19.213803Z","shell.execute_reply.started":"2024-06-05T21:06:18.933616Z","shell.execute_reply":"2024-06-05T21:06:19.212886Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"u_net.compile(optimizer=\"adam\",loss=\"binary_crossentropy\",metrics=\"accuracy\")","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:06:19.214869Z","iopub.execute_input":"2024-06-05T21:06:19.215146Z","iopub.status.idle":"2024-06-05T21:06:19.230586Z","shell.execute_reply.started":"2024-06-05T21:06:19.215120Z","shell.execute_reply":"2024-06-05T21:06:19.229774Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_history = u_net.fit(train_generator,epochs=100,validation_data=valid_generator,steps_per_epoch = int(x.shape[0] / 8),validation_steps = int(v_x.shape[0] / 8))","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:17:02.274704Z","iopub.execute_input":"2024-06-05T21:17:02.275828Z","iopub.status.idle":"2024-06-05T21:23:37.195847Z","shell.execute_reply.started":"2024-06-05T21:17:02.275779Z","shell.execute_reply":"2024-06-05T21:23:37.195030Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"u_net.save(\"u_net.h5\")","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:24:01.741702Z","iopub.execute_input":"2024-06-05T21:24:01.742608Z","iopub.status.idle":"2024-06-05T21:24:02.728493Z","shell.execute_reply.started":"2024-06-05T21:24:01.742567Z","shell.execute_reply":"2024-06-05T21:24:02.727012Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"i = random.randint(0,len(v_x)-1)\n\noriginal = v_x[i].copy()\noriginal_mask = v_y[i].copy()\n\nmask = u_net.predict(np.expand_dims(original,axis=0))\n#ac = 0.95\n\nsegmented = np.squeeze(original).copy()\nsegmented[np.squeeze(mask)<0.2] = 0\n\nplt.subplot(1,4,1)\nplt.imshow(np.squeeze(original),cmap=\"gray\")\nplt.title(\"x-ray\")\nplt.axis(\"off\")\n\nplt.subplot(1,4,2)\nplt.imshow(segmented,cmap=\"gray\")\nplt.title(\"segmented\")\nplt.axis(\"off\")\n\nplt.subplot(1,4,3)\nplt.imshow(np.squeeze(mask[0]),cmap=\"gray\")\nplt.title(\"predicted mask\")\nplt.axis(\"off\")\n\nplt.subplot(1,4,4)\nplt.imshow(np.squeeze(original_mask),cmap=\"gray\")\nplt.title(\"  original mask\")\nplt.axis(\"off\")\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:24:05.332637Z","iopub.execute_input":"2024-06-05T21:24:05.333311Z","iopub.status.idle":"2024-06-05T21:24:05.840677Z","shell.execute_reply.started":"2024-06-05T21:24:05.333268Z","shell.execute_reply":"2024-06-05T21:24:05.839755Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf  # Or import keras directly if using standalone Keras\nimport numpy as np\nimport cv2  # Or use another image loading library if preferred\n\n# Load the model\nmodel = tf.keras.models.load_model(\"/kaggle/working/u_net.h5\")  # Replace with actual model path\n\n# Load test image paths\ntest_image_paths = [\n    f\"/kaggle/input/dataset-ph2/ph2_resized2/trainx/{filename}\"\n    for filename in os.listdir(\"/kaggle/input/dataset-ph2/ph2_resized2/trainx\")\n    if filename.endswith(\".bmp\")\n]\n\n# Prepare test images\ntest_images = []\nfor image_path in test_image_paths:\n    try:\n        image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)  # Load grayscale if needed\n        image = cv2.resize(image, (model.input_shape[1], model.input_shape[2]))  # Resize to model input size\n        test_images.append(image)\n    except cv2.error as e:\n        print(f\"Error loading image {image_path}: {e}\")\n\ntest_images = np.array(test_images)  # Convert to NumPy array\ntest_images = test_images / 255.0  # Normalize pixel values (0-1) if needed\n\n# Reshape and add batch dimension\ntest_images = test_images.reshape((len(test_images), model.input_shape[1], model.input_shape[2], 1))  # Assuming single channel\n\n# Generate predictions\npredictions = model.predict(test_images, batch_size=32)  # Adjust batch size if needed\n#accuracy=ac\n\n# Print or use predictions as needed\nprint(predictions)\n","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:24:16.589039Z","iopub.execute_input":"2024-06-05T21:24:16.589476Z","iopub.status.idle":"2024-06-05T21:24:18.426573Z","shell.execute_reply.started":"2024-06-05T21:24:16.589439Z","shell.execute_reply":"2024-06-05T21:24:18.425453Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nfrom sklearn.metrics import accuracy_score\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# Assuming model is defined and loaded here\n# model = ...\n\n# Image and Mask Data Generators\nimage_test_datagen = ImageDataGenerator()\nmask_test_datagen = ImageDataGenerator()\n\nseed = 1\n\nimage_test_generator = image_test_datagen.flow(v_x, batch_size=16, seed=seed)\nmask_test_generator = mask_test_datagen.flow(v_y, batch_size=16, seed=seed)\n\nvalid_generator = zip(image_test_generator, mask_test_generator)\n\n# Lists to collect true labels and predictions\nall_true_labels = []\nall_predictions = []\n\n# Iterate over the generator\nfor image_batch, mask_batch in valid_generator:\n    labels = mask_batch  # Assuming mask_batch contains the true labels\n    all_true_labels.append(labels.flatten())\n\n    # Generate predictions for the current batch\n    predictions_batch = model.predict(image_batch)\n    predictions_batch = np.argmax(predictions_batch, axis=-1)  # Adjust this based on your model's output\n    all_predictions.append(predictions_batch.flatten())\n\n# Concatenate all collected labels and predictions\ntrue_labels = np.concatenate(all_true_labels)\npredictions = np.concatenate(all_predictions)\naccuracy = accuracy_score(true_labels, predictions)\n\nprint(f'Validation Accuracy: {accuracy * 100:.2f}%')","metadata":{"execution":{"iopub.status.busy":"2024-06-05T21:24:29.065774Z","iopub.execute_input":"2024-06-05T21:24:29.066150Z","iopub.status.idle":"2024-06-05T21:24:29.071838Z","shell.execute_reply.started":"2024-06-05T21:24:29.066121Z","shell.execute_reply":"2024-06-05T21:24:29.070778Z"},"trusted":true},"execution_count":null,"outputs":[]}]}