{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"\n\nimport numpy as np \nimport pandas as pd \n\nfrom fastai import *\nfrom fastai.vision import *\nfrom fastai.callbacks import *\n\nimport os\nprint(os.listdir(\"../input\"))\n\n","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"df= pd.read_csv('../input/train_ship_segmentations_v2.csv').dropna().set_index('ImageId')\ndf.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"path = Path('../input/')\n(path).ls()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img_f= path/'train_v2/000155de5.jpg'\n# df.loc['000155de5.jpg']\nopen_image(img_f)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"mask=open_mask_rle(df.loc['000155de5.jpg'].values[0], shape=(768,768))\nplt.imshow(mask.data.transpose(1,2)[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class ShipSegmentationLabelList(SegmentationLabelList):\n    def open(self,fn): \n        def open_mask_rle_T(mask_rle:str, shape:Tuple[int, int])->ImageSegment:\n            \"Return `ImageSegment` object create from run-length encoded string in `mask_lre` with size in `shape`.\"\n            x = FloatTensor(rle_decode(str(mask_rle), shape).astype(np.uint8).T)\n            x = x.view(shape[1], shape[0], -1)\n            return ImageSegment(x.permute(2,0,1))\n        return open_mask_rle_T(fn, shape=(768, 768))\n    \nclass ShipSegmentationItemList(ImageList):\n    _label_cls= ShipSegmentationLabelList","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"get_labels= lambda x: df.loc[x.parts[-1]].values[0][0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_files= [Path(os.path.join(path/'train_v2',f))  for f in df.index]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"src=(ShipSegmentationItemList(train_files)\n        .split_by_rand_pct()\n        .label_from_func(get_labels,classes=['water','ship']))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data = (src.transform(get_transforms(flip_vert=True), size=(224,224), tfm_y=True)\n        .databunch(bs=16, num_workers=2)\n        .normalize(imagenet_stats))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.show_batch(rows=2, alpha=0.7, figsize=(15,15)) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"im,m = data.one_batch()\nim.shape,m.shape\nplt.imshow(im[0].transpose(1,2).numpy().T, cmap='gray')\nplt.imshow(m[0][0], cmap='ocean', alpha=0.5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def dice(input:Tensor, targs:Tensor, iou:bool=False)->Rank0Tensor:\n    \"Dice coefficient metric for binary target. If iou=True, returns iou metric, classic for segmentation problems.\"\n    n = targs.shape[0]\n    input = input.argmax(dim=1).view(n,-1)\n    targs = targs.view(n,-1)\n    intersect = (input*targs).sum().float()\n    union = (input+targs).sum().float()\n    if not iou: return 2. * intersect / union\n    else: return intersect / (union-intersect+1.0)\n\ndef accuracy_ship(input, target):\n    target=target.squeeze(1)\n    mask =target>0\n    return (input.argmax(dim=1)[mask]==target[mask]).float().mean()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learner= unet_learner(data, models.resnet34,metrics=[accuracy_ship,dice], \n                      model_dir=\"/tmp/models/\", \n                      callback_fns=[partial(SaveModelCallback,every='epoch',name='1'),\n                                 ShowGraph])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learner.lr_find()\nlearner.recorder.plot()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lr=1e-3\nlearner.fit_one_cycle(4, slice(1e-4,2*lr), wd=1e-2)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"MODEL = '/kaggle/working/model'","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}