{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"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\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB 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":"2022-08-01T20:16:46.664689Z","iopub.execute_input":"2022-08-01T20:16:46.665173Z","iopub.status.idle":"2022-08-01T20:16:46.708711Z","shell.execute_reply.started":"2022-08-01T20:16:46.665086Z","shell.execute_reply":"2022-08-01T20:16:46.707410Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# U-Net Original Research Paper\n### Paper Name: U-Net: Convolutional Networks for Biomedical Image Segmentation\n### Paper Link: https://arxiv.org/pdf/1505.04597.pdf","metadata":{}},{"cell_type":"markdown","source":"# Configs","metadata":{}},{"cell_type":"code","source":"class ROOTDIR:\n    train = \"./train\"\n    train_mask = \"./train_masks\"","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:16:46.711236Z","iopub.execute_input":"2022-08-01T20:16:46.711695Z","iopub.status.idle":"2022-08-01T20:16:46.717152Z","shell.execute_reply.started":"2022-08-01T20:16:46.711631Z","shell.execute_reply":"2022-08-01T20:16:46.715756Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# General Imports","metadata":{}},{"cell_type":"code","source":"import os\nimport cv2\nimport zipfile\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\nfrom tqdm.auto import tqdm\nimport matplotlib.pyplot as plt","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:16:46.720316Z","iopub.execute_input":"2022-08-01T20:16:46.720939Z","iopub.status.idle":"2022-08-01T20:16:47.044919Z","shell.execute_reply.started":"2022-08-01T20:16:46.720878Z","shell.execute_reply":"2022-08-01T20:16:47.043929Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Extracting Files","metadata":{}},{"cell_type":"code","source":"dirs = [\"../input/carvana-image-masking-challenge/train.zip\",\n        \"../input/carvana-image-masking-challenge/train_masks.zip\",\n        \"../input/carvana-image-masking-challenge/metadata.csv.zip\"]\n\nfor i in tqdm(dirs):\n    with zipfile.ZipFile(i) as z:\n        z.extractall()\n    ","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:16:47.046232Z","iopub.execute_input":"2022-08-01T20:16:47.048256Z","iopub.status.idle":"2022-08-01T20:17:00.482795Z","shell.execute_reply.started":"2022-08-01T20:16:47.048209Z","shell.execute_reply":"2022-08-01T20:17:00.481696Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Working with CSV","metadata":{}},{"cell_type":"code","source":"df = pd.read_csv(\"./metadata.csv\")\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:00.485680Z","iopub.execute_input":"2022-08-01T20:17:00.486627Z","iopub.status.idle":"2022-08-01T20:17:00.529563Z","shell.execute_reply.started":"2022-08-01T20:17:00.486581Z","shell.execute_reply":"2022-08-01T20:17:00.528701Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.info()","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:00.531030Z","iopub.execute_input":"2022-08-01T20:17:00.531662Z","iopub.status.idle":"2022-08-01T20:17:00.562788Z","shell.execute_reply.started":"2022-08-01T20:17:00.531602Z","shell.execute_reply":"2022-08-01T20:17:00.561536Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Working with Train Images and Masks","metadata":{}},{"cell_type":"code","source":"train_img_lst = os.listdir(ROOTDIR.train) # \"./train\"\ntrain_mask_lst = os.listdir(ROOTDIR.train_mask) # \"./train_masks\"","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:00.564662Z","iopub.execute_input":"2022-08-01T20:17:00.565680Z","iopub.status.idle":"2022-08-01T20:17:00.578591Z","shell.execute_reply.started":"2022-08-01T20:17:00.565617Z","shell.execute_reply":"2022-08-01T20:17:00.577513Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(train_mask_lst[:5])\nprint(train_img_lst[:5])","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:00.580685Z","iopub.execute_input":"2022-08-01T20:17:00.581176Z","iopub.status.idle":"2022-08-01T20:17:00.587477Z","shell.execute_reply.started":"2022-08-01T20:17:00.581134Z","shell.execute_reply":"2022-08-01T20:17:00.586307Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(train_mask_lst))\nprint(len(train_img_lst))","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:00.589369Z","iopub.execute_input":"2022-08-01T20:17:00.590196Z","iopub.status.idle":"2022-08-01T20:17:00.599726Z","shell.execute_reply.started":"2022-08-01T20:17:00.590149Z","shell.execute_reply":"2022-08-01T20:17:00.598434Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Sorting to make sure we get right image and right mask","metadata":{}},{"cell_type":"code","source":"sorted_train_mask_lst = sorted(train_mask_lst)","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:00.601846Z","iopub.execute_input":"2022-08-01T20:17:00.602786Z","iopub.status.idle":"2022-08-01T20:17:00.610999Z","shell.execute_reply.started":"2022-08-01T20:17:00.602731Z","shell.execute_reply":"2022-08-01T20:17:00.609899Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sorted_train_img_lst = sorted(train_img_lst)","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:00.612968Z","iopub.execute_input":"2022-08-01T20:17:00.613672Z","iopub.status.idle":"2022-08-01T20:17:00.623004Z","shell.execute_reply.started":"2022-08-01T20:17:00.613609Z","shell.execute_reply":"2022-08-01T20:17:00.621842Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(sorted_train_mask_lst[:16])\nprint(sorted_train_img_lst[:16])","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:00.626969Z","iopub.execute_input":"2022-08-01T20:17:00.627296Z","iopub.status.idle":"2022-08-01T20:17:00.635789Z","shell.execute_reply.started":"2022-08-01T20:17:00.627268Z","shell.execute_reply":"2022-08-01T20:17:00.634382Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Visualizing Images with their Mask\n### Making sure images and mask are paired correctly.","metadata":{}},{"cell_type":"code","source":"def show_images(imgs_lst,masks_lst,loops=2):\n    for i in range(loops):\n        img_path = os.path.join(ROOTDIR.train,imgs_lst[i])\n        mask_path = os.path.join(ROOTDIR.train_mask,masks_lst[i])\n        img = Image.open(img_path)\n        mask = Image.open(mask_path)\n        print(img_path)\n        print(img.size)\n        print(type(img))\n        plt.imshow(img)\n        plt.show()\n        print(mask_path)\n        print(mask.size)\n        plt.imshow(mask)\n        plt.show()\n        print(\"----------------------------------------------------\")\n\nshow_images(sorted_train_img_lst, sorted_train_mask_lst)","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:00.638172Z","iopub.execute_input":"2022-08-01T20:17:00.638832Z","iopub.status.idle":"2022-08-01T20:17:02.743785Z","shell.execute_reply.started":"2022-08-01T20:17:00.638776Z","shell.execute_reply":"2022-08-01T20:17:02.742772Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# PyTorch Imports","metadata":{}},{"cell_type":"code","source":"import torch\nimport torchvision\nimport torch.nn as nn\nimport albumentations as A\nimport torch.optim as optim\nfrom torchvision import models\nimport torch.nn.functional as F\nfrom torch.optim import lr_scheduler\nimport torchvision.datasets as datasets\nimport torchvision.transforms as transforms\nfrom torchvision.datasets import ImageFolder\nfrom albumentations.pytorch import ToTensorV2 \nfrom torch.utils.data import DataLoader, Dataset","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:02.748584Z","iopub.execute_input":"2022-08-01T20:17:02.748936Z","iopub.status.idle":"2022-08-01T20:17:05.670693Z","shell.execute_reply.started":"2022-08-01T20:17:02.748892Z","shell.execute_reply":"2022-08-01T20:17:05.669372Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# PyTorch Configuration","metadata":{}},{"cell_type":"code","source":"class CFG:\n    device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n    split_pct = 0.2\n    learning_rate = 3e-4\n    batch_size = 4\n    epochs = 3","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:05.676361Z","iopub.execute_input":"2022-08-01T20:17:05.677152Z","iopub.status.idle":"2022-08-01T20:17:05.802725Z","shell.execute_reply.started":"2022-08-01T20:17:05.677108Z","shell.execute_reply":"2022-08-01T20:17:05.801369Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"seed = 123\nnp.random.seed(seed)\ntorch.manual_seed(seed)","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:05.806944Z","iopub.execute_input":"2022-08-01T20:17:05.807289Z","iopub.status.idle":"2022-08-01T20:17:05.820464Z","shell.execute_reply.started":"2022-08-01T20:17:05.807244Z","shell.execute_reply":"2022-08-01T20:17:05.819146Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"CFG.device","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:05.822207Z","iopub.execute_input":"2022-08-01T20:17:05.823118Z","iopub.status.idle":"2022-08-01T20:17:05.830932Z","shell.execute_reply.started":"2022-08-01T20:17:05.823073Z","shell.execute_reply":"2022-08-01T20:17:05.829856Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Working with data","metadata":{}},{"cell_type":"markdown","source":"### Shuffling the data.","metadata":{}},{"cell_type":"code","source":"permuted_train_img_lst = np.random.permutation(np.array(sorted_train_img_lst))\npermuted_train_mask_lst = [x.replace(\".jpg\", \"_mask.gif\") for x in permuted_train_img_lst]\nprint(permuted_train_img_lst[:5])\nprint(permuted_train_mask_lst[:5])","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:05.832715Z","iopub.execute_input":"2022-08-01T20:17:05.834234Z","iopub.status.idle":"2022-08-01T20:17:05.851551Z","shell.execute_reply.started":"2022-08-01T20:17:05.834130Z","shell.execute_reply":"2022-08-01T20:17:05.850361Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"show_images(permuted_train_img_lst,permuted_train_mask_lst)","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:05.853074Z","iopub.execute_input":"2022-08-01T20:17:05.853538Z","iopub.status.idle":"2022-08-01T20:17:07.813166Z","shell.execute_reply.started":"2022-08-01T20:17:05.853482Z","shell.execute_reply":"2022-08-01T20:17:07.811934Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Splitting into Training and Validation","metadata":{}},{"cell_type":"code","source":"length = len(permuted_train_img_lst)\nprint(length*0.2) # convert this to int","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:07.815061Z","iopub.execute_input":"2022-08-01T20:17:07.815859Z","iopub.status.idle":"2022-08-01T20:17:07.822393Z","shell.execute_reply.started":"2022-08-01T20:17:07.815814Z","shell.execute_reply":"2022-08-01T20:17:07.821202Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_images_list = permuted_train_img_lst[int(CFG.split_pct*len(permuted_train_img_lst)) :]\ntrain_masks_list = permuted_train_mask_lst[int(CFG.split_pct*len(permuted_train_mask_lst)) :]\nprint(len(train_masks_list))\n\nval_images_list = permuted_train_img_lst[: int(CFG.split_pct*len(permuted_train_img_lst))]\nval_masks_list = permuted_train_mask_lst[: int(CFG.split_pct*len(permuted_train_mask_lst))]\nprint(len(val_masks_list))\n\n# 4071+1017=5088 (split includes all items)","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:07.824110Z","iopub.execute_input":"2022-08-01T20:17:07.825247Z","iopub.status.idle":"2022-08-01T20:17:07.836105Z","shell.execute_reply.started":"2022-08-01T20:17:07.825202Z","shell.execute_reply":"2022-08-01T20:17:07.834733Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Visualizing Train Dataset","metadata":{}},{"cell_type":"code","source":"show_images(train_images_list,train_masks_list)","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:07.837687Z","iopub.execute_input":"2022-08-01T20:17:07.840989Z","iopub.status.idle":"2022-08-01T20:17:10.038526Z","shell.execute_reply.started":"2022-08-01T20:17:07.840945Z","shell.execute_reply":"2022-08-01T20:17:10.037364Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Visualizing Validation Dataset","metadata":{}},{"cell_type":"code","source":"show_images(val_images_list,val_masks_list)","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:10.040022Z","iopub.execute_input":"2022-08-01T20:17:10.041127Z","iopub.status.idle":"2022-08-01T20:17:12.171007Z","shell.execute_reply.started":"2022-08-01T20:17:10.041078Z","shell.execute_reply":"2022-08-01T20:17:12.169831Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Dataset Class","metadata":{}},{"cell_type":"code","source":"class CarvanaDataset(Dataset):\n    def __init__(self,img_list,mask_list,transform=None):\n        self.img_list = img_list\n        self.mask_list = mask_list\n        self.transform = transform\n        \n    def __len__(self):\n        return len(self.img_list)\n    \n    def __getitem__(self,index):\n        img_path = os.path.join(ROOTDIR.train,self.img_list[index])\n        mask_path = os.path.join(ROOTDIR.train_mask,self.mask_list[index])\n        img = Image.open(img_path)\n        mask = Image.open(mask_path)\n        img = np.array(img)\n        mask = np.array(mask)\n        mask[mask==255.0] = 1.0\n        #img_mask_dict = {\"image\": img, \"mask\": mask}\n        \n        if self.transform:\n            augmentation = self.transform(image=img, mask=mask)\n            img = augmentation[\"image\"]\n            mask = augmentation[\"mask\"]\n            mask = torch.unsqueeze(mask,0)\n            #transformations = self.transform(image=img, mask=mask)\n            #img = transformations[\"image\"]\n            #mask = transformations[\"mask\"]\n            \n        return img,mask","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:12.172761Z","iopub.execute_input":"2022-08-01T20:17:12.173468Z","iopub.status.idle":"2022-08-01T20:17:12.184935Z","shell.execute_reply.started":"2022-08-01T20:17:12.173421Z","shell.execute_reply":"2022-08-01T20:17:12.183713Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_transform = A.Compose([A.Resize(572,572), \n                             A.Rotate(limit=15,p=0.1),\n                             A.HorizontalFlip(p=0.5),\n                             A.Normalize(mean=(0,0,0),std=(1,1,1),max_pixel_value=255),\n                             ToTensorV2()])\n\nval_transform = A.Compose([A.Resize(572,572),\n                           A.Normalize(mean=(0,0,0),std=(1,1,1),max_pixel_value=255),\n                           ToTensorV2()])","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:12.187948Z","iopub.execute_input":"2022-08-01T20:17:12.188496Z","iopub.status.idle":"2022-08-01T20:17:12.200768Z","shell.execute_reply.started":"2022-08-01T20:17:12.188449Z","shell.execute_reply":"2022-08-01T20:17:12.199592Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dataset = CarvanaDataset(train_images_list, train_masks_list, transform = train_transform)\nval_dataset = CarvanaDataset(val_images_list, val_masks_list, transform = train_transform)","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:12.203411Z","iopub.execute_input":"2022-08-01T20:17:12.203799Z","iopub.status.idle":"2022-08-01T20:17:12.216776Z","shell.execute_reply.started":"2022-08-01T20:17:12.203754Z","shell.execute_reply":"2022-08-01T20:17:12.215761Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"idx = 200\nimg,mask = train_dataset[idx]","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:12.218234Z","iopub.execute_input":"2022-08-01T20:17:12.219783Z","iopub.status.idle":"2022-08-01T20:17:12.306353Z","shell.execute_reply.started":"2022-08-01T20:17:12.219734Z","shell.execute_reply":"2022-08-01T20:17:12.305379Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mask.shape","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:12.308560Z","iopub.execute_input":"2022-08-01T20:17:12.309278Z","iopub.status.idle":"2022-08-01T20:17:12.318320Z","shell.execute_reply.started":"2022-08-01T20:17:12.309235Z","shell.execute_reply":"2022-08-01T20:17:12.317138Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img.max()","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:12.320173Z","iopub.execute_input":"2022-08-01T20:17:12.322903Z","iopub.status.idle":"2022-08-01T20:17:12.334402Z","shell.execute_reply.started":"2022-08-01T20:17:12.322858Z","shell.execute_reply":"2022-08-01T20:17:12.333170Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def show_single_img(img,mask,index=None,train=True):\n    if index:\n        if train:\n            img,mask = train_dataset[index]\n        else:\n            img,mask = val_dataset[index]\n    plt.imshow(img.permute(1,2,0),cmap=\"gray\")  # Convert (3, 572, 572) -> (572, 572, 3)\n    plt.show()\n    plt.imshow(mask.permute(1,2,0), cmap=\"gray\")  # Convert (1, 572, 572) -> (572, 572, 1)\n    print(mask.shape)\n    plt.show()\n    ","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:12.336097Z","iopub.execute_input":"2022-08-01T20:17:12.337128Z","iopub.status.idle":"2022-08-01T20:17:12.345765Z","shell.execute_reply.started":"2022-08-01T20:17:12.337084Z","shell.execute_reply":"2022-08-01T20:17:12.344722Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"---------------Train---------------\")\nshow_single_img(img,mask,index=15,train=False)\nprint(\"---------------Validation---------------\")\nshow_single_img(img,mask,index=15,train=True)","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:12.347404Z","iopub.execute_input":"2022-08-01T20:17:12.348833Z","iopub.status.idle":"2022-08-01T20:17:13.416769Z","shell.execute_reply.started":"2022-08-01T20:17:12.348683Z","shell.execute_reply":"2022-08-01T20:17:13.415748Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Dataloader","metadata":{}},{"cell_type":"code","source":"train_dataloader = DataLoader(train_dataset,batch_size=CFG.batch_size,shuffle=True)\nval_dataloader = DataLoader(val_dataset,batch_size=CFG.batch_size,shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:13.418320Z","iopub.execute_input":"2022-08-01T20:17:13.418961Z","iopub.status.idle":"2022-08-01T20:17:13.426472Z","shell.execute_reply.started":"2022-08-01T20:17:13.418915Z","shell.execute_reply":"2022-08-01T20:17:13.424309Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"a = iter(train_dataloader)\nimg,mask = a.next()\nprint(img.shape,mask.shape)","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:13.428144Z","iopub.execute_input":"2022-08-01T20:17:13.428908Z","iopub.status.idle":"2022-08-01T20:17:13.692282Z","shell.execute_reply.started":"2022-08-01T20:17:13.428864Z","shell.execute_reply":"2022-08-01T20:17:13.690145Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Utility Functions","metadata":{}},{"cell_type":"code","source":"def double_conv(in_ch, out_ch):\n    conv = nn.Sequential(\n        nn.Conv2d(in_channels=in_ch,out_channels=out_ch,kernel_size=3,stride=1,padding=1),\n        nn.BatchNorm2d(out_ch),                                                            \n        nn.ReLU(inplace=True),\n        nn.Conv2d(in_channels=out_ch,out_channels=out_ch,kernel_size=3,stride=1,padding=1), \n        nn.BatchNorm2d(out_ch),                                                            \n        nn.ReLU(inplace=True)\n    )\n    \n    return conv\n\n#def cropper(og_tensor, target_tensor):\n#    og_shape = og_tensor.shape[2]\n#    target_shape = target_tensor.shape[2]\n#    delta = (og_shape - target_shape) // 2\n#    cropped_og_tensor = og_tensor[:,:,delta:og_shape-delta,delta:og_shape-delta]\n#    return cropped_og_tensor\n \n    \ndef padder(left_tensor, right_tensor): \n    # left_tensor is the tensor on the encoder side of UNET\n    # right_tensor is the tensor on the decoder side  of the UNET\n    \n    if left_tensor.shape != right_tensor.shape:\n        padded = torch.zeros(left_tensor.shape)\n        padded[:, :, :right_tensor.shape[2], :right_tensor.shape[3]] = right_tensor\n        return padded.to(CFG.device)\n    \n    return right_tensor.to(CFG.device)\n    ","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:17:13.694346Z","iopub.execute_input":"2022-08-01T20:17:13.694896Z","iopub.status.idle":"2022-08-01T20:17:13.704952Z","shell.execute_reply.started":"2022-08-01T20:17:13.694849Z","shell.execute_reply":"2022-08-01T20:17:13.703691Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# UNET MODEL FROM SCRATCH","metadata":{}},{"cell_type":"code","source":"class UNET(nn.Module):\n    def __init__(self,in_chnls, n_classes):\n        super(UNET,self).__init__()\n        \n        self.in_chnls = in_chnls\n        self.n_classes = n_classes\n        \n        self.max_pool = nn.MaxPool2d(kernel_size=2,stride=2)\n        \n        self.down_conv_1 = double_conv(in_ch=self.in_chnls,out_ch=64)\n        self.down_conv_2 = double_conv(in_ch=64,out_ch=128)\n        self.down_conv_3 = double_conv(in_ch=128,out_ch=256)\n        self.down_conv_4 = double_conv(in_ch=256,out_ch=512)\n        self.down_conv_5 = double_conv(in_ch=512,out_ch=1024)\n        #print(self.down_conv_1)\n        \n        self.up_conv_trans_1 = nn.ConvTranspose2d(in_channels=1024,out_channels=512,kernel_size=2,stride=2)\n        self.up_conv_trans_2 = nn.ConvTranspose2d(in_channels=512,out_channels=256,kernel_size=2,stride=2)\n        self.up_conv_trans_3 = nn.ConvTranspose2d(in_channels=256,out_channels=128,kernel_size=2,stride=2)\n        self.up_conv_trans_4 = nn.ConvTranspose2d(in_channels=128,out_channels=64,kernel_size=2,stride=2)\n        \n        self.up_conv_1 = double_conv(in_ch=1024,out_ch=512)\n        self.up_conv_2 = double_conv(in_ch=512,out_ch=256)\n        self.up_conv_3 = double_conv(in_ch=256,out_ch=128)\n        self.up_conv_4 = double_conv(in_ch=128,out_ch=64)\n        \n        self.conv_1x1 = nn.Conv2d(in_channels=64,out_channels=self.n_classes,kernel_size=1,stride=1)\n        \n    def forward(self,x):\n        \n        # encoding\n        x1 = self.down_conv_1(x)\n        #print(\"X1\", x1.shape)\n        p1 = self.max_pool(x1)\n        #print(\"p1\", p1.shape)\n        x2 = self.down_conv_2(p1)\n        #print(\"X2\", x2.shape)\n        p2 = self.max_pool(x2)\n        #print(\"p2\", p2.shape)\n        x3 = self.down_conv_3(p2)\n        #print(\"X2\", x3.shape)\n        p3 = self.max_pool(x3)\n        #print(\"p3\", p3.shape)\n        x4 = self.down_conv_4(p3)\n        #print(\"X4\", x4.shape)\n        p4 = self.max_pool(x4)\n        #print(\"p4\", p4.shape)\n        x5 = self.down_conv_5(p4)\n        #print(\"X5\", x5.shape)\n        \n        # decoding\n        d1 = self.up_conv_trans_1(x5)  # up transpose convolution (\"up sampling\" as called in UNET paper)\n        pad1 = padder(x4,d1) # padding d1 to match x4 shape\n        cat1 = torch.cat([x4,pad1],dim=1) # concatenating padded d1 and x4 on channel dimension(dim 1) [batch(dim 0),channel(dim 1),height(dim 2),width(dim 3)]\n        uc1 = self.up_conv_1(cat1) # 1st up double convolution\n        \n        d2 = self.up_conv_trans_2(uc1)\n        pad2 = padder(x3,d2)\n        cat2 = torch.cat([x3,pad2],dim=1)\n        uc2 = self.up_conv_2(cat2)\n        \n        d3 = self.up_conv_trans_3(uc2)\n        pad3 = padder(x2,d3)\n        cat3 = torch.cat([x2,pad3],dim=1)\n        uc3 = self.up_conv_3(cat3)\n        \n        d4 = self.up_conv_trans_4(uc3)\n        pad4 = padder(x1,d4)\n        cat4 = torch.cat([x1,pad4],dim=1)\n        uc4 = self.up_conv_4(cat4)\n        \n        conv_1x1 = self.conv_1x1(uc4)\n        return conv_1x1\n        #print(conv_1x1.shape)","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:18:31.239048Z","iopub.execute_input":"2022-08-01T20:18:31.239500Z","iopub.status.idle":"2022-08-01T20:18:31.261611Z","shell.execute_reply.started":"2022-08-01T20:18:31.239467Z","shell.execute_reply":"2022-08-01T20:18:31.260526Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Training and Validation","metadata":{}},{"cell_type":"markdown","source":"### Train Function\n","metadata":{}},{"cell_type":"code","source":"def train_model(model,dataloader,criterion,optimizer):\n    model.train()\n    train_running_loss = 0.0\n    for j,img_mask in enumerate(tqdm(dataloader)):\n        img = img_mask[0].float().to(CFG.device)\n        #print(\" ----- IMAGE -----\")\n        #print(img)\n        mask = img_mask[1].float().to(CFG.device)\n        #print(\" ----- MASK -----\")\n        #print(mask)\n        \n        y_pred = model(img)\n        #print(\" ----- Y PRED -----\")\n        #print(y_pred)\n        #print(\" ----- Y PRED SHAPE -----\")#\n        #print(y_pred.shape)\n        optimizer.zero_grad()\n        \n        loss = criterion(y_pred,mask)\n        \n        train_running_loss += loss.item() * CFG.batch_size\n        \n        loss.backward()\n        optimizer.step()\n        \n    train_loss = train_running_loss / (j+1)\n    return train_loss","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:18:44.564570Z","iopub.execute_input":"2022-08-01T20:18:44.565005Z","iopub.status.idle":"2022-08-01T20:18:44.574638Z","shell.execute_reply.started":"2022-08-01T20:18:44.564973Z","shell.execute_reply":"2022-08-01T20:18:44.573256Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Validation Function","metadata":{}},{"cell_type":"code","source":"def val_model(model,dataloader,criterion,optimizer):\n    model.eval()\n    val_running_loss = 0\n    with torch.no_grad():\n        for j,img_mask in enumerate(tqdm(dataloader)):\n            img = img_mask[0].float().to(CFG.device)\n            mask = img_mask[1].float().to(CFG.device)\n            y_pred = model(img)\n            loss = criterion(y_pred,mask)\n            \n            val_running_loss += loss.item() * CFG.batch_size\n            \n        val_loss = val_running_loss / (j+1)\n    return val_loss","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:18:47.976069Z","iopub.execute_input":"2022-08-01T20:18:47.976733Z","iopub.status.idle":"2022-08-01T20:18:47.988103Z","shell.execute_reply.started":"2022-08-01T20:18:47.976663Z","shell.execute_reply":"2022-08-01T20:18:47.986811Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = UNET(in_chnls = 3, n_classes = 1).to(CFG.device)\noptimizer = optim.Adam(model.parameters(), lr = CFG.learning_rate)\ncriterion = nn.BCEWithLogitsLoss()\ntrain_loss_lst = []\nval_loss_lst = []  ","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:18:49.206294Z","iopub.execute_input":"2022-08-01T20:18:49.206919Z","iopub.status.idle":"2022-08-01T20:18:53.162932Z","shell.execute_reply.started":"2022-08-01T20:18:49.206884Z","shell.execute_reply":"2022-08-01T20:18:53.161825Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Train and Validation Loop","metadata":{}},{"cell_type":"code","source":"for i in tqdm(range(CFG.epochs)):\n    train_loss = train_model(model=model,dataloader=train_dataloader,criterion=criterion,optimizer=optimizer)\n    val_loss = val_model(model=model,dataloader=val_dataloader,criterion=criterion,optimizer=optimizer)\n    train_loss_lst.append(train_loss)\n    val_loss_lst.append(val_loss)\n    print(f\" Train Loss : {train_loss:.4f}\")\n    print(f\" Validation Loss : {val_loss:.4f}\")","metadata":{"execution":{"iopub.status.busy":"2022-08-01T20:18:53.165009Z","iopub.execute_input":"2022-08-01T20:18:53.165442Z","iopub.status.idle":"2022-08-01T21:33:06.588348Z","shell.execute_reply.started":"2022-08-01T20:18:53.165398Z","shell.execute_reply":"2022-08-01T21:33:06.587000Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Training and Validation Loss Plot","metadata":{}},{"cell_type":"code","source":"plt.plot(train_loss_lst, color=\"green\", label='train loss')\nplt.plot(val_loss_lst, color=\"red\", label='validation loss')\nplt.xlabel(\"epochs\")\nplt.ylabel(\"loss\")\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-08-01T21:33:06.590845Z","iopub.execute_input":"2022-08-01T21:33:06.591387Z","iopub.status.idle":"2022-08-01T21:33:06.830769Z","shell.execute_reply.started":"2022-08-01T21:33:06.591340Z","shell.execute_reply":"2022-08-01T21:33:06.829617Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Saving Model","metadata":{}},{"cell_type":"code","source":"TRAINED_FILE = \"./unet_scratch.pth\"","metadata":{"execution":{"iopub.status.busy":"2022-08-01T21:33:25.051221Z","iopub.execute_input":"2022-08-01T21:33:25.051640Z","iopub.status.idle":"2022-08-01T21:33:25.056635Z","shell.execute_reply.started":"2022-08-01T21:33:25.051607Z","shell.execute_reply":"2022-08-01T21:33:25.055526Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"torch.save(model.state_dict(), TRAINED_FILE)","metadata":{"execution":{"iopub.status.busy":"2022-08-01T21:33:25.313760Z","iopub.execute_input":"2022-08-01T21:33:25.314095Z","iopub.status.idle":"2022-08-01T21:33:25.562737Z","shell.execute_reply.started":"2022-08-01T21:33:25.314052Z","shell.execute_reply":"2022-08-01T21:33:25.561710Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from IPython.display import FileLink\nFileLink(TRAINED_FILE)","metadata":{"execution":{"iopub.status.busy":"2022-08-01T21:33:25.592861Z","iopub.execute_input":"2022-08-01T21:33:25.593165Z","iopub.status.idle":"2022-08-01T21:33:25.600568Z","shell.execute_reply.started":"2022-08-01T21:33:25.593136Z","shell.execute_reply":"2022-08-01T21:33:25.599385Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Testing","metadata":{}},{"cell_type":"code","source":"trained_model = UNET(in_chnls = 3, n_classes = 1)","metadata":{"execution":{"iopub.status.busy":"2022-08-01T21:53:02.114394Z","iopub.execute_input":"2022-08-01T21:53:02.114872Z","iopub.status.idle":"2022-08-01T21:53:02.400811Z","shell.execute_reply.started":"2022-08-01T21:53:02.114839Z","shell.execute_reply":"2022-08-01T21:53:02.399752Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"UNET_TRAINED = \"../input/unet-4-epoch-trained/unet_scratch.pth\"","metadata":{"execution":{"iopub.status.busy":"2022-08-01T21:53:20.892389Z","iopub.execute_input":"2022-08-01T21:53:20.892863Z","iopub.status.idle":"2022-08-01T21:53:20.899236Z","shell.execute_reply.started":"2022-08-01T21:53:20.892833Z","shell.execute_reply":"2022-08-01T21:53:20.898165Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"trained_model.load_state_dict(torch.load(UNET_TRAINED))","metadata":{"execution":{"iopub.status.busy":"2022-08-01T21:53:22.486364Z","iopub.execute_input":"2022-08-01T21:53:22.486778Z","iopub.status.idle":"2022-08-01T21:53:24.381925Z","shell.execute_reply.started":"2022-08-01T21:53:22.486747Z","shell.execute_reply":"2022-08-01T21:53:24.380842Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"trained_model = trained_model.to(\"cuda\")\ntrained_model.eval()\n","metadata":{"execution":{"iopub.status.busy":"2022-08-01T21:53:25.666220Z","iopub.execute_input":"2022-08-01T21:53:25.666716Z","iopub.status.idle":"2022-08-01T21:53:25.710365Z","shell.execute_reply.started":"2022-08-01T21:53:25.666661Z","shell.execute_reply":"2022-08-01T21:53:25.709052Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_path = \"../input/carvana-image-masking-challenge/29bb3ece3180_11.jpg\"\n\nimg = cv2.imread(img_path)","metadata":{"execution":{"iopub.status.busy":"2022-08-01T21:53:26.806653Z","iopub.execute_input":"2022-08-01T21:53:26.807175Z","iopub.status.idle":"2022-08-01T21:53:26.840592Z","shell.execute_reply.started":"2022-08-01T21:53:26.807142Z","shell.execute_reply":"2022-08-01T21:53:26.839445Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(img)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-08-01T21:53:27.957940Z","iopub.execute_input":"2022-08-01T21:53:27.958339Z","iopub.status.idle":"2022-08-01T21:53:28.455788Z","shell.execute_reply.started":"2022-08-01T21:53:27.958302Z","shell.execute_reply":"2022-08-01T21:53:28.454678Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_transform = A.Compose([A.Resize(572,572),\n                           A.Normalize(mean=(0,0,0),std=(1,1,1),max_pixel_value=255),\n                           ToTensorV2()])","metadata":{"execution":{"iopub.status.busy":"2022-08-01T21:53:30.133257Z","iopub.execute_input":"2022-08-01T21:53:30.136263Z","iopub.status.idle":"2022-08-01T21:53:30.145695Z","shell.execute_reply.started":"2022-08-01T21:53:30.136217Z","shell.execute_reply":"2022-08-01T21:53:30.144549Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_image = test_transform(image = img)\n\nprint(test_image)\n\nprint(test_image[\"image\"].dtype)\nprint(test_image[\"image\"].shape)\n\nimg = test_image[\"image\"].unsqueeze(0)\nprint(img.shape)\n\nimg = img.to(\"cuda\")","metadata":{"execution":{"iopub.status.busy":"2022-08-01T21:53:31.317507Z","iopub.execute_input":"2022-08-01T21:53:31.317940Z","iopub.status.idle":"2022-08-01T21:53:31.339025Z","shell.execute_reply.started":"2022-08-01T21:53:31.317906Z","shell.execute_reply":"2022-08-01T21:53:31.337956Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred = trained_model(img)\npred.shape","metadata":{"execution":{"iopub.status.busy":"2022-08-01T21:53:32.413116Z","iopub.execute_input":"2022-08-01T21:53:32.413805Z","iopub.status.idle":"2022-08-01T21:53:32.468581Z","shell.execute_reply.started":"2022-08-01T21:53:32.413770Z","shell.execute_reply":"2022-08-01T21:53:32.466361Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mask = pred.squeeze(0).cpu().detach().numpy()\nprint(mask.shape)\nmask = mask.transpose(1,2,0)\nprint(mask.shape)","metadata":{"execution":{"iopub.status.busy":"2022-08-01T21:53:34.767356Z","iopub.execute_input":"2022-08-01T21:53:34.767877Z","iopub.status.idle":"2022-08-01T21:53:34.777225Z","shell.execute_reply.started":"2022-08-01T21:53:34.767789Z","shell.execute_reply":"2022-08-01T21:53:34.775714Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"display_test_img = test_image[\"image\"].cpu().detach().numpy()\nprint(display_test_img.shape)\ndisplay_test_img = display_test_img.transpose(1,2,0)\ndisplay_test_img.shape","metadata":{"execution":{"iopub.status.busy":"2022-08-01T21:53:35.951638Z","iopub.execute_input":"2022-08-01T21:53:35.952850Z","iopub.status.idle":"2022-08-01T21:53:35.967789Z","shell.execute_reply.started":"2022-08-01T21:53:35.952807Z","shell.execute_reply":"2022-08-01T21:53:35.966533Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mask[mask < 0]=0\nmask[mask > 0]=1","metadata":{"execution":{"iopub.status.busy":"2022-08-01T21:53:39.088049Z","iopub.execute_input":"2022-08-01T21:53:39.089257Z","iopub.status.idle":"2022-08-01T21:53:39.096381Z","shell.execute_reply.started":"2022-08-01T21:53:39.089178Z","shell.execute_reply":"2022-08-01T21:53:39.095409Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"-------Original Image-------\")\nplt.imshow(display_test_img, cmap=\"gray\")\nplt.show()\nprint(\"-------Image Mask-------\")\nplt.imshow(mask,cmap=\"gray\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-08-01T21:53:41.252577Z","iopub.execute_input":"2022-08-01T21:53:41.253340Z","iopub.status.idle":"2022-08-01T21:53:41.785290Z","shell.execute_reply.started":"2022-08-01T21:53:41.253294Z","shell.execute_reply":"2022-08-01T21:53:41.784234Z"},"trusted":true},"execution_count":null,"outputs":[]}]}