{"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":"none","dataSources":[{"sourceId":9988,"databundleVersionId":868324,"sourceType":"competition"}],"dockerImageVersionId":30761,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-08-30T14:55:28.513917Z","iopub.execute_input":"2024-08-30T14:55:28.514411Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import warnings\nwarnings.filterwarnings('ignore')\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom skimage.io import imread\nfrom skimage.segmentation import mark_boundaries\nfrom skimage.util import montage\nfrom skimage.morphology import label\n\nimport gc\ngc.enable()","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:48:53.961196Z","iopub.execute_input":"2024-08-30T15:48:53.961786Z","iopub.status.idle":"2024-08-30T15:48:53.973828Z","shell.execute_reply.started":"2024-08-30T15:48:53.961737Z","shell.execute_reply":"2024-08-30T15:48:53.972149Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_image_dir = '../input/airbus-ship-detection/train_v2'\ntest_image_dir = \"../input/airbus-ship-detection/test_v2\"","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:48:56.57916Z","iopub.execute_input":"2024-08-30T15:48:56.579682Z","iopub.status.idle":"2024-08-30T15:48:56.585991Z","shell.execute_reply.started":"2024-08-30T15:48:56.579637Z","shell.execute_reply":"2024-08-30T15:48:56.584668Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_images = os.listdir(train_image_dir)\ntrain_images.sort()\nprint(f\"Total of {len(train_images)} images in train directory.\\nHere is how first five train_images looks like:- {train_images[:5]}\")","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:49:45.189927Z","iopub.execute_input":"2024-08-30T15:49:45.19049Z","iopub.status.idle":"2024-08-30T15:49:45.524205Z","shell.execute_reply.started":"2024-08-30T15:49:45.190442Z","shell.execute_reply":"2024-08-30T15:49:45.522654Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(15,15))\nplt.suptitle('TRAIN IMAGES\\n', weight = 'bold', fontsize = 15, color = 'r')\nfor i in range(16):\n    plt.subplot(4, 4, i+1)\n    plt.imshow(imread(train_image_dir + \"/\" + train_images[i]))\n    plt.title(f\"{train_images[i]}\", weight = 'bold')\n    plt.axis('off')\nplt.tight_layout()","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:49:46.162561Z","iopub.execute_input":"2024-08-30T15:49:46.163012Z","iopub.status.idle":"2024-08-30T15:49:51.595807Z","shell.execute_reply.started":"2024-08-30T15:49:46.162971Z","shell.execute_reply":"2024-08-30T15:49:51.594374Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Train ships segmented masks\nmasks = pd.read_csv(\"../input/airbus-ship-detection/train_ship_segmentations_v2.csv\")\nmasks.head(10)","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:49:51.598065Z","iopub.execute_input":"2024-08-30T15:49:51.599355Z","iopub.status.idle":"2024-08-30T15:49:52.472833Z","shell.execute_reply.started":"2024-08-30T15:49:51.599288Z","shell.execute_reply":"2024-08-30T15:49:52.471506Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Run Length Encoding (RLE) and Decoding**\n\nWe simply run through the data and count how many times each data point is repeated without any breaks.\n\nlossless compression","metadata":{}},{"cell_type":"code","source":"row_rle = ['10 1', \n           '4 1 2 0 4 1', \n           '3 1 4 0 3 1', \n           '2 1 6 0 2 1',\n           '1 1 2 0 1 1 2 0 1 1 2 0 1 1', \n           '1 1 8 0 1 1', \n           '3 1 1 0 2 1 1 0 3 1', \n           '2 1 1 0 1 1 2 0 1 1 1 0 2 1', \n           '1 1 1 0 1 1 1 0 2 1 1 0 1 1 1 0 1 1', \n           '10 1',\n           'Total']\n\npixels = [len(row.split(\" \")) for row in row_rle if row != 'Total']\nsum_pixels = np.array(pixels).sum()\npixels.append(sum_pixels)\n\ndata = {\n    'Row - RLE' : row_rle,\n    'Pixels' : pixels\n}\n\nrle_df = pd.DataFrame(data)\nrle_df.index+=1\nrle_df","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:57:05.87827Z","iopub.execute_input":"2024-08-30T15:57:05.878771Z","iopub.status.idle":"2024-08-30T15:57:05.898284Z","shell.execute_reply.started":"2024-08-30T15:57:05.878728Z","shell.execute_reply":"2024-08-30T15:57:05.896575Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_arr = imread(train_image_dir + '/' + '0005d01c8.jpg')\nplt.figure(figsize=(15,8))\nplt.imshow(img_arr)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:57:06.355265Z","iopub.execute_input":"2024-08-30T15:57:06.356412Z","iopub.status.idle":"2024-08-30T15:57:06.881568Z","shell.execute_reply.started":"2024-08-30T15:57:06.356354Z","shell.execute_reply":"2024-08-30T15:57:06.880229Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_arr.shape","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:57:07.580106Z","iopub.execute_input":"2024-08-30T15:57:07.581296Z","iopub.status.idle":"2024-08-30T15:57:07.589166Z","shell.execute_reply.started":"2024-08-30T15:57:07.581242Z","shell.execute_reply":"2024-08-30T15:57:07.587751Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Filter out all 0005d01c8.jpg image ids and respective encoded data \n# 2 ships means 2 same image ids will be there!\nrle_0 = masks.query('ImageId==\"0005d01c8.jpg\"')['EncodedPixels']\nrle_0","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:57:08.182798Z","iopub.execute_input":"2024-08-30T15:57:08.183387Z","iopub.status.idle":"2024-08-30T15:57:08.225664Z","shell.execute_reply.started":"2024-08-30T15:57:08.18334Z","shell.execute_reply":"2024-08-30T15:57:08.224328Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Make a list of each mask shown above also visualise whats happening!\nmask_lst, ct = [], 1\nfor mask in rle_0:\n    print(f\"Mask {ct} -\\n{mask}\\n\\n\")\n    mask_lst.append(mask)\n    ct+=1","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:57:12.197291Z","iopub.execute_input":"2024-08-30T15:57:12.197835Z","iopub.status.idle":"2024-08-30T15:57:12.207547Z","shell.execute_reply.started":"2024-08-30T15:57:12.19778Z","shell.execute_reply":"2024-08-30T15:57:12.205604Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Split and Display how the first mask in the list looks like\nsplit = mask_lst[0].split()\nprint(split)","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:57:12.295504Z","iopub.execute_input":"2024-08-30T15:57:12.29597Z","iopub.status.idle":"2024-08-30T15:57:12.303301Z","shell.execute_reply.started":"2024-08-30T15:57:12.295929Z","shell.execute_reply":"2024-08-30T15:57:12.301904Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"This data shows start_pixels and lenghts where we can think ship to exist in the original image.\nFor example, 56777 3 shows that pixels 56777, 56778, 56779 contributes to the ship.\nOur target is to create an image with these pixels labeled as 1 and remaining as 0.\nThis is how we can produce a mask for respective image.","metadata":{}},{"cell_type":"code","source":"# Grab all the starting pixels and lenghts and convert it into integers using numpy \nstarts, lengths = [np.array(x, dtype = int) for x in (split[::2], split[1::2])]\nstarts, lengths","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:57:15.85975Z","iopub.execute_input":"2024-08-30T15:57:15.860297Z","iopub.status.idle":"2024-08-30T15:57:15.873384Z","shell.execute_reply.started":"2024-08-30T15:57:15.860252Z","shell.execute_reply":"2024-08-30T15:57:15.871788Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get the ending pixels.\nends = starts + lengths - 1\npd.DataFrame({\n    'Starts' : starts,\n    'Lengths' : lengths,\n    'Ends' : ends\n}).head(10)","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:57:16.274267Z","iopub.execute_input":"2024-08-30T15:57:16.274736Z","iopub.status.idle":"2024-08-30T15:57:16.290378Z","shell.execute_reply.started":"2024-08-30T15:57:16.274693Z","shell.execute_reply":"2024-08-30T15:57:16.288954Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create 1s in place of these pixels and rest should be 0\nimg = np.zeros(768*768, dtype = np.uint8)\nfor start, end in zip(starts, ends):\n    img[start:end+1] = 1","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:57:19.270783Z","iopub.execute_input":"2024-08-30T15:57:19.271319Z","iopub.status.idle":"2024-08-30T15:57:19.279787Z","shell.execute_reply.started":"2024-08-30T15:57:19.271276Z","shell.execute_reply":"2024-08-30T15:57:19.278009Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img[56776:56781]","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:57:19.632631Z","iopub.execute_input":"2024-08-30T15:57:19.633157Z","iopub.status.idle":"2024-08-30T15:57:19.64326Z","shell.execute_reply.started":"2024-08-30T15:57:19.633113Z","shell.execute_reply":"2024-08-30T15:57:19.641458Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"split_1 = mask_lst[1].split()                                                                # Split the mask into start_pixels and lengths\nstarts, lengths = [np.array(x, dtype = int) for x in (split_1[0:][::2], split_1[1:][::2])]   # Generate arrays from only starts and lengths\nends = starts + lengths - 1                                                                  # Start pixel to end pixel will be start - 1 + length\nimg1 = np.zeros(768*768, dtype = np.uint8)                                                   # 1D array containing all zeros\nfor start, end in zip(starts, ends):                                                         # For each start to end pair\n    img1[start:end+1] = 1   ","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:57:20.122164Z","iopub.execute_input":"2024-08-30T15:57:20.122653Z","iopub.status.idle":"2024-08-30T15:57:20.132707Z","shell.execute_reply.started":"2024-08-30T15:57:20.12261Z","shell.execute_reply":"2024-08-30T15:57:20.131306Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img = img.reshape(768, 768)\nimg1 = img1.reshape(768, 768)\nfinal = img+img1\nprint(final, '\\n\\n', final.shape, '\\n\\n', final.ndim)","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:57:25.250608Z","iopub.execute_input":"2024-08-30T15:57:25.251149Z","iopub.status.idle":"2024-08-30T15:57:25.260187Z","shell.execute_reply.started":"2024-08-30T15:57:25.251103Z","shell.execute_reply":"2024-08-30T15:57:25.25879Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"final = np.expand_dims(final, -1) # -1 means the last available dimenstion, in this case it is 2. Hence, on axis = 2 we will get 1.\noriginal = imread(train_image_dir+'/'+train_images[15])\nplt.figure(figsize=(15, 8))\nplt.subplot(1, 2, 1)\nplt.title(f\"Original - Train Image, {original.shape}\")\nplt.imshow(original)\nplt.subplot(1, 2, 2)\nplt.title(f\"Mask generated from the RLE data for each ship, {final.shape}\")\nplt.imshow(final, cmap = \"gray\")\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:57:25.807552Z","iopub.execute_input":"2024-08-30T15:57:25.808939Z","iopub.status.idle":"2024-08-30T15:57:26.871379Z","shell.execute_reply.started":"2024-08-30T15:57:25.808885Z","shell.execute_reply":"2024-08-30T15:57:26.869955Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img = img.reshape(768, 768).T     # Transpose the first ship mask\nimg1 = img1.reshape(768, 768).T   # Transpose the second ship mask\nfinal = img+img1                  # Generate the final mask with two ships \nfinal = np.expand_dims(final, -1) \nplt.figure(figsize=(15, 8))\nplt.subplot(1, 2, 1)\nplt.title(f\"Original - Train Image, {original.shape}\")\nplt.imshow(original)\nplt.subplot(1, 2, 2)\nplt.title(f\"Mask generated from the RLE data for each ship, {final.shape}\")\nplt.imshow(final, cmap = \"Blues_r\")\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:57:26.873746Z","iopub.execute_input":"2024-08-30T15:57:26.874307Z","iopub.status.idle":"2024-08-30T15:57:27.825448Z","shell.execute_reply.started":"2024-08-30T15:57:26.874252Z","shell.execute_reply":"2024-08-30T15:57:27.824007Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define functions to do these tasks for all the training images\ndef rle_decode(mask_rle, shape=(768,768)):\n    '''\n    Input arguments -\n    mask_rle: Mask of one ship in the train image\n    shape: Output shape of the image array\n    '''\n    s = mask_rle.split()                                                               # Split the mask of each ship that is in RLE format\n    starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]     # Get the start pixels and lengths for which image has ship\n    ends = starts + lengths - 1                                                        # Get the end pixels where we need to stop\n    img = np.zeros(shape[0]*shape[1], dtype=np.uint8)                                  # A 1D vec full of zeros of size = 768*768\n    for lo, hi in zip(starts, ends):                                                   # For each start to end pixels where ship exists\n        img[lo:hi+1] = 1                                                               # Fill those values with 1 in the main 1D vector\n    '''\n    Returns -\n    Transposed array of the mask: Contains 1s and 0s. 1 for ship and 0 for background\n    '''\n    return img.reshape(shape).T                                                       \n\ndef masks_as_image(in_mask_list):\n    '''\n    Input - \n    in_mask_list: List of the masks of each ship in one whole training image\n    '''\n    all_masks = np.zeros((768, 768), dtype = np.int16)                                 # Creating 0s for the background\n    for mask in in_mask_list:                                                          # For each ship rle data in the list of mask rle \n        if isinstance(mask, str):                                                      # If the datatype is string\n            all_masks += rle_decode(mask)                                              # Use rle_decode to create one mask for whole image\n    '''\n    Returns - \n    Full mask of the training image whose RLE data has been passed as an input\n    '''\n    return np.expand_dims(all_masks, -1)","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:57:30.60758Z","iopub.execute_input":"2024-08-30T15:57:30.608039Z","iopub.status.idle":"2024-08-30T15:57:30.622689Z","shell.execute_reply.started":"2024-08-30T15:57:30.607999Z","shell.execute_reply":"2024-08-30T15:57:30.621215Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for num in [3, 4, 5, 6]:\n    rle_0 = masks.query(f'ImageId==\"{train_images[num-1]}\"')['EncodedPixels']\n    img_0 = masks_as_image(rle_0)\n    original = imread(train_image_dir+\"/\"+train_images[num-1])\n    plt.figure(figsize=(15, 8))\n    plt.subplot(1, 2, 1)\n    plt.title(f\"Original - Train Image {original.shape}\")\n    plt.imshow(original)\n    plt.subplot(1, 2, 2)\n    plt.title(f\"Mask generated from the RLE data for each ship {final.shape}\")\n    plt.imshow(img_0, cmap = \"Blues_r\")\n    plt.tight_layout()\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:57:31.091979Z","iopub.execute_input":"2024-08-30T15:57:31.093113Z","iopub.status.idle":"2024-08-30T15:57:35.776198Z","shell.execute_reply.started":"2024-08-30T15:57:31.09306Z","shell.execute_reply":"2024-08-30T15:57:35.774803Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Add a new feature to the masks data frame named as ship. If Encoded pixel in any row is a string, there is a ship else there isn't. \nmasks['ships'] = masks['EncodedPixels'].map(lambda c_row: 1 if isinstance(c_row, str) else 0)\nmasks.head(9)","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:57:35.778568Z","iopub.execute_input":"2024-08-30T15:57:35.778998Z","iopub.status.idle":"2024-08-30T15:57:35.996655Z","shell.execute_reply.started":"2024-08-30T15:57:35.778955Z","shell.execute_reply":"2024-08-30T15:57:35.995289Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Making a new data frame with unique image ids where we are summing up the ship counts\nunique_img_ids = masks.groupby('ImageId').agg({'ships': 'sum'}).reset_index() \nunique_img_ids.index+=1 # Incrimenting all the index by 1\nunique_img_ids.head()","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:57:35.998281Z","iopub.execute_input":"2024-08-30T15:57:35.9987Z","iopub.status.idle":"2024-08-30T15:57:36.322244Z","shell.execute_reply.started":"2024-08-30T15:57:35.998657Z","shell.execute_reply":"2024-08-30T15:57:36.32087Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Adding two new features to unique_img_ids data frame. If ship exists in image, val is 1 else 0. And it's vec form\nunique_img_ids['has_ship'] = unique_img_ids['ships'].map(lambda x: 1.0 if x>0 else 0.0)\nunique_img_ids.head()","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:57:36.325163Z","iopub.execute_input":"2024-08-30T15:57:36.325622Z","iopub.status.idle":"2024-08-30T15:57:36.427462Z","shell.execute_reply.started":"2024-08-30T15:57:36.325579Z","shell.execute_reply":"2024-08-30T15:57:36.426246Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Adding two new features to unique_img_ids data frame. If ship exists in image, val is 1 else 0. And it's vec form\nunique_img_ids['has_ship'] = unique_img_ids['ships'].map(lambda x: 1.0 if x>0 else 0.0)\nunique_img_ids.head()","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:57:36.429136Z","iopub.execute_input":"2024-08-30T15:57:36.430248Z","iopub.status.idle":"2024-08-30T15:57:36.529055Z","shell.execute_reply.started":"2024-08-30T15:57:36.430155Z","shell.execute_reply":"2024-08-30T15:57:36.527683Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Check the size of the files. Will take some time to run as there are loads of files!!!\nunique_img_ids['file_size_kb'] = unique_img_ids['ImageId'].map(lambda c_img_id: os.stat(os.path.join(train_image_dir, c_img_id)).st_size/1024)\n'''os.stat is used to get status of the specified path. Here, st_size represents size of the file in bytes. Converting it into kB!'''","metadata":{"execution":{"iopub.status.busy":"2024-08-30T15:57:36.530456Z","iopub.execute_input":"2024-08-30T15:57:36.53082Z","iopub.status.idle":"2024-08-30T16:04:21.432098Z","shell.execute_reply.started":"2024-08-30T15:57:36.530783Z","shell.execute_reply":"2024-08-30T16:04:21.430565Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# We can get rid of any images whose size is less than 35 Kb. As some of the files are corrupted! \nunique_img_ids[unique_img_ids.file_size_kb<35].head()","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:04:21.435603Z","iopub.execute_input":"2024-08-30T16:04:21.436075Z","iopub.status.idle":"2024-08-30T16:04:21.454628Z","shell.execute_reply.started":"2024-08-30T16:04:21.43603Z","shell.execute_reply":"2024-08-30T16:04:21.452865Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"rle_0 = masks.query(f'ImageId==\"0318fc519.jpg\"')['EncodedPixels']\nimg_0 = masks_as_image(rle_0)\noriginal = imread(train_image_dir+\"/\"+'0318fc519.jpg')\nplt.figure(figsize=(15, 8))\nplt.subplot(1, 2, 1)\nplt.title(f\"Original - Train Image {original.shape}\")\nplt.imshow(original)\nplt.subplot(1, 2, 2)\nplt.title(f\"Mask generated from the RLE data for each ship {final.shape}\")\nplt.imshow(img_0, cmap = \"Blues_r\")\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:04:21.456782Z","iopub.execute_input":"2024-08-30T16:04:21.457334Z","iopub.status.idle":"2024-08-30T16:04:22.368528Z","shell.execute_reply.started":"2024-08-30T16:04:21.457287Z","shell.execute_reply":"2024-08-30T16:04:22.367114Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"unique_img_ids = unique_img_ids[unique_img_ids.file_size_kb > 35]\nunique_img_ids.head()","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:04:28.466505Z","iopub.execute_input":"2024-08-30T16:04:28.467021Z","iopub.status.idle":"2024-08-30T16:04:28.498665Z","shell.execute_reply.started":"2024-08-30T16:04:28.466974Z","shell.execute_reply":"2024-08-30T16:04:28.497379Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"masks.drop(['ships'], axis=1, inplace=True)\nmasks.index+=1 \nmasks.head()","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:04:28.541478Z","iopub.execute_input":"2024-08-30T16:04:28.541914Z","iopub.status.idle":"2024-08-30T16:04:28.571334Z","shell.execute_reply.started":"2024-08-30T16:04:28.541874Z","shell.execute_reply":"2024-08-30T16:04:28.569764Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split                   \ntrain_ids, valid_ids = train_test_split(unique_img_ids, test_size = 0.3, stratify = unique_img_ids['ships'])","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:04:28.633058Z","iopub.execute_input":"2024-08-30T16:04:28.634114Z","iopub.status.idle":"2024-08-30T16:04:28.761267Z","shell.execute_reply.started":"2024-08-30T16:04:28.634063Z","shell.execute_reply":"2024-08-30T16:04:28.759962Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create train data frame\ntrain_df = pd.merge(masks, train_ids)\n\n# Create test data frame\nvalid_df = pd.merge(masks, valid_ids)","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:04:28.763366Z","iopub.execute_input":"2024-08-30T16:04:28.763848Z","iopub.status.idle":"2024-08-30T16:04:29.15866Z","shell.execute_reply.started":"2024-08-30T16:04:28.763804Z","shell.execute_reply":"2024-08-30T16:04:29.157442Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"There are ~\")\nprint(train_df.shape[0], 'training masks,')\nprint(valid_df.shape[0], 'validation masks.')","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:04:33.093704Z","iopub.execute_input":"2024-08-30T16:04:33.094639Z","iopub.status.idle":"2024-08-30T16:04:33.101726Z","shell.execute_reply.started":"2024-08-30T16:04:33.094592Z","shell.execute_reply":"2024-08-30T16:04:33.100405Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Clipping the max value of grouped_ship_count to be 7, minimum to be 0\ntrain_df['grouped_ship_count'] = train_df.ships.map(lambda x: (x+1)//2).clip(0,7)","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:04:33.107209Z","iopub.execute_input":"2024-08-30T16:04:33.108352Z","iopub.status.idle":"2024-08-30T16:04:33.254596Z","shell.execute_reply.started":"2024-08-30T16:04:33.108299Z","shell.execute_reply":"2024-08-30T16:04:33.252935Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.grouped_ship_count.value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:04:35.381156Z","iopub.execute_input":"2024-08-30T16:04:35.381731Z","iopub.status.idle":"2024-08-30T16:04:35.397481Z","shell.execute_reply.started":"2024-08-30T16:04:35.381683Z","shell.execute_reply":"2024-08-30T16:04:35.39603Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.head(10)","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:04:36.033888Z","iopub.execute_input":"2024-08-30T16:04:36.034414Z","iopub.status.idle":"2024-08-30T16:04:36.054363Z","shell.execute_reply.started":"2024-08-30T16:04:36.034369Z","shell.execute_reply":"2024-08-30T16:04:36.052773Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.sample(10)","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:04:37.420882Z","iopub.execute_input":"2024-08-30T16:04:37.421362Z","iopub.status.idle":"2024-08-30T16:04:37.446985Z","shell.execute_reply.started":"2024-08-30T16:04:37.421319Z","shell.execute_reply":"2024-08-30T16:04:37.445446Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Random Under-Sampling ships\ndef sample_ships(in_df, base_rep_val=1500):\n    '''\n    Input Args:\n    in_df - dataframe we want to apply this function\n    base_val - random sample of this value to be taken from the data frame\n    '''\n    if in_df['ships'].values[0]==0:                                                 \n        return in_df.sample(base_rep_val//3)  # Random 1500//3 = 500 samples taken whose ship count is 0 in an image \n    else:                                 \n        return in_df.sample(base_rep_val)    # Random 1500 samples taken whose ship count is not 0 in an image","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:04:39.657288Z","iopub.execute_input":"2024-08-30T16:04:39.658571Z","iopub.status.idle":"2024-08-30T16:04:39.666957Z","shell.execute_reply.started":"2024-08-30T16:04:39.658509Z","shell.execute_reply":"2024-08-30T16:04:39.665106Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Creating groups of ship counts and applying the sample_ships functions to randomly undersample the ships\nbalanced_train_df = train_df.groupby('grouped_ship_count').apply(sample_ships)\nbalanced_train_df.grouped_ship_count.value_counts() # In each group we have total of 1500 ships except 0 as we have decreased it even more to 500","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:04:40.233808Z","iopub.execute_input":"2024-08-30T16:04:40.234514Z","iopub.status.idle":"2024-08-30T16:04:40.295802Z","shell.execute_reply.started":"2024-08-30T16:04:40.234464Z","shell.execute_reply":"2024-08-30T16:04:40.29445Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Explaining what we just did if still not clear\nfor i in range(8):\n    df_val_counts = balanced_train_df[balanced_train_df.grouped_ship_count==i].ships.value_counts()\n    print(f\"Data frame for grouped ship count = {i}:-\\n{df_val_counts}\\nSum of Values:- {df_val_counts.values.sum()}\\n\\n\")","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:04:42.260239Z","iopub.execute_input":"2024-08-30T16:04:42.260734Z","iopub.status.idle":"2024-08-30T16:04:42.289459Z","shell.execute_reply.started":"2024-08-30T16:04:42.260689Z","shell.execute_reply":"2024-08-30T16:04:42.288271Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize = (15, 5))\nplt.suptitle(\"Train Data\", fontsize = 18, color = 'r', weight = 'bold')\nplt.subplot(1, 2, 1)\nimport seaborn as sns\nsns.distplot(train_df.ships)\nplt.title(\"Ship Counts - Before Balancing\", color = 'm', fontsize = 15)\nplt.ylabel(\"Count\", color = 'tab:pink', fontsize = 13)\nplt.xlabel(\"# Ships in an image\", color = 'tab:pink', fontsize = 13)\nplt.subplot(1, 2, 2)\nsns.distplot(balanced_train_df.ships)\nplt.title(\"Ship Counts - After Balancing\", color = 'm', fontsize = 15)\nplt.xlabel(\"# Ships in an image\", color = 'tab:pink', fontsize = 13)\nplt.tight_layout()","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:04:42.784327Z","iopub.execute_input":"2024-08-30T16:04:42.784803Z","iopub.status.idle":"2024-08-30T16:04:44.634791Z","shell.execute_reply.started":"2024-08-30T16:04:42.78476Z","shell.execute_reply":"2024-08-30T16:04:44.633296Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Parameters\nBATCH_SIZE = 4                 # Train batch size\nEDGE_CROP = 16                 # While building the model\nNB_EPOCHS = 5                  # Training epochs\nGAUSSIAN_NOISE = 0.1           # To be used in a layer in the model\nUPSAMPLE_MODE = 'SIMPLE'       # SIMPLE ==> UpSampling2D, else Conv2DTranspose\nNET_SCALING = None             # Downsampling inside the network                        \nIMG_SCALING = (1, 1)           # Downsampling in preprocessing\nVALID_IMG_COUNT = 400          # Valid batch size\nMAX_TRAIN_STEPS = 200          # Maximum number of steps_per_epoch in training","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:04:44.848908Z","iopub.execute_input":"2024-08-30T16:04:44.849419Z","iopub.status.idle":"2024-08-30T16:04:44.85668Z","shell.execute_reply.started":"2024-08-30T16:04:44.849376Z","shell.execute_reply":"2024-08-30T16:04:44.85529Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Image and Mask Generator\ndef make_image_gen(in_df, batch_size = BATCH_SIZE):\n    '''\n    Inputs -\n    in_df - data frame on which the function will be applied\n    batch_size - number of training examples in one iteration\n    '''\n    all_batches = list(in_df.groupby('ImageId'))                             # Group ImageIds and create list of that dataframe\n    out_rgb = []                                                             # Image list\n    out_mask = []                                                            # Mask list\n    while True:                                                              # Loop for every data\n        np.random.shuffle(all_batches)                                       # Shuffling the data\n        for c_img_id, c_masks in all_batches:                                # For img_id and msk_rle in all_batches\n            rgb_path = os.path.join(train_image_dir, c_img_id)               # Get the img path\n            c_img = imread(rgb_path)                                         # img array\n            c_mask = masks_as_image(c_masks['EncodedPixels'].values)         # Create mask of rle data for each ship in an img\n            out_rgb += [c_img]                                               # Append the current img in the out_rgb / img list\n            out_mask += [c_mask]                                             # Append the current mask in the out_mask / mask list\n            if len(out_rgb)>=batch_size:                                     # If length of list is more or equal to batch size then\n                yield np.stack(out_rgb)/255.0, np.stack(out_mask)            # Yeild the scaled img array (b/w 0 and 1) and mask array (0 for bg and 1 for ship)\n                out_rgb, out_mask=[], []                                     # Empty the lists to create another batch","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:04:45.418715Z","iopub.execute_input":"2024-08-30T16:04:45.419218Z","iopub.status.idle":"2024-08-30T16:04:45.430486Z","shell.execute_reply.started":"2024-08-30T16:04:45.41915Z","shell.execute_reply":"2024-08-30T16:04:45.42923Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Generate train data \ntrain_gen = make_image_gen(balanced_train_df)\n\n# Image and Mask\ntrain_x, train_y = next(train_gen)\n\n# Print the summary\nprint(f\"train_x ~\\nShape: {train_x.shape}\\nMin value: {train_x.min()}\\nMax value: {train_x.max()}\")\nprint(f\"\\ntrain_y ~\\nShape: {train_y.shape}\\nMin value: {train_y.min()}\\nMax value: {train_y.max()}\")","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:04:50.001157Z","iopub.execute_input":"2024-08-30T16:04:50.001659Z","iopub.status.idle":"2024-08-30T16:04:50.796475Z","shell.execute_reply.started":"2024-08-30T16:04:50.001617Z","shell.execute_reply":"2024-08-30T16:04:50.795062Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Visulaising train batch\nmontage_rgb = lambda x: np.stack([montage(x[:, :, :, i]) for i in range(x.shape[3])], -1)\nbatch_rgb = montage_rgb(train_x)                                                   # Create montage of img\nbatch_seg = montage(train_y[:, :, :, 0])                                           # Create montafe of msk\nbatch_overlap = mark_boundaries(batch_rgb, batch_seg.astype(int))                  # Create bounding box around ships in img\ntitles = [\"Images\", \"Segmentations\", \"Bounding Boxes on ships in Images\"]          # Titles for subplot\ncolors = ['g', 'm', 'b']                                                           # Colors to be used for title\ndisplay = [batch_rgb, batch_seg, batch_overlap]                                    # What to display in subplot\nplt.figure(figsize=(25,10))                                                        # Generate figure \nfor i in range(3):                                                                 # For i = 0, 1, 2, 3                           \n    plt.subplot(1, 3, i+1)                                                         # Create subplot\n    plt.imshow(display[i])                                                         # Display \n    plt.title(titles[i], fontsize = 18, color = colors[i])                         # Title \n    plt.axis('off')                                                                # Turn off the axis\nplt.suptitle(\"Batch Visualizations\", fontsize = 20, color = 'r', weight = 'bold')  # Add suptitle\nplt.tight_layout()  ","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:04:50.798472Z","iopub.execute_input":"2024-08-30T16:04:50.798881Z","iopub.status.idle":"2024-08-30T16:04:54.814683Z","shell.execute_reply.started":"2024-08-30T16:04:50.798838Z","shell.execute_reply":"2024-08-30T16:04:54.813065Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"valid_x, valid_y = next(make_image_gen(valid_df, VALID_IMG_COUNT))\nprint(f\"valid_x ~\\nShape: {valid_x.shape}\\nMin value: {valid_x.min()}\\nMax value: {valid_x.max()}\")\nprint(f\"\\nvalid_y ~\\nShape: {valid_y.shape}\\nMin value: {valid_y.min()}\\nMax value: {valid_y.max()}\")","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:04:54.817005Z","iopub.execute_input":"2024-08-30T16:04:54.81779Z","iopub.status.idle":"2024-08-30T16:05:14.721945Z","shell.execute_reply.started":"2024-08-30T16:04:54.817743Z","shell.execute_reply":"2024-08-30T16:05:14.720596Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Augmenting Data using ImageDataGenerator\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# Preparing image data generator arguments\ndg_args = dict(rotation_range = 15,            # Degree range for random rotations\n               horizontal_flip = True,         # Randomly flips the inputs horizontally\n               vertical_flip = True,           # Randomly flips the inputs vertically\n               data_format = 'channels_last')  # channels_last refer to (batch, height, width, channels)","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:09:01.574641Z","iopub.execute_input":"2024-08-30T16:09:01.575222Z","iopub.status.idle":"2024-08-30T16:09:01.607492Z","shell.execute_reply.started":"2024-08-30T16:09:01.575152Z","shell.execute_reply":"2024-08-30T16:09:01.605784Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_gen = ImageDataGenerator(**dg_args)\nlabel_gen = ImageDataGenerator(**dg_args)\n\ndef create_aug_gen(in_gen, seed = None):\n    '''\n    Takes in -\n    in_gen - train data generator, seed value\n    '''\n    np.random.seed(seed if seed is not None else np.random.choice(range(9999)))  # Randomly assign seed value if not provided\n    for in_x, in_y in in_gen:                                                    # For imgs and msks in train data generator\n        seed = 12                                                                # Seed value for imgs and msks must be same else augmentation won't be same\n        \n        # Create augmented imgs\n        g_x = image_gen.flow(255*in_x,                                           # Inverse scaling on imgs for augmentation                                       \n                             batch_size = in_x.shape[0],                         # batch_size = 3\n                             seed = seed,                                        # Seed\n                             shuffle=True)                                       # Shuffle the data\n        \n        # Create augmented masks\n        g_y = label_gen.flow(in_y,\n                             batch_size = in_x.shape[0],                       \n                             seed = seed,                                         \n                             shuffle=True)                                       \n        \n        '''Yeilds - augmented scaled imgs and msks array'''\n        yield next(g_x)/255.0, next(g_y)","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:09:03.479882Z","iopub.execute_input":"2024-08-30T16:09:03.481226Z","iopub.status.idle":"2024-08-30T16:09:03.494185Z","shell.execute_reply.started":"2024-08-30T16:09:03.481138Z","shell.execute_reply":"2024-08-30T16:09:03.492529Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Augment the train data\ncur_gen = create_aug_gen(train_gen, seed = 42)\nt_x, t_y = next(cur_gen)\nprint('x', t_x.shape, t_x.dtype, t_x.min(), t_x.max())\nprint('y', t_y.shape, t_y.dtype, t_y.min(), t_y.max())","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:09:04.388826Z","iopub.execute_input":"2024-08-30T16:09:04.389357Z","iopub.status.idle":"2024-08-30T16:09:05.441504Z","shell.execute_reply.started":"2024-08-30T16:09:04.389315Z","shell.execute_reply":"2024-08-30T16:09:05.440235Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize = (25, 10))\nax1.imshow(montage_rgb(t_x), cmap='gray')\nax1.set_title('Images', fontsize = 18, color = 'g')\nax1.axis('off')\nax2.imshow(montage(t_y[:, :, :, 0]), cmap='Blues_r')\nax2.set_title('Masks', fontsize = 18, color = 'r')\nax2.axis('off')\nax3.imshow(mark_boundaries(montage_rgb(t_x), montage(t_y[:, :, :, 0].astype(int))))\nax3.set_title('Bounding Box', fontsize = 18, color = 'b')\nax3.axis('off')\nplt.tight_layout()","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:09:06.273022Z","iopub.execute_input":"2024-08-30T16:09:06.274125Z","iopub.status.idle":"2024-08-30T16:09:09.872255Z","shell.execute_reply.started":"2024-08-30T16:09:06.27407Z","shell.execute_reply":"2024-08-30T16:09:09.871057Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:09:17.514832Z","iopub.execute_input":"2024-08-30T16:09:17.515411Z","iopub.status.idle":"2024-08-30T16:09:18.003372Z","shell.execute_reply.started":"2024-08-30T16:09:17.515361Z","shell.execute_reply":"2024-08-30T16:09:18.001813Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras import models, layers\n\n# Conv2DTranspose upsampling\ndef upsample_conv(filters, kernel_size, strides, padding):\n    return layers.Conv2DTranspose(filters, kernel_size, strides=strides, padding=padding)\n# Upsampling without Conv2DTranspose\ndef upsample_simple(filters, kernel_size, strides, padding):\n    return layers.UpSampling2D(strides)\n\n# Upsampling method choice\nif UPSAMPLE_MODE=='DECONV':\n    upsample=upsample_conv\nelse:\n    upsample=upsample_simple\n\n# Building the layers of UNET\ninput_img = layers.Input(t_x.shape[1:], name = 'RGB_Input')\npp_in_layer = input_img\n\n# If NET_SCALING is defined then do the next step else continue ahead\nif NET_SCALING is not None:\n    pp_in_layer = layers.AvgPool2D(NET_SCALING)(pp_in_layer)\n\n# To avoid overfitting and fastening the process of training\npp_in_layer = layers.GaussianNoise(GAUSSIAN_NOISE)(pp_in_layer)                       # Useful to mitigate overfitting\npp_in_layer = layers.BatchNormalization()(pp_in_layer)                                # Allows using higher learning rate without causing problems with gradients\n\n\n## Downsample (C-->C-->MP)\n\nc1 = layers.Conv2D(8, (3, 3), activation='relu', padding='same') (pp_in_layer)\nc1 = layers.Conv2D(8, (3, 3), activation='relu', padding='same') (c1)\np1 = layers.MaxPooling2D((2, 2)) (c1)\n\nc2 = layers.Conv2D(16, (3, 3), activation='relu', padding='same') (p1)\nc2 = layers.Conv2D(16, (3, 3), activation='relu', padding='same') (c2)\np2 = layers.MaxPooling2D((2, 2)) (c2)\n\nc3 = layers.Conv2D(32, (3, 3), activation='relu', padding='same') (p2)\nc3 = layers.Conv2D(32, (3, 3), activation='relu', padding='same') (c3)\np3 = layers.MaxPooling2D((2, 2)) (c3)\n\nc4 = layers.Conv2D(64, (3, 3), activation='relu', padding='same') (p3)\nc4 = layers.Conv2D(64, (3, 3), activation='relu', padding='same') (c4)\np4 = layers.MaxPooling2D(pool_size=(2, 2)) (c4)\n\n\nc5 = layers.Conv2D(128, (3, 3), activation='relu', padding='same') (p4)\nc5 = layers.Conv2D(128, (3, 3), activation='relu', padding='same') (c5)\n\n## Upsample (U --> Concat --> C --> C)\n\nu6 = upsample(64, (2, 2), strides=(2, 2), padding='same') (c5)\nu6 = layers.concatenate([u6, c4])\nc6 = layers.Conv2D(64, (3, 3), activation='relu', padding='same') (u6)\nc6 = layers.Conv2D(64, (3, 3), activation='relu', padding='same') (c6)\n\nu7 = upsample(32, (2, 2), strides=(2, 2), padding='same') (c6)\nu7 = layers.concatenate([u7, c3])\nc7 = layers.Conv2D(32, (3, 3), activation='relu', padding='same') (u7)\nc7 = layers.Conv2D(32, (3, 3), activation='relu', padding='same') (c7)\n\nu8 = upsample(16, (2, 2), strides=(2, 2), padding='same') (c7)\nu8 = layers.concatenate([u8, c2])\nc8 = layers.Conv2D(16, (3, 3), activation='relu', padding='same') (u8)\nc8 = layers.Conv2D(16, (3, 3), activation='relu', padding='same') (c8)\n\nu9 = upsample(8, (2, 2), strides=(2, 2), padding='same') (c8)\nu9 = layers.concatenate([u9, c1], axis=3)\nc9 = layers.Conv2D(8, (3, 3), activation='relu', padding='same') (u9)\nc9 = layers.Conv2D(8, (3, 3), activation='relu', padding='same') (c9)\n\nd = layers.Conv2D(1, (1, 1), activation='sigmoid') (c9)\nd = layers.Cropping2D((EDGE_CROP, EDGE_CROP))(d)\nd = layers.ZeroPadding2D((EDGE_CROP, EDGE_CROP))(d)\n\nif NET_SCALING is not None:\n    d = layers.UpSampling2D(NET_SCALING)(d)\n\nseg_model = models.Model(inputs=[input_img], outputs=[d])\n\nseg_model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:09:18.466758Z","iopub.execute_input":"2024-08-30T16:09:18.467265Z","iopub.status.idle":"2024-08-30T16:09:18.969991Z","shell.execute_reply.started":"2024-08-30T16:09:18.467214Z","shell.execute_reply":"2024-08-30T16:09:18.968671Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Compute dice coefficient, loss with BCE and compile the model\nimport keras.backend as K\nfrom tensorflow.keras.optimizers import Adam\nfrom keras.losses import binary_crossentropy\n\n# Dice coeff\ndef dice_coef(y_true, y_pred, smooth=1):\n    intersection = K.sum(y_true * y_pred, axis=[1,2,3]  )                         # int = y_true ∩ y_pred\n    union = K.sum(y_true, axis=[1,2,3]) + K.sum(y_pred, axis=[1,2,3])           # un = y_true_flatten ed ∪ y_pred_flattened\n    return K.mean( (2. * intersection + smooth) / (union + smooth), axis=0)     # dice = 2 * int + 1 / un + 1\n\n# Dice with BCE\ndef dice_p_bce(y_true, y_pred):\n    '''\n    Compute this function based on the explanation\n    - use alpha = 1e-3\n    '''\n    \n    combo_loss = \"Something\"\n         \n    return combo_loss\n\n# Compile the model\nseg_model.compile(optimizer=Adam(1e-4, decay=1e-6), loss=dice_p_bce, metrics=[dice_coef])","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:09:25.72461Z","iopub.execute_input":"2024-08-30T16:09:25.725136Z","iopub.status.idle":"2024-08-30T16:09:25.753471Z","shell.execute_reply.started":"2024-08-30T16:09:25.725094Z","shell.execute_reply":"2024-08-30T16:09:25.751774Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau\n\n# Define the weight path with the correct file extension\nweight_path = \"{}_weights.best.weights.h5\".format('seg_model')\n\n# Monitor validation dice coefficient and save the best model weights\ncheckpoint = ModelCheckpoint(weight_path, monitor='val_dice_coef', verbose=1, \n                             save_best_only=True, mode='max', save_weights_only=True)\n\n# Reduce Learning Rate on Plateau\nreduceLROnPlat = ReduceLROnPlateau(monitor='val_dice_coef', factor=0.5, \n                                   patience=3, \n                                   verbose=1, mode='max', epsilon=0.0001, cooldown=2, min_lr=1e-6)\n\n# Stop training once there is no improvement seen in the model\nearly = EarlyStopping(monitor=\"val_dice_coef\", \n                      mode=\"max\", \n                      patience=15) # probably needs to be more patient, but kaggle time is limited\n\n# Callbacks ready\ncallbacks_list = [checkpoint, early, reduceLROnPlat]","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:10:21.412131Z","iopub.execute_input":"2024-08-30T16:10:21.412784Z","iopub.status.idle":"2024-08-30T16:10:21.425983Z","shell.execute_reply.started":"2024-08-30T16:10:21.412737Z","shell.execute_reply":"2024-08-30T16:10:21.423917Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for batch in aug_gen:\n    print(f\"Image batch dtype: {batch[0].dtype}, shape: {batch[0].shape}\")\n    print(f\"Label batch dtype: {batch[1].dtype}, shape: {batch[1].shape}\")\n    break  # Stop after the first batch to inspect\n    \ndef preprocess_image(image):\n    image = tf.image.convert_image_dtype(image, dtype=tf.float32)\n    return image\n\nvalid_x = valid_x.astype('float32')\nvalid_y = valid_y.astype('float32')","metadata":{"execution":{"iopub.status.busy":"2024-08-30T16:13:07.636376Z","iopub.execute_input":"2024-08-30T16:13:07.636947Z","iopub.status.idle":"2024-08-30T16:13:13.930696Z","shell.execute_reply.started":"2024-08-30T16:13:07.6369Z","shell.execute_reply":"2024-08-30T16:13:13.929421Z"},"trusted":true},"execution_count":null,"outputs":[]}]}