{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":6927,"databundleVersionId":45059,"sourceType":"competition"}],"dockerImageVersionId":31089,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Paketi koji se koriste**","metadata":{}},{"cell_type":"code","source":"import copy\nimport os\nimport random\nimport shutil\nimport zipfile\nfrom math import atan2, cos, sin, sqrt, pi, log\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision.transforms as transforms\nfrom PIL import Image\nfrom numpy import linalg as LA\nfrom torch import optim, nn\nfrom torch.utils.data import DataLoader, random_split\nfrom torch.utils.data.dataset import Dataset\nfrom torchvision import transforms\nfrom tqdm import tqdm","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-24T13:44:10.792624Z","iopub.execute_input":"2025-08-24T13:44:10.793063Z","iopub.status.idle":"2025-08-24T13:44:23.678233Z","shell.execute_reply.started":"2025-08-24T13:44:10.793028Z","shell.execute_reply":"2025-08-24T13:44:23.676864Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Prvo definišemo dvostruku konvoluciju koja se ponavlja u svakom koraku. Sadrži se od dvije konvolucije sa 3x3 kernelom, sa ReLU aktivacionom funkcijom.","metadata":{}},{"cell_type":"code","source":"class DoubleConv(nn.Module):\n    def __init__(self, in_channels, out_channels):\n        super().__init__()\n        self.conv_op = nn.Sequential(\n            nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),\n            nn.ReLU(inplace=True)\n        )\n\n    def forward(self, x):\n        return self.conv_op(x)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-24T13:46:50.786856Z","iopub.execute_input":"2025-08-24T13:46:50.787259Z","iopub.status.idle":"2025-08-24T13:46:50.794196Z","shell.execute_reply.started":"2025-08-24T13:46:50.787231Z","shell.execute_reply":"2025-08-24T13:46:50.792978Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> Downsample dio","metadata":{}},{"cell_type":"code","source":"class DownSample(nn.Module):\n    def __init__(self, in_channels, out_channels):\n        super().__init__()\n        self.conv = DoubleConv(in_channels, out_channels)\n        self.pool = nn.MaxPool2d(kernel_size=2, stride=2)\n\n    def forward(self, x):\n        down = self.conv(x)\n        p = self.pool(down)\n\n        return down, p","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-24T13:47:25.788188Z","iopub.execute_input":"2025-08-24T13:47:25.788615Z","iopub.status.idle":"2025-08-24T13:47:25.796671Z","shell.execute_reply.started":"2025-08-24T13:47:25.788581Z","shell.execute_reply":"2025-08-24T13:47:25.795275Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class UpSample(nn.Module):\n    def __init__(self, in_channels, out_channels):\n        super().__init__()\n        self.up = nn.ConvTranspose2d(in_channels, in_channels//2, kernel_size=2, stride=2)\n        self.conv = DoubleConv(in_channels, out_channels)\n\n    def forward(self, x1, x2):\n        x1 = self.up(x1)\n        x = torch.cat([x1, x2], 1)\n        return self.conv(x)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-24T13:48:05.399767Z","iopub.execute_input":"2025-08-24T13:48:05.400129Z","iopub.status.idle":"2025-08-24T13:48:05.407419Z","shell.execute_reply.started":"2025-08-24T13:48:05.400103Z","shell.execute_reply":"2025-08-24T13:48:05.406189Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class UNet(nn.Module):\n    def __init__(self, in_channels, num_classes):\n        super().__init__()\n        self.down_convolution_1 = DownSample(in_channels, 64)\n        self.down_convolution_2 = DownSample(64, 128)\n        self.down_convolution_3 = DownSample(128, 256)\n        self.down_convolution_4 = DownSample(256, 512)\n\n        self.bottle_neck = DoubleConv(512, 1024)\n\n        self.up_convolution_1 = UpSample(1024, 512)\n        self.up_convolution_2 = UpSample(512, 256)\n        self.up_convolution_3 = UpSample(256, 128)\n        self.up_convolution_4 = UpSample(128, 64)\n\n        self.out = nn.Conv2d(in_channels=64, out_channels=num_classes, kernel_size=1)\n\n    def forward(self, x):\n        down_1, p1 = self.down_convolution_1(x)\n        down_2, p2 = self.down_convolution_2(p1)\n        down_3, p3 = self.down_convolution_3(p2)\n        down_4, p4 = self.down_convolution_4(p3)\n\n        b = self.bottle_neck(p4)\n\n        up_1 = self.up_convolution_1(b, down_4)\n        up_2 = self.up_convolution_2(up_1, down_3)\n        up_3 = self.up_convolution_3(up_2, down_2)\n        up_4 = self.up_convolution_4(up_3, down_1)\n\n        out = self.out(up_4)\n        return out","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-24T13:48:17.915263Z","iopub.execute_input":"2025-08-24T13:48:17.915642Z","iopub.status.idle":"2025-08-24T13:48:17.925045Z","shell.execute_reply.started":"2025-08-24T13:48:17.915614Z","shell.execute_reply":"2025-08-24T13:48:17.923823Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"input_image = torch.rand((1,3,512,512))\nmodel = UNet(3,10)\noutput = model(input_image)\nprint(output.size())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-24T13:48:28.338891Z","iopub.execute_input":"2025-08-24T13:48:28.339269Z","iopub.status.idle":"2025-08-24T13:48:33.708141Z","shell.execute_reply.started":"2025-08-24T13:48:28.339243Z","shell.execute_reply":"2025-08-24T13:48:33.707127Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class CarvanaDataset(Dataset):\n    def __init__(self, root_path, limit=None):\n        self.root_path = root_path\n        self.limit = limit\n        self.images = sorted([root_path + \"/train/\" + i for i in os.listdir(root_path + \"/train/\")])[:self.limit]\n        self.masks = sorted([root_path + \"/train_masks/\" + i for i in os.listdir(root_path + \"/train_masks/\")])[:self.limit]\n\n        self.transform = transforms.Compose([\n            transforms.Resize((512, 512)),\n            transforms.ToTensor()])\n        \n        if self.limit is None:\n            self.limit = len(self.images)\n\n    def __getitem__(self, index):\n        img = Image.open(self.images[index]).convert(\"RGB\")\n        mask = Image.open(self.masks[index]).convert(\"L\")\n\n        return self.transform(img), self.transform(mask)\n\n    def __len__(self):\n        return min(len(self.images), self.limit)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-24T13:48:51.465506Z","iopub.execute_input":"2025-08-24T13:48:51.465936Z","iopub.status.idle":"2025-08-24T13:48:51.475805Z","shell.execute_reply.started":"2025-08-24T13:48:51.465902Z","shell.execute_reply":"2025-08-24T13:48:51.474493Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(os.listdir(\"../input/carvana-image-masking-challenge/\"))\n\nDATASET_DIR = '../input/carvana-image-masking-challenge/'\nWORKING_DIR = '/kaggle/working/'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-24T13:59:16.568490Z","iopub.execute_input":"2025-08-24T13:59:16.569601Z","iopub.status.idle":"2025-08-24T13:59:16.584349Z","shell.execute_reply.started":"2025-08-24T13:59:16.569560Z","shell.execute_reply":"2025-08-24T13:59:16.582977Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"if len(os.listdir(WORKING_DIR)) <= 1:\n\n    with zipfile.ZipFile(DATASET_DIR + 'train.zip', 'r') as zip_file:\n        zip_file.extractall(WORKING_DIR)\n\n    with zipfile.ZipFile(DATASET_DIR + 'train_masks.zip', 'r') as zip_file:\n        zip_file.extractall(WORKING_DIR)\n    \n    print(\n        len(os.listdir(WORKING_DIR + 'train')),\n        len(os.listdir(WORKING_DIR + 'train_masks'))\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-24T13:59:33.023666Z","iopub.execute_input":"2025-08-24T13:59:33.024454Z","iopub.status.idle":"2025-08-24T13:59:43.714607Z","shell.execute_reply.started":"2025-08-24T13:59:33.024418Z","shell.execute_reply":"2025-08-24T13:59:43.713405Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_dataset = CarvanaDataset(WORKING_DIR)\n\ngenerator = torch.Generator().manual_seed(25)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-24T14:00:29.442308Z","iopub.execute_input":"2025-08-24T14:00:29.442782Z","iopub.status.idle":"2025-08-24T14:00:29.461507Z","shell.execute_reply.started":"2025-08-24T14:00:29.442708Z","shell.execute_reply":"2025-08-24T14:00:29.460314Z"}},"outputs":[],"execution_count":null}]}