{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-output":true},"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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom skimage.data import imread\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"4cf2c43bfcd31772ddf1fb9bc31d775df00eed48"},"cell_type":"code","source":"# ref: https://www.kaggle.com/paulorzp/run-length-encode-and-decode\ndef rle_decode(mask_rle, shape=(768, 768)):\n    '''\n    mask_rle: run-length as string formated (start length)\n    shape: (height,width) of array to return \n    Returns numpy array, 1 - mask, 0 - background\n\n    '''\n    s = mask_rle.split()\n    starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]\n    starts -= 1\n    ends = starts + lengths\n    img = np.zeros(shape[0]*shape[1], dtype=np.uint8)\n    for lo, hi in zip(starts, ends):\n        img[lo:hi] = 1\n    return img.reshape(shape).T  # Needed to align to RLE direction","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"5c637577ab3a8ac8ffd67fe8bfcf8a43defc214d"},"cell_type":"markdown","source":"## Look at a sample of the training images."},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"train = pd.read_csv('../input/train_ship_segmentations.csv')\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"5c280f6308cc97d6f30484391a9e785c00ee653f"},"cell_type":"markdown","source":"## Look at 25 images with ships..."},{"metadata":{"trusted":true,"_uuid":"8b48df1a40648b4c212768e130848560de994c7e"},"cell_type":"code","source":"sample = train[~train.EncodedPixels.isna()].sample(25)\n\nfig, ax = plt.subplots(5, 5, sharex='col', sharey='row')\nfig.set_size_inches(20, 20)\n\nfor i, imgid in enumerate(sample.ImageId):\n    col = i % 5\n    row = i // 5\n    \n    path = Path('../input/train') / '{}'.format(imgid)\n    img = imread(path)\n    \n    ax[row, col].imshow(img)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"c954e0657e18f7be6c5bff7b0b279d58af9a4c66"},"cell_type":"markdown","source":"## ...and 25 without ships."},{"metadata":{"trusted":true,"scrolled":false,"_uuid":"44f8f6c310995282bc74d77afbda008abb67a7e8"},"cell_type":"code","source":"sample = train[train.EncodedPixels.isna()].sample(25)\n\nfig, ax = plt.subplots(5, 5, sharex='col', sharey='row')\nfig.set_size_inches(20, 20)\n\nfor i, imgid in enumerate(sample.ImageId):\n    col = i % 5\n    row = i // 5\n    \n    path = Path('../input/train') / '{}'.format(imgid)\n    img = imread(path)\n    \n    ax[row, col].imshow(img)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"899ef6e2a72db9749b7200290c537465a7814da8"},"cell_type":"markdown","source":"## Look at class balance"},{"metadata":{"trusted":true,"_uuid":"0280055240c9ca385532beff63424f1f917d46a6"},"cell_type":"code","source":"ships = train[~train.EncodedPixels.isna()].ImageId.unique()\nnoships = train[train.EncodedPixels.isna()].ImageId.unique()\n\nplt.bar(['Ships', 'No Ships'], [len(ships), len(noships)]);\nplt.ylabel('Number of Images');","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"e5b2b4f441d7d73baa3a2573f280b59a0b3f478e"},"cell_type":"markdown","source":"## Look at colour distributions between images with ships and those without.\n\nLets look at 250 of each, sampled at random."},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"1681edef1d625e62fd45ebb28f151cd2aff669cb"},"cell_type":"code","source":"def get_img(imgid):\n    '''Return image array, given ID.'''\n    path = Path('../input/train/') / '{}'.format(imgid)\n    return imread(path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":false,"_uuid":"642e23bc325641393361420a4f3c3ae290a42121"},"cell_type":"code","source":"fig, ax = plt.subplots(1, 2, sharex='col', sharey='row')\nfig.set_size_inches(20, 6)\n\nmask = train.EncodedPixels.isna()\nfor i, (msk, label) in enumerate(zip([mask, ~mask], ['No Ships', 'Ships'])):\n    _ids = train[msk].ImageId.sample(250)\n    imgs = np.array([get_img(_id) for _id in _ids])\n    \n    red = imgs[:, :, :, 0]\n    green = imgs[:, :, :, 1]\n    blue = imgs[:, :, :, 2]\n    \n    ax[i].plot(np.bincount(red.ravel()), color='orangered', label='red', lw=2)\n    ax[i].plot(np.bincount(green.ravel()), color='yellowgreen', label='green', lw=2)\n    ax[i].plot(np.bincount(blue.ravel()), color='skyblue', label='blue', lw=2)\n    ax[i].legend()\n    ax[i].title.set_text(label)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"d2e4c851dd1b61e23dc5e5f8efa23cc4a60eb7b3"},"cell_type":"markdown","source":"## Look at colour distributions of areas with no ships and ships themselves."},{"metadata":{"trusted":true,"_uuid":"9672423a9db4d5ec4aae6cbbc2220fb61bb84261"},"cell_type":"code","source":"def apply_masks_to_img(img, _id, df):\n    '''Apply masks to image given img, its id and the dataframe.'''\n    masks = df[df.ImageId == _id].EncodedPixels.apply(lambda x: rle_decode(x)).tolist()\n    masks = sum(masks)\n    return img * masks.reshape(img.shape[0], img.shape[1], 1)\n\n\nfig, ax = plt.subplots(1, 2, sharex='col')#, sharey='row')\nfig.set_size_inches(20, 6)\n\nmask = train.EncodedPixels.isna()\nfor i, (msk, label) in enumerate(zip([mask, ~mask], ['No Ships', 'Ships'])):\n    _ids = train[msk].ImageId.sample(250)\n    imgs = [get_img(_id) for _id in _ids]\n    \n    # if we have an encoding to decode\n    if i == 1:\n        imgs = [apply_masks_to_img(i, _id, train) for (i, _id) in zip(imgs, _ids)]\n\n    imgs = np.array(imgs)\n    red = imgs[:, :, :, 0]\n    green = imgs[:, :, :, 1]\n    blue = imgs[:, :, :, 2]\n    \n    # skip bincount index 0 to avoid the masked pixels to overpower the others.\n    ax[i].plot(np.bincount(red.ravel())[1:], color='orangered', label='red', lw=2)\n    ax[i].plot(np.bincount(green.ravel())[1:], color='yellowgreen', label='green', lw=2)\n    ax[i].plot(np.bincount(blue.ravel())[1:], color='skyblue', label='blue', lw=2)\n    ax[i].legend()\n    ax[i].title.set_text(label)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"056f5c48ed0b3262e32c72ccf8fce3215413639c"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"3b18dc6b10db09c65b580d374f0689fb0fcc72bb"},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}