{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":6927,"databundleVersionId":45059,"sourceType":"competition"}],"dockerImageVersionId":30762,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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":"2024-09-21T09:02:53.200325Z","iopub.execute_input":"2024-09-21T09:02:53.200777Z","iopub.status.idle":"2024-09-21T09:02:53.60651Z","shell.execute_reply.started":"2024-09-21T09:02:53.200728Z","shell.execute_reply":"2024-09-21T09:02:53.605501Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-09-21T09:02:53.608461Z","iopub.execute_input":"2024-09-21T09:02:53.608972Z","iopub.status.idle":"2024-09-21T09:02:58.267319Z","shell.execute_reply.started":"2024-09-21T09:02:53.608925Z","shell.execute_reply":"2024-09-21T09:02:58.266475Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-09-21T09:02:58.2685Z","iopub.execute_input":"2024-09-21T09:02:58.269032Z","iopub.status.idle":"2024-09-21T09:02:58.276006Z","shell.execute_reply.started":"2024-09-21T09:02:58.268985Z","shell.execute_reply":"2024-09-21T09:02:58.275061Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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\n\n# U-Net architecture includes skip connections which allow for the fusion of low-level and high-level features, aiding in better localization. \n# In this downsampling part of the architecture, before doing the MaxPooling, we save the convolutioned tensor. That convolutioned tensor is later on concatenated with an upsampled tensor with its own dimension. \n# In the code, this can be seen that the createdDownSample class return two variables down and p.","metadata":{"execution":{"iopub.status.busy":"2024-09-21T09:02:58.279003Z","iopub.execute_input":"2024-09-21T09:02:58.279303Z","iopub.status.idle":"2024-09-21T09:02:58.290509Z","shell.execute_reply.started":"2024-09-21T09:02:58.279271Z","shell.execute_reply":"2024-09-21T09:02:58.289648Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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)\n\n# Here we can ask ourselves why Upsample receive two tensors meanwhile Downsample only receives one. \n# This is because Downsample returns two variables p and down and the latter is saved to be later on concatenated with the output of the Upsample class \n# (i.e., the nn.ConvTranspose2d). Downsampleonly receives one because the skip connections are not applied in the encoding path, only in the decoding one.\n","metadata":{"execution":{"iopub.status.busy":"2024-09-21T09:02:58.29171Z","iopub.execute_input":"2024-09-21T09:02:58.292516Z","iopub.status.idle":"2024-09-21T09:02:58.302305Z","shell.execute_reply.started":"2024-09-21T09:02:58.292482Z","shell.execute_reply":"2024-09-21T09:02:58.301509Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-09-21T09:02:58.303443Z","iopub.execute_input":"2024-09-21T09:02:58.303756Z","iopub.status.idle":"2024-09-21T09:02:58.313332Z","shell.execute_reply.started":"2024-09-21T09:02:58.303724Z","shell.execute_reply":"2024-09-21T09:02:58.312407Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"![Graphical Representation](https://miro.medium.com/v2/resize:fit:828/format:webp/1*4nwUFJwS-EdYade_Lt5xTA.png)","metadata":{}},{"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)\n","metadata":{"execution":{"iopub.status.busy":"2024-09-21T09:02:58.314489Z","iopub.execute_input":"2024-09-21T09:02:58.315079Z","iopub.status.idle":"2024-09-21T09:02:58.325523Z","shell.execute_reply.started":"2024-09-21T09:02:58.315021Z","shell.execute_reply":"2024-09-21T09:02:58.32438Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(os.listdir(\"../input/carvana-image-masking-challenge/\"))\n\nDATASET_DIR = '../input/carvana-image-masking-challenge/'\nWORKING_DIR = '/kaggle/working/'\n","metadata":{"execution":{"iopub.status.busy":"2024-09-21T09:02:58.326652Z","iopub.execute_input":"2024-09-21T09:02:58.326981Z","iopub.status.idle":"2024-09-21T09:02:58.337453Z","shell.execute_reply.started":"2024-09-21T09:02:58.326948Z","shell.execute_reply":"2024-09-21T09:02:58.336505Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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    )\n","metadata":{"execution":{"iopub.status.busy":"2024-09-21T09:02:58.339019Z","iopub.execute_input":"2024-09-21T09:02:58.339345Z","iopub.status.idle":"2024-09-21T09:03:07.897365Z","shell.execute_reply.started":"2024-09-21T09:02:58.339314Z","shell.execute_reply":"2024-09-21T09:03:07.896372Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dataset = CarvanaDataset(WORKING_DIR)\n\ngenerator = torch.Generator().manual_seed(25)\n","metadata":{"execution":{"iopub.status.busy":"2024-09-21T09:03:07.901533Z","iopub.execute_input":"2024-09-21T09:03:07.901863Z","iopub.status.idle":"2024-09-21T09:03:07.917999Z","shell.execute_reply.started":"2024-09-21T09:03:07.90183Z","shell.execute_reply":"2024-09-21T09:03:07.91729Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dataset, test_dataset = random_split(train_dataset, [0.8, 0.2], generator=generator)\ntest_dataset, val_dataset = random_split(test_dataset, [0.5, 0.5], generator=generator)","metadata":{"execution":{"iopub.status.busy":"2024-09-21T09:03:07.918953Z","iopub.execute_input":"2024-09-21T09:03:07.919238Z","iopub.status.idle":"2024-09-21T09:03:07.943867Z","shell.execute_reply.started":"2024-09-21T09:03:07.919206Z","shell.execute_reply":"2024-09-21T09:03:07.94291Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\nif device == \"cuda\":\n    num_workers = torch.cuda.device_count() * 4","metadata":{"execution":{"iopub.status.busy":"2024-09-21T09:03:07.945176Z","iopub.execute_input":"2024-09-21T09:03:07.945548Z","iopub.status.idle":"2024-09-21T09:03:08.027002Z","shell.execute_reply.started":"2024-09-21T09:03:07.945507Z","shell.execute_reply":"2024-09-21T09:03:08.026222Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"LEARNING_RATE = 3e-4\nBATCH_SIZE = 8\n\ntrain_dataloader = DataLoader(dataset=train_dataset,\n                              num_workers=num_workers, pin_memory=False,\n                              batch_size=BATCH_SIZE,\n                              shuffle=True)\nval_dataloader = DataLoader(dataset=val_dataset,\n                            num_workers=num_workers, pin_memory=False,\n                            batch_size=BATCH_SIZE,\n                            shuffle=True)\n\ntest_dataloader = DataLoader(dataset=test_dataset,\n                            num_workers=num_workers, pin_memory=False,\n                            batch_size=BATCH_SIZE,\n                            shuffle=True)\n\nmodel = UNet(in_channels=3, num_classes=1).to(device)\noptimizer = optim.AdamW(model.parameters(), lr=LEARNING_RATE)\ncriterion = nn.BCEWithLogitsLoss()","metadata":{"execution":{"iopub.status.busy":"2024-09-21T09:03:08.027965Z","iopub.execute_input":"2024-09-21T09:03:08.028252Z","iopub.status.idle":"2024-09-21T09:03:08.508975Z","shell.execute_reply.started":"2024-09-21T09:03:08.028221Z","shell.execute_reply":"2024-09-21T09:03:08.508192Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def dice_coefficient(prediction, target, epsilon=1e-07):\n    prediction_copy = prediction.clone()\n\n    prediction_copy[prediction_copy < 0] = 0\n    prediction_copy[prediction_copy > 0] = 1\n\n    intersection = abs(torch.sum(prediction_copy * target))\n    union = abs(torch.sum(prediction_copy) + torch.sum(target))\n    dice = (2. * intersection + epsilon) / (union + epsilon)\n    \n    return dice","metadata":{"execution":{"iopub.status.busy":"2024-09-21T09:03:08.510019Z","iopub.execute_input":"2024-09-21T09:03:08.510313Z","iopub.status.idle":"2024-09-21T09:03:08.516099Z","shell.execute_reply.started":"2024-09-21T09:03:08.510281Z","shell.execute_reply":"2024-09-21T09:03:08.515111Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"torch.cuda.empty_cache()\n","metadata":{"execution":{"iopub.status.busy":"2024-09-21T09:03:08.517306Z","iopub.execute_input":"2024-09-21T09:03:08.517683Z","iopub.status.idle":"2024-09-21T09:03:08.5239Z","shell.execute_reply.started":"2024-09-21T09:03:08.517636Z","shell.execute_reply":"2024-09-21T09:03:08.523107Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"EPOCHS = 10\n\ntrain_losses = []\ntrain_dcs = []\nval_losses = []\nval_dcs = []\n\nfor epoch in tqdm(range(EPOCHS)):\n    model.train()\n    train_running_loss = 0\n    train_running_dc = 0\n    \n    for idx, img_mask in enumerate(tqdm(train_dataloader, position=0, leave=True)):\n        img = img_mask[0].float().to(device)\n        mask = img_mask[1].float().to(device)\n        \n        y_pred = model(img)\n        optimizer.zero_grad()\n        \n        dc = dice_coefficient(y_pred, mask)\n        loss = criterion(y_pred, mask)\n        \n        train_running_loss += loss.item()\n        train_running_dc += dc.item()\n\n        loss.backward()\n        optimizer.step()\n\n    train_loss = train_running_loss / (idx + 1)\n    train_dc = train_running_dc / (idx + 1)\n    \n    train_losses.append(train_loss)\n    train_dcs.append(train_dc)\n\n    model.eval()\n    val_running_loss = 0\n    val_running_dc = 0\n    \n    with torch.no_grad():\n        for idx, img_mask in enumerate(tqdm(val_dataloader, position=0, leave=True)):\n            img = img_mask[0].float().to(device)\n            mask = img_mask[1].float().to(device)\n\n            y_pred = model(img)\n            loss = criterion(y_pred, mask)\n            dc = dice_coefficient(y_pred, mask)\n            \n            val_running_loss += loss.item()\n            val_running_dc += dc.item()\n\n        val_loss = val_running_loss / (idx + 1)\n        val_dc = val_running_dc / (idx + 1)\n    \n    val_losses.append(val_loss)\n    val_dcs.append(val_dc)\n\n    print(\"-\" * 30)\n    print(f\"Training Loss EPOCH {epoch + 1}: {train_loss:.4f}\")\n    print(f\"Training DICE EPOCH {epoch + 1}: {train_dc:.4f}\")\n    print(\"\\n\")\n    print(f\"Validation Loss EPOCH {epoch + 1}: {val_loss:.4f}\")\n    print(f\"Validation DICE EPOCH {epoch + 1}: {val_dc:.4f}\")\n    print(\"-\" * 30)\n\n# Saving the model\ntorch.save(model.state_dict(), 'my_checkpoint.pth')\n","metadata":{"execution":{"iopub.status.busy":"2024-09-21T09:03:08.525058Z","iopub.execute_input":"2024-09-21T09:03:08.525438Z","iopub.status.idle":"2024-09-21T11:19:29.467997Z","shell.execute_reply.started":"2024-09-21T09:03:08.525393Z","shell.execute_reply":"2024-09-21T11:19:29.466976Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epochs_list = list(range(1, EPOCHS + 1))\n\nplt.figure(figsize=(12, 5))\nplt.subplot(1, 2, 1)\nplt.plot(epochs_list, train_losses, label='Training Loss')\nplt.plot(epochs_list, val_losses, label='Validation Loss')\nplt.xticks(ticks=list(range(1, EPOCHS + 1, 1))) \nplt.title('Loss over epochs')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.grid()\nplt.tight_layout()\n\nplt.legend()\n\n\nplt.subplot(1, 2, 2)\nplt.plot(epochs_list, train_dcs, label='Training DICE')\nplt.plot(epochs_list, val_dcs, label='Validation DICE')\nplt.xticks(ticks=list(range(1, EPOCHS + 1, 1)))  \nplt.title('DICE Coefficient over epochs')\nplt.xlabel('Epochs')\nplt.ylabel('DICE')\nplt.grid()\nplt.legend()\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-09-21T11:19:29.469585Z","iopub.execute_input":"2024-09-21T11:19:29.469966Z","iopub.status.idle":"2024-09-21T11:19:30.189759Z","shell.execute_reply.started":"2024-09-21T11:19:29.46993Z","shell.execute_reply":"2024-09-21T11:19:30.188817Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epochs_list = list(range(1, EPOCHS + 1))\n\nplt.figure(figsize=(12, 5))\nplt.plot(epochs_list, train_losses, label='Training Loss')\nplt.plot(epochs_list, val_losses, label='Validation Loss')\nplt.xticks(ticks=list(range(1, EPOCHS + 1, 1))) \nplt.ylim(0, 0.05)\nplt.title('Loss over epochs (zoomed)')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.grid()\nplt.tight_layout()\n\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-09-21T11:19:30.191064Z","iopub.execute_input":"2024-09-21T11:19:30.191423Z","iopub.status.idle":"2024-09-21T11:19:30.577297Z","shell.execute_reply.started":"2024-09-21T11:19:30.191384Z","shell.execute_reply":"2024-09-21T11:19:30.576341Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_pth = '/kaggle/working/my_checkpoint.pth'\ntrained_model = UNet(in_channels=3, num_classes=1).to(device)\ntrained_model.load_state_dict(torch.load(model_pth, map_location=torch.device(device)))\n","metadata":{"execution":{"iopub.status.busy":"2024-09-21T11:19:30.578497Z","iopub.execute_input":"2024-09-21T11:19:30.578832Z","iopub.status.idle":"2024-09-21T11:19:30.969803Z","shell.execute_reply.started":"2024-09-21T11:19:30.578797Z","shell.execute_reply":"2024-09-21T11:19:30.968837Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_running_loss = 0\ntest_running_dc = 0\n\nwith torch.no_grad():\n    for idx, img_mask in enumerate(tqdm(test_dataloader, position=0, leave=True)):\n        img = img_mask[0].float().to(device)\n        mask = img_mask[1].float().to(device)\n\n        y_pred = trained_model(img)\n        loss = criterion(y_pred, mask)\n        dc = dice_coefficient(y_pred, mask)\n\n        test_running_loss += loss.item()\n        test_running_dc += dc.item()\n\n    test_loss = test_running_loss / (idx + 1)\n    test_dc = test_running_dc / (idx + 1)\n","metadata":{"execution":{"iopub.status.busy":"2024-09-21T11:19:30.971045Z","iopub.execute_input":"2024-09-21T11:19:30.97137Z","iopub.status.idle":"2024-09-21T11:20:09.174237Z","shell.execute_reply.started":"2024-09-21T11:19:30.971321Z","shell.execute_reply":"2024-09-21T11:20:09.17284Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def random_images_inference(image_tensors, mask_tensors, image_paths, model_pth, device):\n    model = UNet(in_channels=3, num_classes=1).to(device)\n    model.load_state_dict(torch.load(model_pth, map_location=torch.device(device)))\n\n    transform = transforms.Compose([\n        transforms.Resize((512, 512))\n    ])\n\n    # Iterate for the images, masks and paths\n    for image_pth, mask_pth, image_paths in zip(image_tensors, mask_tensors, image_paths):\n        # Load the image\n        img = transform(image_pth)\n        \n        # Predict the imagen with the model\n        pred_mask = model(img.unsqueeze(0))\n        pred_mask = pred_mask.squeeze(0).permute(1,2,0)\n        \n        # Load the mask to compare\n        mask = transform(mask_pth).permute(1, 2, 0).to(device)\n        \n        print(f\"Image: {os.path.basename(image_paths)}, DICE coefficient: {round(float(dice_coefficient(pred_mask, mask)),5)}\")\n        \n        # Show the images\n        img = img.cpu().detach().permute(1, 2, 0)\n        pred_mask = pred_mask.cpu().detach()\n        pred_mask[pred_mask < 0] = 0\n        pred_mask[pred_mask > 0] = 1\n        \n        plt.figure(figsize=(15, 16))\n        plt.subplot(131), plt.imshow(img), plt.title(\"original\")\n        plt.subplot(132), plt.imshow(pred_mask, cmap=\"gray\"), plt.title(\"predicted\")\n        plt.subplot(133), plt.imshow(mask, cmap=\"gray\"), plt.title(\"mask\")\n        plt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-09-21T11:20:09.17575Z","iopub.execute_input":"2024-09-21T11:20:09.176092Z","iopub.status.idle":"2024-09-21T11:20:09.187462Z","shell.execute_reply.started":"2024-09-21T11:20:09.176057Z","shell.execute_reply":"2024-09-21T11:20:09.186442Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"n = 10\n\nimage_tensors = []\nmask_tensors = []\nimage_paths = []\n\nfor _ in range(n):\n    random_index = random.randint(0, len(test_dataloader.dataset) - 1)\n    random_sample = test_dataloader.dataset[random_index]\n\n    image_tensors.append(random_sample[0])  \n    mask_tensors.append(random_sample[1]) \n    image_paths.append(random_sample[2]) \n","metadata":{"execution":{"iopub.status.busy":"2024-09-21T11:20:09.188739Z","iopub.execute_input":"2024-09-21T11:20:09.189065Z","iopub.status.idle":"2024-09-21T11:20:09.577793Z","shell.execute_reply.started":"2024-09-21T11:20:09.189029Z","shell.execute_reply":"2024-09-21T11:20:09.576522Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_path = '/kaggle/working/my_checkpoint.pth'\n\nrandom_images_inference(image_tensors, mask_tensors, image_paths, model_pàth, device=\"cpu\")\n","metadata":{"execution":{"iopub.status.busy":"2024-09-21T11:20:09.578531Z","iopub.status.idle":"2024-09-21T11:20:09.578893Z","shell.execute_reply.started":"2024-09-21T11:20:09.578719Z","shell.execute_reply":"2024-09-21T11:20:09.578738Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}