{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":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\nimport tensorflow as tf\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":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"train = os.listdir('../input/train')\nprint(len(train))\n\ntest = os.listdir('../input/test')\nprint(len(test))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c6dbe55d09328048f5f7b98aedd8eaa8f68a3751"},"cell_type":"code","source":"submission = pd.read_csv('../input/sample_submission.csv')\nsubmission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"6122ccb9e58bfac6fa5e11c86121e78d9e5151b1"},"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\n\n# https://github.com/ternaus/TernausNet/blob/master/Example.ipynb\ndef mask_overlay(image, mask):\n    \"\"\"\n    Helper function to visualize mask\n    \"\"\"\n    mask = mask.astype(np.uint8)\n    weighted_sum = cv2.addWeighted(mask, 0.75, image, 0.5, 0.)\n    img = image.copy()\n    ind = mask[:, :, 1] > 0    \n    img[ind] = weighted_sum[ind]    \n    return img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"0b5958ff2c83bc8122f4500e74e23b0b013fe610"},"cell_type":"code","source":"def cnn_model_fn(features, labels, mode):\n  \"\"\"Model function for CNN.\"\"\"\n  # Input Layer\n  input_layer = tf.reshape(features, [-1, 768, 768, 1])\n\n  # Convolutional Layer #1\n  conv1 = tf.layers.conv2d(\n      inputs=input_layer,\n      filters=32,\n      kernel_size=[5, 5],\n      padding=\"same\",\n      activation=tf.nn.relu)\n\n  # Pooling Layer #1\n  pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)\n\n  # Convolutional Layer #2 and Pooling Layer #2\n  conv2 = tf.layers.conv2d(\n      inputs=pool1,\n      filters=64,\n      kernel_size=[5, 5],\n      padding=\"same\",\n      activation=tf.nn.relu)\n  pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)\n\n  # Dense Layer\n  pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])\n  dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu)\n  dropout = tf.layers.dropout(\n      inputs=dense, rate=0.4, training=mode == tf.estimator.ModeKeys.TRAIN)\n\n  # Logits Layer\n  logits = tf.layers.dense(inputs=dropout, units=10)\n\n  predictions = {\n      # Generate predictions (for PREDICT and EVAL mode)\n      \"classes\": tf.argmax(input=logits, axis=1),\n      # Add `softmax_tensor` to the graph. It is used for PREDICT and by the\n      # `logging_hook`.\n      \"probabilities\": tf.nn.softmax(logits, name=\"softmax_tensor\")\n  }\n\n  if mode == tf.estimator.ModeKeys.PREDICT:\n    return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)\n\n  # Calculate Loss (for both TRAIN and EVAL modes)\n  loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)\n\n  # Configure the Training Op (for TRAIN mode)\n  if mode == tf.estimator.ModeKeys.TRAIN:\n    optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)\n    train_op = optimizer.minimize(\n        loss=loss,\n        global_step=tf.train.get_global_step())\n    return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)\n\n  # Add evaluation metrics (for EVAL mode)\n  eval_metric_ops = {\n      \"accuracy\": tf.metrics.accuracy(\n          labels=labels, predictions=predictions[\"classes\"])}\n  return tf.estimator.EstimatorSpec(\n      mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"206104f888afa9c62a0bbcb45229f58111094f18"},"cell_type":"code","source":"masks = pd.read_csv('../input/train_ship_segmentations.csv')\nmasks.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"63e18e8573dbb3fe1d3ff1d72b6dc756e067d43a"},"cell_type":"code","source":"ImageId = list()\n\nfor ImageId in train:\n    img = imread('../input/train/' + ImageId)\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"0a38d343b2654f87934a88524ebc14a5759e07cb"},"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}