{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":9988,"databundleVersionId":868324,"sourceType":"competition"}],"dockerImageVersionId":30698,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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\n#B 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-06-11T17:24:12.258829Z","iopub.execute_input":"2024-06-11T17:24:12.259387Z","iopub.status.idle":"2024-06-11T17:24:13.314177Z","shell.execute_reply.started":"2024-06-11T17:24:12.259360Z","shell.execute_reply":"2024-06-11T17:24:13.313207Z"},"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-06-11T17:24:13.316114Z","iopub.execute_input":"2024-06-11T17:24:13.316563Z","iopub.status.idle":"2024-06-11T17:24:15.341807Z","shell.execute_reply.started":"2024-06-11T17:24:13.316529Z","shell.execute_reply":"2024-06-11T17:24:15.340869Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Train and test directories\ntrain_image_dir = '../input/airbus-ship-detection/train_v2'\ntest_image_dir = \"../input/airbus-ship-detection/test_v2\"","metadata":{"execution":{"iopub.status.busy":"2024-06-11T17:24:15.343385Z","iopub.execute_input":"2024-06-11T17:24:15.343848Z","iopub.status.idle":"2024-06-11T17:24:15.348702Z","shell.execute_reply.started":"2024-06-11T17:24:15.343810Z","shell.execute_reply":"2024-06-11T17:24:15.347635Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ntrain_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-06-11T17:24:15.351722Z","iopub.execute_input":"2024-06-11T17:24:15.352039Z","iopub.status.idle":"2024-06-11T17:24:23.799727Z","shell.execute_reply.started":"2024-06-11T17:24:15.352012Z","shell.execute_reply":"2024-06-11T17:24:23.798756Z"},"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-06-11T17:24:23.800809Z","iopub.execute_input":"2024-06-11T17:24:23.801105Z","iopub.status.idle":"2024-06-11T17:24:28.338689Z","shell.execute_reply.started":"2024-06-11T17:24:23.801079Z","shell.execute_reply":"2024-06-11T17:24:28.337170Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"masks = pd.read_csv(\"../input/airbus-ship-detection/train_ship_segmentations_v2.csv\")\nmasks.head(10)","metadata":{"execution":{"iopub.status.busy":"2024-06-11T17:24:28.340489Z","iopub.execute_input":"2024-06-11T17:24:28.340948Z","iopub.status.idle":"2024-06-11T17:24:29.379649Z","shell.execute_reply.started":"2024-06-11T17:24:28.340892Z","shell.execute_reply":"2024-06-11T17:24:29.378717Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#RUN LENGTH ENCODING AND DECODING\nrow_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\n","metadata":{"execution":{"iopub.status.busy":"2024-06-11T17:24:29.381126Z","iopub.execute_input":"2024-06-11T17:24:29.381512Z","iopub.status.idle":"2024-06-11T17:24:29.394800Z","shell.execute_reply.started":"2024-06-11T17:24:29.381477Z","shell.execute_reply":"2024-06-11T17:24:29.393897Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# mask data frame\n\n# Original image from training set\nimg_arr = imread(train_image_dir + '/' + '0005d01c8.jpg')\nplt.figure(figsize=(15,8))\nplt.imshow(img_arr)\nplt.show()\nimg_arr.shape","metadata":{"execution":{"iopub.status.busy":"2024-06-11T17:24:29.395787Z","iopub.execute_input":"2024-06-11T17:24:29.396062Z","iopub.status.idle":"2024-06-11T17:24:29.833138Z","shell.execute_reply.started":"2024-06-11T17:24:29.396039Z","shell.execute_reply":"2024-06-11T17:24:29.832141Z"},"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-06-11T17:24:29.834404Z","iopub.execute_input":"2024-06-11T17:24:29.834702Z","iopub.status.idle":"2024-06-11T17:24:29.864690Z","shell.execute_reply.started":"2024-06-11T17:24:29.834676Z","shell.execute_reply":"2024-06-11T17:24:29.863690Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mask_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-06-11T17:24:29.869113Z","iopub.execute_input":"2024-06-11T17:24:29.869453Z","iopub.status.idle":"2024-06-11T17:24:29.874423Z","shell.execute_reply.started":"2024-06-11T17:24:29.869426Z","shell.execute_reply":"2024-06-11T17:24:29.873422Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\nsplit = mask_lst[0].split()\nprint(split)","metadata":{"execution":{"iopub.status.busy":"2024-06-11T17:24:29.875492Z","iopub.execute_input":"2024-06-11T17:24:29.875835Z","iopub.status.idle":"2024-06-11T17:24:29.884630Z","shell.execute_reply.started":"2024-06-11T17:24:29.875804Z","shell.execute_reply":"2024-06-11T17:24:29.883666Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"starts, lengths = [np.array(x, dtype = int) for x in (split[::2], split[1::2])]\nstarts, lengths","metadata":{"execution":{"iopub.status.busy":"2024-06-11T17:24:29.885716Z","iopub.execute_input":"2024-06-11T17:24:29.886046Z","iopub.status.idle":"2024-06-11T17:24:29.897543Z","shell.execute_reply.started":"2024-06-11T17:24:29.886014Z","shell.execute_reply":"2024-06-11T17:24:29.896661Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#ending pixels. \n'''Examples:- \n56010 1 ---> Starts at 56010 and ends at 56010\n56777 3 ---> Starts at 56777 and ends at 56779\n57544 6 ---> Starts at 57544 and ends at 57549'''\nends = starts + lengths - 1\npd.DataFrame({\n    'Starts' : starts,\n    'Lengths' : lengths,\n    'Ends' : ends\n}).head(10)","metadata":{"execution":{"iopub.status.busy":"2024-06-11T17:24:29.898646Z","iopub.execute_input":"2024-06-11T17:24:29.898879Z","iopub.status.idle":"2024-06-11T17:24:29.911979Z","shell.execute_reply.started":"2024-06-11T17:24:29.898858Z","shell.execute_reply":"2024-06-11T17:24:29.910978Z"},"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-06-11T17:24:29.913096Z","iopub.execute_input":"2024-06-11T17:24:29.913361Z","iopub.status.idle":"2024-06-11T17:24:29.920856Z","shell.execute_reply.started":"2024-06-11T17:24:29.913338Z","shell.execute_reply":"2024-06-11T17:24:29.920098Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img[56776:56781]","metadata":{"execution":{"iopub.status.busy":"2024-06-11T17:24:29.921954Z","iopub.execute_input":"2024-06-11T17:24:29.922254Z","iopub.status.idle":"2024-06-11T17:24:29.930803Z","shell.execute_reply.started":"2024-06-11T17:24:29.922229Z","shell.execute_reply":"2024-06-11T17:24:29.929888Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\n\n\nsplit_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-06-11T17:24:29.931890Z","iopub.execute_input":"2024-06-11T17:24:29.932586Z","iopub.status.idle":"2024-06-11T17:24:29.939731Z","shell.execute_reply.started":"2024-06-11T17:24:29.932555Z","shell.execute_reply":"2024-06-11T17:24:29.938968Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\n\n\n\n\nimg = 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-06-11T17:24:29.940711Z","iopub.execute_input":"2024-06-11T17:24:29.941016Z","iopub.status.idle":"2024-06-11T17:24:29.953354Z","shell.execute_reply.started":"2024-06-11T17:24:29.940993Z","shell.execute_reply":"2024-06-11T17:24:29.952382Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n#final = np.expand_dims(final, axis=-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-06-11T17:24:29.954471Z","iopub.execute_input":"2024-06-11T17:24:29.954741Z","iopub.status.idle":"2024-06-11T17:24:30.981845Z","shell.execute_reply.started":"2024-06-11T17:24:29.954718Z","shell.execute_reply":"2024-06-11T17:24:30.980935Z"},"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-06-11T17:24:30.983039Z","iopub.execute_input":"2024-06-11T17:24:30.983322Z","iopub.status.idle":"2024-06-11T17:24:31.768753Z","shell.execute_reply.started":"2024-06-11T17:24:30.983297Z","shell.execute_reply":"2024-06-11T17:24:31.767803Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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-06-11T17:24:31.770051Z","iopub.execute_input":"2024-06-11T17:24:31.770314Z","iopub.status.idle":"2024-06-11T17:24:31.779987Z","shell.execute_reply.started":"2024-06-11T17:24:31.770290Z","shell.execute_reply":"2024-06-11T17:24:31.779126Z"},"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-06-11T17:24:31.781058Z","iopub.execute_input":"2024-06-11T17:24:31.781367Z","iopub.status.idle":"2024-06-11T17:24:35.783383Z","shell.execute_reply.started":"2024-06-11T17:24:31.781338Z","shell.execute_reply":"2024-06-11T17:24:35.782373Z"},"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-06-11T17:24:35.784749Z","iopub.execute_input":"2024-06-11T17:24:35.785463Z","iopub.status.idle":"2024-06-11T17:24:35.969695Z","shell.execute_reply.started":"2024-06-11T17:24:35.785429Z","shell.execute_reply":"2024-06-11T17:24:35.968814Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"unique_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-06-11T17:24:35.971005Z","iopub.execute_input":"2024-06-11T17:24:35.971653Z","iopub.status.idle":"2024-06-11T17:24:36.224968Z","shell.execute_reply.started":"2024-06-11T17:24:35.971617Z","shell.execute_reply":"2024-06-11T17:24:36.223965Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"unique_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-06-11T17:24:36.225981Z","iopub.execute_input":"2024-06-11T17:24:36.226235Z","iopub.status.idle":"2024-06-11T17:24:36.309385Z","shell.execute_reply.started":"2024-06-11T17:24:36.226212Z","shell.execute_reply":"2024-06-11T17:24:36.308407Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"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-06-11T17:24:36.310470Z","iopub.execute_input":"2024-06-11T17:24:36.310744Z","iopub.status.idle":"2024-06-11T17:24:37.151145Z","shell.execute_reply.started":"2024-06-11T17:24:36.310719Z","shell.execute_reply":"2024-06-11T17:24:37.150199Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"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-06-11T17:24:37.152587Z","iopub.execute_input":"2024-06-11T17:24:37.153237Z","iopub.status.idle":"2024-06-11T17:24:37.170822Z","shell.execute_reply.started":"2024-06-11T17:24:37.153198Z","shell.execute_reply":"2024-06-11T17:24:37.169956Z"},"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-06-11T17:24:37.172046Z","iopub.execute_input":"2024-06-11T17:24:37.172329Z","iopub.status.idle":"2024-06-11T17:24:37.444062Z","shell.execute_reply.started":"2024-06-11T17:24:37.172304Z","shell.execute_reply":"2024-06-11T17:24:37.443210Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#create train and test data frame\ntrain_df = pd.merge(masks, train_ids)\n\n\nvalid_df = pd.merge(masks, valid_ids)","metadata":{"execution":{"iopub.status.busy":"2024-06-11T17:24:37.449537Z","iopub.execute_input":"2024-06-11T17:24:37.449818Z","iopub.status.idle":"2024-06-11T17:24:37.694468Z","shell.execute_reply.started":"2024-06-11T17:24:37.449795Z","shell.execute_reply":"2024-06-11T17:24:37.693601Z"},"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-06-11T17:24:37.695674Z","iopub.execute_input":"2024-06-11T17:24:37.695969Z","iopub.status.idle":"2024-06-11T17:24:37.701809Z","shell.execute_reply.started":"2024-06-11T17:24:37.695943Z","shell.execute_reply":"2024-06-11T17:24:37.700776Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport seaborn as sns\n\nplt.figure(figsize=(6, 10))\nsns.countplot(data=train_df, x='ships')\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-06-11T17:24:37.703001Z","iopub.execute_input":"2024-06-11T17:24:37.703283Z","iopub.status.idle":"2024-06-11T17:24:37.953648Z","shell.execute_reply.started":"2024-06-11T17:24:37.703258Z","shell.execute_reply":"2024-06-11T17:24:37.952741Z"},"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-06-11T17:24:37.954854Z","iopub.execute_input":"2024-06-11T17:24:37.955225Z","iopub.status.idle":"2024-06-11T17:24:38.083421Z","shell.execute_reply.started":"2024-06-11T17:24:37.955192Z","shell.execute_reply":"2024-06-11T17:24:38.082676Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Check\ntrain_df.grouped_ship_count.value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-06-11T17:24:38.084496Z","iopub.execute_input":"2024-06-11T17:24:38.084758Z","iopub.status.idle":"2024-06-11T17:24:38.094066Z","shell.execute_reply.started":"2024-06-11T17:24:38.084733Z","shell.execute_reply":"2024-06-11T17:24:38.092983Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Top 10 data\ntrain_df.head(10)","metadata":{"execution":{"iopub.status.busy":"2024-06-11T17:24:38.095412Z","iopub.execute_input":"2024-06-11T17:24:38.095764Z","iopub.status.idle":"2024-06-11T17:24:38.112293Z","shell.execute_reply.started":"2024-06-11T17:24:38.095735Z","shell.execute_reply":"2024-06-11T17:24:38.111267Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.sample(10)","metadata":{"execution":{"iopub.status.busy":"2024-06-11T17:24:38.113594Z","iopub.execute_input":"2024-06-11T17:24:38.113900Z","iopub.status.idle":"2024-06-11T17:24:38.135732Z","shell.execute_reply.started":"2024-06-11T17:24:38.113873Z","shell.execute_reply":"2024-06-11T17:24:38.134772Z"},"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-06-11T17:24:38.136872Z","iopub.execute_input":"2024-06-11T17:24:38.137263Z","iopub.status.idle":"2024-06-11T17:24:38.143597Z","shell.execute_reply.started":"2024-06-11T17:24:38.137234Z","shell.execute_reply":"2024-06-11T17:24:38.142452Z"},"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-06-11T17:24:38.145032Z","iopub.execute_input":"2024-06-11T17:24:38.145406Z","iopub.status.idle":"2024-06-11T17:24:38.191164Z","shell.execute_reply.started":"2024-06-11T17:24:38.145370Z","shell.execute_reply":"2024-06-11T17:24:38.190037Z"},"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\")\n","metadata":{"execution":{"iopub.status.busy":"2024-06-11T17:24:38.192335Z","iopub.execute_input":"2024-06-11T17:24:38.192638Z","iopub.status.idle":"2024-06-11T17:24:38.212127Z","shell.execute_reply.started":"2024-06-11T17:24:38.192612Z","shell.execute_reply":"2024-06-11T17:24:38.211053Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport seaborn as sns\n\nplt.figure(figsize=(15, 5))\nplt.suptitle(\"Train Data\", fontsize=18, color='r', weight='bold')\n\n\nplt.subplot(1, 2, 1)\nsns.countplot(data=train_df, x='ships', palette='Set2')\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)\n\nplt.subplot(1, 2, 2)\nsns.countplot(data=balanced_train_df, x='ships', palette='Set2')\nplt.title(\"Ship Counts - After Balancing\", color='m', fontsize=15)\nplt.xlabel(\"# Ships in an image\", color='tab:pink', fontsize=13)\n\nplt.tight_layout()\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-06-11T17:24:38.214791Z","iopub.execute_input":"2024-06-11T17:24:38.215547Z","iopub.status.idle":"2024-06-11T17:24:38.921728Z","shell.execute_reply.started":"2024-06-11T17:24:38.215518Z","shell.execute_reply":"2024-06-11T17:24:38.920772Z"},"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-06-11T17:24:38.922869Z","iopub.execute_input":"2024-06-11T17:24:38.923140Z","iopub.status.idle":"2024-06-11T17:24:38.928599Z","shell.execute_reply.started":"2024-06-11T17:24:38.923118Z","shell.execute_reply":"2024-06-11T17:24:38.927578Z"},"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-06-11T17:24:38.929769Z","iopub.execute_input":"2024-06-11T17:24:38.930111Z","iopub.status.idle":"2024-06-11T17:24:38.940132Z","shell.execute_reply.started":"2024-06-11T17:24:38.930085Z","shell.execute_reply":"2024-06-11T17:24:38.939266Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\n# 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-06-11T17:24:38.941093Z","iopub.execute_input":"2024-06-11T17:24:38.941413Z","iopub.status.idle":"2024-06-11T17:24:39.721868Z","shell.execute_reply.started":"2024-06-11T17:24:38.941381Z","shell.execute_reply":"2024-06-11T17:24:39.720882Z"},"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()                                                                 # Layout for subplot","metadata":{"execution":{"iopub.status.busy":"2024-06-11T17:24:39.723057Z","iopub.execute_input":"2024-06-11T17:24:39.723351Z","iopub.status.idle":"2024-06-11T17:24:42.868963Z","shell.execute_reply.started":"2024-06-11T17:24:39.723326Z","shell.execute_reply":"2024-06-11T17:24:42.868089Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Prepare validation data\nvalid_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-06-11T17:24:42.870294Z","iopub.execute_input":"2024-06-11T17:24:42.870694Z","iopub.status.idle":"2024-06-11T17:24:57.971690Z","shell.execute_reply.started":"2024-06-11T17:24:42.870664Z","shell.execute_reply":"2024-06-11T17:24:57.970624Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Augmenting Data using ImageDataGenerator\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\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)\n","metadata":{"execution":{"iopub.status.busy":"2024-06-11T17:24:57.973800Z","iopub.execute_input":"2024-06-11T17:24:57.974857Z","iopub.status.idle":"2024-06-11T17:25:10.650836Z","shell.execute_reply.started":"2024-06-11T17:24:57.974811Z","shell.execute_reply":"2024-06-11T17:25:10.650018Z"},"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-06-11T17:25:10.651931Z","iopub.execute_input":"2024-06-11T17:25:10.652455Z","iopub.status.idle":"2024-06-11T17:25:10.660163Z","shell.execute_reply.started":"2024-06-11T17:25:10.652429Z","shell.execute_reply":"2024-06-11T17:25:10.659262Z"},"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-06-11T17:25:10.661411Z","iopub.execute_input":"2024-06-11T17:25:10.662054Z","iopub.status.idle":"2024-06-11T17:25:11.421640Z","shell.execute_reply.started":"2024-06-11T17:25:10.662028Z","shell.execute_reply":"2024-06-11T17:25:11.420645Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Final display before passing data into model\nfig, (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-06-11T17:25:11.422902Z","iopub.execute_input":"2024-06-11T17:25:11.423279Z","iopub.status.idle":"2024-06-11T17:25:14.228518Z","shell.execute_reply.started":"2024-06-11T17:25:11.423245Z","shell.execute_reply":"2024-06-11T17:25:14.227564Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Build U-Net model\nfrom 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-06-11T17:25:14.230051Z","iopub.execute_input":"2024-06-11T17:25:14.230379Z","iopub.status.idle":"2024-06-11T17:25:15.329948Z","shell.execute_reply.started":"2024-06-11T17:25:14.230351Z","shell.execute_reply":"2024-06-11T17:25:15.328901Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}