{"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-04-27T10:35:20.943654Z","iopub.execute_input":"2022-04-27T10:35:20.944658Z","iopub.status.idle":"2022-04-27T10:35:20.958853Z","shell.execute_reply.started":"2022-04-27T10:35:20.944606Z","shell.execute_reply":"2022-04-27T10:35:20.957885Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Goal of this notebook to test this model:\nhttps://github.com/aladdinpersson/Machine-Learning-Collection/tree/master/ML/Pytorch/image_segmentation/semantic_segmentation_unet","metadata":{}},{"cell_type":"markdown","source":"also used code from:\n- https://www.kaggle.com/code/nandwalritik/u-net-pytorch","metadata":{}},{"cell_type":"code","source":"import os\nfrom PIL import Image\nfrom torch.utils.data import Dataset\n\nimport torch\nimport torchvision\nimport torch.nn as nn\nimport torchvision.transforms.functional as TF\nfrom torch.utils.data import DataLoader\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\nfrom tqdm import tqdm\nimport torch.optim as optim\n\n","metadata":{"execution":{"iopub.status.busy":"2022-04-27T10:06:36.712997Z","iopub.execute_input":"2022-04-27T10:06:36.713278Z","iopub.status.idle":"2022-04-27T10:06:36.719365Z","shell.execute_reply.started":"2022-04-27T10:06:36.713248Z","shell.execute_reply":"2022-04-27T10:06:36.718452Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from zipfile import ZipFile\n\ndatapth = \"../input/carvana-image-masking-challenge/\"\ndirs = ['train.zip','train_masks.zip']\ncdir = \"./\"\n\nfor x in dirs:\n    with ZipFile(datapth + x, 'r') as zipf:\n            zipf.extractall(cdir)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ls","metadata":{"execution":{"iopub.status.busy":"2022-04-27T10:06:42.465753Z","iopub.execute_input":"2022-04-27T10:06:42.466034Z","iopub.status.idle":"2022-04-27T10:06:43.128834Z","shell.execute_reply.started":"2022-04-27T10:06:42.466006Z","shell.execute_reply":"2022-04-27T10:06:43.128039Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Setting hyperparameters:","metadata":{}},{"cell_type":"code","source":"LEARNING_RATE = 1e-4\nDEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\nBATCH_SIZE = 16\nNUM_EPOCHS = 3\nNUM_WORKERS = 2\nIMAGE_HEIGHT = 160  # 1280 originally\nIMAGE_WIDTH = 240  # 1918 originally\nPIN_MEMORY = True\nLOAD_MODEL = False\nIMG_DIR = \"./train\"\nMASK_DIR = \"./train_masks\"","metadata":{"execution":{"iopub.status.busy":"2022-04-27T10:06:54.110825Z","iopub.execute_input":"2022-04-27T10:06:54.111098Z","iopub.status.idle":"2022-04-27T10:06:54.117082Z","shell.execute_reply.started":"2022-04-27T10:06:54.111069Z","shell.execute_reply":"2022-04-27T10:06:54.116072Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_imgs = os.listdir(TRAIN_IMG_DIR)\ntrain_masks = os.listdir(TRAIN_MASK_DIR)","metadata":{"execution":{"iopub.status.busy":"2022-04-27T10:07:02.454662Z","iopub.execute_input":"2022-04-27T10:07:02.454927Z","iopub.status.idle":"2022-04-27T10:07:02.468323Z","shell.execute_reply.started":"2022-04-27T10:07:02.454899Z","shell.execute_reply":"2022-04-27T10:07:02.467593Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Getting dataset","metadata":{}},{"cell_type":"code","source":"# Transformations to apply on images:\ntrain_transforms = A.Compose(\n        [\n            A.Resize(height=IMAGE_HEIGHT, width=IMAGE_WIDTH),\n            A.Rotate(limit=35, p=1.0),\n            A.HorizontalFlip(p=0.5),\n            A.VerticalFlip(p=0.1),\n            A.Normalize(\n                mean=[0.0, 0.0, 0.0],\n                std=[1.0, 1.0, 1.0],\n                max_pixel_value=255.0,\n            ),\n            ToTensorV2(),\n        ],\n    )\n\nval_transforms = A.Compose(\n        [\n            A.Resize(height=IMAGE_HEIGHT, width=IMAGE_WIDTH),\n            A.Normalize(\n                mean=[0.0, 0.0, 0.0],\n                std=[1.0, 1.0, 1.0],\n                max_pixel_value=255.0,\n            ),\n            ToTensorV2(),\n        ],\n    )\n\n#Getting dataset:\nclass CarvanaDataset(Dataset):\n    def __init__(self, images, image_dir, mask_dir, transform=None):\n        self.image_dir = image_dir\n        self.mask_dir = mask_dir\n        self.transform = transform\n        self.images = images\n\n    def __len__(self):\n        return len(self.images)\n\n    def __getitem__(self, index):\n        img_path = os.path.join(self.image_dir, self.images[index])\n        mask_path = os.path.join(self.mask_dir, self.images[index].replace(\".jpg\", \"_mask.gif\"))\n        image = np.array(Image.open(img_path).convert(\"RGB\"))\n        mask = np.array(Image.open(mask_path).convert(\"L\"), dtype=np.float32)\n        mask[mask == 255.0] = 1.0\n\n        if self.transform is not None:\n            augmentations = self.transform(image=image, mask=mask)\n            image = augmentations[\"image\"]\n            mask = augmentations[\"mask\"]\n\n        return image, mask","metadata":{"execution":{"iopub.status.busy":"2022-04-27T10:08:49.294179Z","iopub.execute_input":"2022-04-27T10:08:49.294597Z","iopub.status.idle":"2022-04-27T10:08:49.313343Z","shell.execute_reply.started":"2022-04-27T10:08:49.294561Z","shell.execute_reply":"2022-04-27T10:08:49.312490Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Separating training and validation set:","metadata":{}},{"cell_type":"code","source":"# from: https://www.kaggle.com/code/nandwalritik/u-net-pytorch\ndef train_test_split(images,splitSize=0.2):\n    imageLen = len(images)\n    val_len = int(splitSize*imageLen)\n    train_len = imageLen - val_len\n    train_images,val_images = images[:train_len],images[train_len:]\n    return train_images, val_images","metadata":{"execution":{"iopub.status.busy":"2022-04-27T10:07:11.907003Z","iopub.execute_input":"2022-04-27T10:07:11.907290Z","iopub.status.idle":"2022-04-27T10:07:11.912233Z","shell.execute_reply.started":"2022-04-27T10:07:11.907259Z","shell.execute_reply":"2022-04-27T10:07:11.911342Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_images, val_images = train_test_split(train_imgs)","metadata":{"execution":{"iopub.status.busy":"2022-04-27T10:07:15.850052Z","iopub.execute_input":"2022-04-27T10:07:15.850732Z","iopub.status.idle":"2022-04-27T10:07:15.854597Z","shell.execute_reply.started":"2022-04-27T10:07:15.850695Z","shell.execute_reply":"2022-04-27T10:07:15.853870Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_ds = CarvanaDataset(images=train_images,image_dir=IMG_DIR,mask_dir=MASK_DIR,transform=train_transforms)\ntrain_loader = DataLoader(train_ds,batch_size=BATCH_SIZE,num_workers=NUM_WORKERS,pin_memory=PIN_MEMORY,shuffle=True)\n\nvalid_ds = CarvanaDataset(images=val_images,image_dir=IMG_DIR,mask_dir=MASK_DIR,transform=val_transforms)\nvalid_loader = DataLoader(valid_ds,batch_size=BATCH_SIZE,num_workers=NUM_WORKERS,pin_memory=PIN_MEMORY,shuffle=True)","metadata":{"execution":{"iopub.status.busy":"2022-04-27T10:08:54.823752Z","iopub.execute_input":"2022-04-27T10:08:54.824240Z","iopub.status.idle":"2022-04-27T10:08:54.830990Z","shell.execute_reply.started":"2022-04-27T10:08:54.824181Z","shell.execute_reply":"2022-04-27T10:08:54.830267Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model definition","metadata":{}},{"cell_type":"code","source":"class DoubleConv(nn.Module):\n    def __init__(self, in_channels, out_channels):\n        super(DoubleConv, self).__init__()\n        self.conv = nn.Sequential(\n            nn.Conv2d(in_channels, out_channels, 3, 1, 1, bias=False),\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(out_channels, out_channels, 3, 1, 1, bias=False),\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(inplace=True),\n        )\n\n    def forward(self, x):\n        return self.conv(x)\n\nclass UNET(nn.Module):\n    def __init__(\n            self, in_channels=3, out_channels=1, features=[64, 128, 256, 512],\n    ):\n        super(UNET, self).__init__()\n        self.ups = nn.ModuleList()\n        self.downs = nn.ModuleList()\n        self.pool = nn.MaxPool2d(kernel_size=2, stride=2)\n\n        # Down part of UNET\n        for feature in features:\n            self.downs.append(DoubleConv(in_channels, feature))\n            in_channels = feature\n\n        # Up part of UNET\n        for feature in reversed(features):\n            self.ups.append(\n                nn.ConvTranspose2d(\n                    feature*2, feature, kernel_size=2, stride=2,\n                )\n            )\n            self.ups.append(DoubleConv(feature*2, feature))\n\n        self.bottleneck = DoubleConv(features[-1], features[-1]*2)\n        self.final_conv = nn.Conv2d(features[0], out_channels, kernel_size=1)\n\n    def forward(self, x):\n        skip_connections = []\n\n        for down in self.downs:\n            x = down(x)\n            skip_connections.append(x)\n            x = self.pool(x)\n\n        x = self.bottleneck(x)\n        skip_connections = skip_connections[::-1]\n\n        for idx in range(0, len(self.ups), 2):\n            x = self.ups[idx](x)\n            skip_connection = skip_connections[idx//2]\n\n            if x.shape != skip_connection.shape:\n                x = TF.resize(x, size=skip_connection.shape[2:])\n\n            concat_skip = torch.cat((skip_connection, x), dim=1)\n            x = self.ups[idx+1](concat_skip)\n\n        return self.final_conv(x)\n\ndef test():\n    x = torch.randn((3, 1, 161, 161))\n    model = UNET(in_channels=1, out_channels=1)\n    preds = model(x)\n    assert preds.shape == x.shape","metadata":{"execution":{"iopub.status.busy":"2022-04-27T10:09:07.601143Z","iopub.execute_input":"2022-04-27T10:09:07.601441Z","iopub.status.idle":"2022-04-27T10:09:07.618282Z","shell.execute_reply.started":"2022-04-27T10:09:07.601411Z","shell.execute_reply":"2022-04-27T10:09:07.617502Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Utilation functions","metadata":{}},{"cell_type":"code","source":"save_dir = \"/kaggle/working/saved_images\"\nos.mkdir(save_dir)","metadata":{"execution":{"iopub.status.busy":"2022-04-27T10:54:46.962222Z","iopub.execute_input":"2022-04-27T10:54:46.962866Z","iopub.status.idle":"2022-04-27T10:54:46.967731Z","shell.execute_reply.started":"2022-04-27T10:54:46.962827Z","shell.execute_reply":"2022-04-27T10:54:46.966532Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def save_checkpoint(state, filename=\"my_checkpoint.pth.tar\"):\n    print(\"=> Saving checkpoint\")\n    torch.save(state, filename)\n\ndef load_checkpoint(checkpoint, model):\n    print(\"=> Loading checkpoint\")\n    model.load_state_dict(checkpoint[\"state_dict\"])\n\ndef check_accuracy(loader, model, device=\"cuda\"):\n    num_correct = 0\n    num_pixels = 0\n    dice_score = 0\n    model.eval()\n\n    with torch.no_grad():\n        for x, y in loader:\n            x = x.to(device)\n            y = y.to(device).unsqueeze(1)\n            preds = torch.sigmoid(model(x))\n            preds = (preds > 0.5).float()\n            num_correct += (preds == y).sum()\n            num_pixels += torch.numel(preds)\n            dice_score += (2 * (preds * y).sum()) / (\n                (preds + y).sum() + 1e-8\n            )\n\n    print(\n        f\"Got {num_correct}/{num_pixels} with acc {num_correct/num_pixels*100:.2f}\"\n    )\n    print(f\"Dice score: {dice_score/len(loader)}\")\n    model.train()\n\ndef save_predictions_as_imgs(\n    loader, model, folder=save_dir, device=\"cuda\"\n):\n    model.eval()\n    for idx, (x, y) in enumerate(loader):\n        x = x.to(device=device)\n        with torch.no_grad():\n            preds = torch.sigmoid(model(x))\n            preds = (preds > 0.5).float()\n        torchvision.utils.save_image(\n            preds, f\"{folder}/pred_{idx}.png\"\n        )\n        torchvision.utils.save_image(y.unsqueeze(1), f\"{folder}{idx}.png\")\n\n    model.train()","metadata":{"execution":{"iopub.status.busy":"2022-04-27T10:56:02.847321Z","iopub.execute_input":"2022-04-27T10:56:02.847977Z","iopub.status.idle":"2022-04-27T10:56:02.859762Z","shell.execute_reply.started":"2022-04-27T10:56:02.847937Z","shell.execute_reply":"2022-04-27T10:56:02.858850Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Training","metadata":{}},{"cell_type":"code","source":"def fit(model,dataloader,data,optimizer,criterion):\n    print('-------------Training---------------')\n    model.train()\n    train_running_loss = 0.0\n    counter=0\n    \n    # num of batches\n    num_batches = int(len(data)/dataloader.batch_size)\n    for i,data in tqdm(enumerate(dataloader),total=num_batches):\n        counter+=1\n        image, mask = data[0].to(DEVICE), data[1].to(DEVICE)\n        optimizer.zero_grad()\n        outputs = model(image)\n        outputs =outputs.squeeze(1)\n        loss = criterion(outputs,mask)\n        train_running_loss += loss.item()\n        loss.backward()\n        optimizer.step()\n    train_loss = train_running_loss/counter\n    return train_loss\n\ndef validate(model,dataloader,data,criterion):\n    print(\"\\n--------Validating---------\\n\")\n    model.eval()\n    valid_running_loss = 0.0\n    counter = 0\n    # number of batches\n    num_batches = int(len(data)/dataloader.batch_size)\n    with torch.no_grad():\n        for i,data in tqdm(enumerate(dataloader),total=num_batches):\n            counter+=1\n            image, mask = data[0].to(DEVICE), data[1].to(DEVICE)\n            outputs = model(image)\n            outputs =outputs.squeeze(1)\n            loss = criterion(outputs,mask)\n            valid_running_loss += loss.item()\n    valid_loss = valid_running_loss/counter\n    return valid_loss","metadata":{"execution":{"iopub.status.busy":"2022-04-27T13:21:50.048071Z","iopub.execute_input":"2022-04-27T13:21:50.048754Z","iopub.status.idle":"2022-04-27T13:21:50.061015Z","shell.execute_reply.started":"2022-04-27T13:21:50.048713Z","shell.execute_reply":"2022-04-27T13:21:50.058519Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"    \n    model = UNET(in_channels=3, out_channels=1).to(DEVICE)\n    loss_fn = nn.BCEWithLogitsLoss()\n    optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)\n    #-----------------------------------------------------------#\n    \n    if LOAD_MODEL:\n        load_checkpoint(torch.load(\"my_checkpoint.pth.tar\"), model)\n    \n    train_loss=[]\n    val_loss=[]\n    \n    for epoch in range(NUM_EPOCHS):\n        \n        # Training and validation\n        print(f\"Epoch {epoch+1} of {NUM_EPOCHS}\")\n        train_epoch_loss = fit(model, train_loader, train_ds, optimizer, loss_fn)\n        val_epoch_loss = validate(model, valid_loader, valid_ds, loss_fn)        \n        train_loss.append(train_epoch_loss)\n        val_loss.append(val_epoch_loss)\n        print(f\"Train Loss: {train_epoch_loss:.4f}\")\n        print(f'Val Loss: {val_epoch_loss:.4f}')\n    \n        # Save model\n        checkpoint = {\n            \"state_dict\": model.state_dict(),\n            \"optimizer\":optimizer.state_dict(),\n        }\n        save_checkpoint(checkpoint)\n\n        # check accuracy\n        check_accuracy(valid_loader, model, device=DEVICE)\n\n        # print some examples to a folder\n        save_predictions_as_imgs(\n            valid_loader, model, folder=save_dir, device=DEVICE\n        )    \n","metadata":{"execution":{"iopub.status.busy":"2022-04-27T13:21:56.950015Z","iopub.execute_input":"2022-04-27T13:21:56.950723Z","iopub.status.idle":"2022-04-27T13:37:43.010363Z","shell.execute_reply.started":"2022-04-27T13:21:56.950683Z","shell.execute_reply":"2022-04-27T13:37:43.009464Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from matplotlib import pyplot as plt\n\n# loss plots\nplt.figure(figsize=(10, 7))\nplt.plot(train_loss, color=\"orange\", label='train loss')\nplt.plot(val_loss, color=\"red\", label='validation loss')\nplt.title(\"Training results\")\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Loss\")\nplt.legend()\n# plt.savefig(f\"../input/loss.png\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-04-27T14:03:15.657785Z","iopub.execute_input":"2022-04-27T14:03:15.658056Z","iopub.status.idle":"2022-04-27T14:03:15.892910Z","shell.execute_reply.started":"2022-04-27T14:03:15.658026Z","shell.execute_reply":"2022-04-27T14:03:15.892052Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}