{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np \nimport pandas as pd \n\nfrom fastai import *\nfrom fastai.vision import *\n\nimport os\nprint(os.listdir(\"../input\"))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"path=Path('../input/train')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img_f =path.ls()[0]\nimg_f","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img= open_image(img_f)\nimg","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"get_labels = lambda x: path.parent/f'train_masks/{x.stem}_mask.gif'\nmask=open_mask(get_labels(img_f), div=True)\nmask","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(img.data.transpose(1,2).numpy().T)\nplt.imshow(mask.data[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class CaravanaSegmentationLabelList(SegmentationLabelList):\n    def open(self,fn): return open_mask(fn, div=True)\n    \nclass CaravanaSegmentationItemList(ImageList):\n    _label_cls= CaravanaSegmentationLabelList","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"src=(CaravanaSegmentationItemList.from_folder(path)\n     .split_by_rand_pct()\n     .label_from_func(get_labels, classes=['void','car']))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data = (src.transform(get_transforms(), size=(224,224), tfm_y=True)\n        .databunch(bs=16)\n        .normalize(imagenet_stats))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.show_batch(rows=3, alpha=0.6)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"im,m=data.one_batch()\nim.shape, m.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"m[0,0].unique()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Metrics"},{"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    \n# def iou(outputs: torch.Tensor, labels: torch.Tensor):\n#     # You can comment out this line if you are passing tensors of equal shape\n#     # But if you are passing output from UNet or something it will most probably\n#     # be with the BATCH x 1 x H x W shape\n# #     outputs = outputs.squeeze(1)  # BATCH x 1 x H x W => BATCH x H x W\n    \n#     intersection = (outputs & labels).float().sum((1, 2))  # Will be zero if Truth=0 or Prediction=0\n#     union = (outputs | labels).float().sum((1, 2))         # Will be zzero if both are 0\n    \n#     iou = (intersection + SMOOTH) / (union + SMOOTH)  # We smooth our devision to avoid 0/0\n    \n#     thresholded = torch.clamp(20 * (iou - 0.5), 0, 10).ceil() / 10  # This is equal to comparing with thresolds\n    \n#     return thresholded\ndef accuracy_carvana(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":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Dynimic U-Net "},{"metadata":{"trusted":true},"cell_type":"code","source":"learner= unet_learner(data, models.resnet34, metrics=[dice, accuracy_carvana], model_dir=\"/tmp/models/\") ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# pred, target = learner.model(im.cuda()), m.cuda()\n# pred.shape, target.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learner.lr_find()\nlearner.recorder.plot()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-output":true},"cell_type":"code","source":"learner.fit_one_cycle(1, 1e-3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learner.save('stage-1')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learner.load('stage-1');","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img,mk= learner.data.one_batch()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def overlay(pred, mask):\n    plt.imshow(pred[0].transpose(1,2).numpy().T, cmap='gray')\n    plt.imshow(mask[0,0].numpy(),cmap='jet', alpha=0.5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"overlay(img,mk)","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":{"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}