{"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":"none","dataSources":[{"sourceId":9988,"databundleVersionId":868324,"sourceType":"competition"}],"dockerImageVersionId":30698,"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\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-05-04T10:50:04.794458Z","iopub.execute_input":"2024-05-04T10:50:04.794882Z","iopub.status.idle":"2024-05-04T10:50:04.800037Z","shell.execute_reply.started":"2024-05-04T10:50:04.794851Z","shell.execute_reply":"2024-05-04T10:50:04.798971Z"},"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-05-04T10:50:07.529344Z","iopub.execute_input":"2024-05-04T10:50:07.529743Z","iopub.status.idle":"2024-05-04T10:50:07.536048Z","shell.execute_reply.started":"2024-05-04T10:50:07.529712Z","shell.execute_reply":"2024-05-04T10:50:07.534928Z"},"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-05-04T10:50:18.154133Z","iopub.execute_input":"2024-05-04T10:50:18.154601Z","iopub.status.idle":"2024-05-04T10:50:18.159509Z","shell.execute_reply.started":"2024-05-04T10:50:18.154560Z","shell.execute_reply":"2024-05-04T10:50:18.158503Z"},"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-05-04T10:50:20.704144Z","iopub.execute_input":"2024-05-04T10:50:20.706504Z","iopub.status.idle":"2024-05-04T10:50:22.033843Z","shell.execute_reply.started":"2024-05-04T10:50:20.706466Z","shell.execute_reply":"2024-05-04T10:50:22.032760Z"},"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-05-04T10:50:23.403862Z","iopub.execute_input":"2024-05-04T10:50:23.404736Z","iopub.status.idle":"2024-05-04T10:50:28.112733Z","shell.execute_reply.started":"2024-05-04T10:50:23.404703Z","shell.execute_reply":"2024-05-04T10:50:28.111369Z"},"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-05-04T10:50:35.498601Z","iopub.execute_input":"2024-05-04T10:50:35.499354Z","iopub.status.idle":"2024-05-04T10:50:36.141740Z","shell.execute_reply.started":"2024-05-04T10:50:35.499309Z","shell.execute_reply":"2024-05-04T10:50:36.140684Z"},"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-05-04T10:50:38.784500Z","iopub.execute_input":"2024-05-04T10:50:38.784873Z","iopub.status.idle":"2024-05-04T10:50:38.798497Z","shell.execute_reply.started":"2024-05-04T10:50:38.784846Z","shell.execute_reply":"2024-05-04T10:50:38.797429Z"},"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-05-04T10:50:51.994786Z","iopub.execute_input":"2024-05-04T10:50:51.995506Z","iopub.status.idle":"2024-05-04T10:50:52.467609Z","shell.execute_reply.started":"2024-05-04T10:50:51.995471Z","shell.execute_reply":"2024-05-04T10:50:52.466623Z"},"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-05-04T10:50:59.880284Z","iopub.execute_input":"2024-05-04T10:50:59.880881Z","iopub.status.idle":"2024-05-04T10:50:59.906567Z","shell.execute_reply.started":"2024-05-04T10:50:59.880847Z","shell.execute_reply":"2024-05-04T10:50:59.905352Z"},"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-05-04T10:50:59.908361Z","iopub.execute_input":"2024-05-04T10:50:59.908701Z","iopub.status.idle":"2024-05-04T10:50:59.914640Z","shell.execute_reply.started":"2024-05-04T10:50:59.908673Z","shell.execute_reply":"2024-05-04T10:50:59.913438Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\nsplit = mask_lst[0].split()\nprint(split)","metadata":{"execution":{"iopub.status.busy":"2024-05-04T10:50:59.916040Z","iopub.execute_input":"2024-05-04T10:50:59.916402Z","iopub.status.idle":"2024-05-04T10:50:59.922540Z","shell.execute_reply.started":"2024-05-04T10:50:59.916375Z","shell.execute_reply":"2024-05-04T10:50:59.921462Z"},"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-05-04T10:50:59.924599Z","iopub.execute_input":"2024-05-04T10:50:59.924971Z","iopub.status.idle":"2024-05-04T10:50:59.935114Z","shell.execute_reply.started":"2024-05-04T10:50:59.924902Z","shell.execute_reply":"2024-05-04T10:50:59.933892Z"},"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-05-04T10:54:47.214501Z","iopub.execute_input":"2024-05-04T10:54:47.215597Z","iopub.status.idle":"2024-05-04T10:54:47.226882Z","shell.execute_reply.started":"2024-05-04T10:54:47.215560Z","shell.execute_reply":"2024-05-04T10:54:47.225799Z"},"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-05-04T10:55:00.269753Z","iopub.execute_input":"2024-05-04T10:55:00.270683Z","iopub.status.idle":"2024-05-04T10:55:00.275712Z","shell.execute_reply.started":"2024-05-04T10:55:00.270644Z","shell.execute_reply":"2024-05-04T10:55:00.274907Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img[56776:56781]","metadata":{"execution":{"iopub.status.busy":"2024-05-04T10:55:00.281204Z","iopub.execute_input":"2024-05-04T10:55:00.281523Z","iopub.status.idle":"2024-05-04T10:55:00.288172Z","shell.execute_reply.started":"2024-05-04T10:55:00.281498Z","shell.execute_reply":"2024-05-04T10:55:00.287180Z"},"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-05-04T10:55:14.549512Z","iopub.execute_input":"2024-05-04T10:55:14.550187Z","iopub.status.idle":"2024-05-04T10:55:14.556780Z","shell.execute_reply.started":"2024-05-04T10:55:14.550151Z","shell.execute_reply":"2024-05-04T10:55:14.555628Z"},"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-05-04T10:55:15.079728Z","iopub.execute_input":"2024-05-04T10:55:15.080541Z","iopub.status.idle":"2024-05-04T10:55:15.086791Z","shell.execute_reply.started":"2024-05-04T10:55:15.080502Z","shell.execute_reply":"2024-05-04T10:55:15.085696Z"},"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-05-04T10:55:18.084587Z","iopub.execute_input":"2024-05-04T10:55:18.085001Z","iopub.status.idle":"2024-05-04T10:55:18.991167Z","shell.execute_reply.started":"2024-05-04T10:55:18.084967Z","shell.execute_reply":"2024-05-04T10:55:18.990368Z"},"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-05-04T10:55:33.535357Z","iopub.execute_input":"2024-05-04T10:55:33.535957Z","iopub.status.idle":"2024-05-04T10:55:34.432988Z","shell.execute_reply.started":"2024-05-04T10:55:33.535897Z","shell.execute_reply":"2024-05-04T10:55:34.431962Z"},"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-05-04T10:55:39.405174Z","iopub.execute_input":"2024-05-04T10:55:39.405578Z","iopub.status.idle":"2024-05-04T10:55:39.414263Z","shell.execute_reply.started":"2024-05-04T10:55:39.405547Z","shell.execute_reply":"2024-05-04T10:55:39.413183Z"},"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-05-04T10:55:51.044895Z","iopub.execute_input":"2024-05-04T10:55:51.045329Z","iopub.status.idle":"2024-05-04T10:55:55.260744Z","shell.execute_reply.started":"2024-05-04T10:55:51.045297Z","shell.execute_reply":"2024-05-04T10:55:55.257184Z"},"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-05-04T10:56:11.847544Z","iopub.execute_input":"2024-05-04T10:56:11.848280Z","iopub.status.idle":"2024-05-04T10:56:11.967517Z","shell.execute_reply.started":"2024-05-04T10:56:11.848245Z","shell.execute_reply":"2024-05-04T10:56:11.966393Z"},"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-05-04T10:56:12.064343Z","iopub.execute_input":"2024-05-04T10:56:12.064949Z","iopub.status.idle":"2024-05-04T10:56:12.238757Z","shell.execute_reply.started":"2024-05-04T10:56:12.064900Z","shell.execute_reply":"2024-05-04T10:56:12.237491Z"},"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-05-04T10:56:12.241290Z","iopub.execute_input":"2024-05-04T10:56:12.242368Z","iopub.status.idle":"2024-05-04T10:56:12.302997Z","shell.execute_reply.started":"2024-05-04T10:56:12.242326Z","shell.execute_reply":"2024-05-04T10:56:12.302196Z"},"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-05-04T10:56:17.124647Z","iopub.execute_input":"2024-05-04T10:56:17.125229Z","iopub.status.idle":"2024-05-04T10:56:17.931674Z","shell.execute_reply.started":"2024-05-04T10:56:17.125184Z","shell.execute_reply":"2024-05-04T10:56:17.930625Z"},"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-05-04T10:56:20.159952Z","iopub.execute_input":"2024-05-04T10:56:20.160320Z","iopub.status.idle":"2024-05-04T10:56:20.177736Z","shell.execute_reply.started":"2024-05-04T10:56:20.160293Z","shell.execute_reply":"2024-05-04T10:56:20.176643Z"},"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-05-04T10:56:23.114028Z","iopub.execute_input":"2024-05-04T10:56:23.114402Z","iopub.status.idle":"2024-05-04T10:56:23.198250Z","shell.execute_reply.started":"2024-05-04T10:56:23.114374Z","shell.execute_reply":"2024-05-04T10:56:23.197365Z"},"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-05-04T10:56:24.149217Z","iopub.execute_input":"2024-05-04T10:56:24.149565Z","iopub.status.idle":"2024-05-04T10:56:24.380032Z","shell.execute_reply.started":"2024-05-04T10:56:24.149540Z","shell.execute_reply":"2024-05-04T10:56:24.379181Z"},"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-05-04T10:56:24.539629Z","iopub.execute_input":"2024-05-04T10:56:24.540019Z","iopub.status.idle":"2024-05-04T10:56:24.545708Z","shell.execute_reply.started":"2024-05-04T10:56:24.539990Z","shell.execute_reply":"2024-05-04T10:56:24.544673Z"},"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-05-04T10:57:46.334152Z","iopub.execute_input":"2024-05-04T10:57:46.334905Z","iopub.status.idle":"2024-05-04T10:57:46.621391Z","shell.execute_reply.started":"2024-05-04T10:57:46.334871Z","shell.execute_reply":"2024-05-04T10:57:46.620362Z"},"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-05-04T10:58:12.544819Z","iopub.execute_input":"2024-05-04T10:58:12.545928Z","iopub.status.idle":"2024-05-04T10:58:12.633490Z","shell.execute_reply.started":"2024-05-04T10:58:12.545881Z","shell.execute_reply":"2024-05-04T10:58:12.632603Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Check\ntrain_df.grouped_ship_count.value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-05-04T10:58:12.636503Z","iopub.execute_input":"2024-05-04T10:58:12.638825Z","iopub.status.idle":"2024-05-04T10:58:12.648705Z","shell.execute_reply.started":"2024-05-04T10:58:12.638793Z","shell.execute_reply":"2024-05-04T10:58:12.647350Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Top 10 data\ntrain_df.head(10)","metadata":{"execution":{"iopub.status.busy":"2024-05-04T10:58:12.650653Z","iopub.execute_input":"2024-05-04T10:58:12.651447Z","iopub.status.idle":"2024-05-04T10:58:12.666110Z","shell.execute_reply.started":"2024-05-04T10:58:12.651405Z","shell.execute_reply":"2024-05-04T10:58:12.664992Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.sample(10)","metadata":{"execution":{"iopub.status.busy":"2024-05-04T10:58:20.504343Z","iopub.execute_input":"2024-05-04T10:58:20.504727Z","iopub.status.idle":"2024-05-04T10:58:20.521253Z","shell.execute_reply.started":"2024-05-04T10:58:20.504696Z","shell.execute_reply":"2024-05-04T10:58:20.520379Z"},"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-05-04T10:58:20.559688Z","iopub.execute_input":"2024-05-04T10:58:20.560374Z","iopub.status.idle":"2024-05-04T10:58:20.565159Z","shell.execute_reply.started":"2024-05-04T10:58:20.560342Z","shell.execute_reply":"2024-05-04T10:58:20.564328Z"},"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-05-04T10:58:23.644832Z","iopub.execute_input":"2024-05-04T10:58:23.645427Z","iopub.status.idle":"2024-05-04T10:58:23.685803Z","shell.execute_reply.started":"2024-05-04T10:58:23.645398Z","shell.execute_reply":"2024-05-04T10:58:23.685088Z"},"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-05-04T10:58:26.095083Z","iopub.execute_input":"2024-05-04T10:58:26.095641Z","iopub.status.idle":"2024-05-04T10:58:26.114447Z","shell.execute_reply.started":"2024-05-04T10:58:26.095602Z","shell.execute_reply":"2024-05-04T10:58:26.113415Z"},"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-05-04T11:00:01.940203Z","iopub.execute_input":"2024-05-04T11:00:01.940602Z","iopub.status.idle":"2024-05-04T11:00:02.544334Z","shell.execute_reply.started":"2024-05-04T11:00:01.940570Z","shell.execute_reply":"2024-05-04T11:00:02.543284Z"},"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-05-04T11:03:18.330334Z","iopub.execute_input":"2024-05-04T11:03:18.330899Z","iopub.status.idle":"2024-05-04T11:03:18.335385Z","shell.execute_reply.started":"2024-05-04T11:03:18.330871Z","shell.execute_reply":"2024-05-04T11:03:18.334435Z"},"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-05-04T11:03:19.024585Z","iopub.execute_input":"2024-05-04T11:03:19.024974Z","iopub.status.idle":"2024-05-04T11:03:19.034960Z","shell.execute_reply.started":"2024-05-04T11:03:19.024944Z","shell.execute_reply":"2024-05-04T11:03:19.033977Z"},"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-05-04T11:03:19.614692Z","iopub.execute_input":"2024-05-04T11:03:19.615100Z","iopub.status.idle":"2024-05-04T11:03:20.490112Z","shell.execute_reply.started":"2024-05-04T11:03:19.615068Z","shell.execute_reply":"2024-05-04T11:03:20.488962Z"},"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-05-04T11:03:37.371256Z","iopub.execute_input":"2024-05-04T11:03:37.371684Z","iopub.status.idle":"2024-05-04T11:03:40.861404Z","shell.execute_reply.started":"2024-05-04T11:03:37.371652Z","shell.execute_reply":"2024-05-04T11:03:40.860318Z"},"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-05-04T11:04:22.304284Z","iopub.execute_input":"2024-05-04T11:04:22.304669Z","iopub.status.idle":"2024-05-04T11:04:37.750605Z","shell.execute_reply.started":"2024-05-04T11:04:22.304642Z","shell.execute_reply":"2024-05-04T11:04:37.749658Z"},"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-05-04T11:06:11.365804Z","iopub.execute_input":"2024-05-04T11:06:11.366930Z","iopub.status.idle":"2024-05-04T11:06:11.372485Z","shell.execute_reply.started":"2024-05-04T11:06:11.366879Z","shell.execute_reply":"2024-05-04T11:06:11.371706Z"},"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":{"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":{"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":{"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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}