{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":14774,"databundleVersionId":875431,"sourceType":"competition"}],"dockerImageVersionId":31090,"isInternetEnabled":false,"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\n# for 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,"execution":{"iopub.status.busy":"2025-10-28T06:20:35.212864Z","iopub.execute_input":"2025-10-28T06:20:35.213098Z","iopub.status.idle":"2025-10-28T06:20:36.687737Z","shell.execute_reply.started":"2025-10-28T06:20:35.213073Z","shell.execute_reply":"2025-10-28T06:20:36.686641Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train = pd.read_csv(\"/kaggle/input/aptos2019-blindness-detection/train.csv\")\ntest = pd.read_csv(\"/kaggle/input/aptos2019-blindness-detection/test.csv\")\nsample = pd.read_csv(\"/kaggle/input/aptos2019-blindness-detection/sample_submission.csv\")\n\n\ntrain.head()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-28T06:20:36.689716Z","iopub.execute_input":"2025-10-28T06:20:36.690113Z","iopub.status.idle":"2025-10-28T06:20:36.755585Z","shell.execute_reply.started":"2025-10-28T06:20:36.690087Z","shell.execute_reply":"2025-10-28T06:20:36.754894Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train.loc[train['id_code']=='ef476be214d4']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-28T06:20:36.756262Z","iopub.execute_input":"2025-10-28T06:20:36.756486Z","iopub.status.idle":"2025-10-28T06:20:36.775931Z","shell.execute_reply.started":"2025-10-28T06:20:36.756467Z","shell.execute_reply":"2025-10-28T06:20:36.775060Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-28T06:20:36.776943Z","iopub.execute_input":"2025-10-28T06:20:36.777472Z","iopub.status.idle":"2025-10-28T06:20:36.796419Z","shell.execute_reply.started":"2025-10-28T06:20:36.777438Z","shell.execute_reply":"2025-10-28T06:20:36.795650Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train.diagnosis.value_counts()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-28T06:20:36.797304Z","iopub.execute_input":"2025-10-28T06:20:36.797589Z","iopub.status.idle":"2025-10-28T06:20:36.825135Z","shell.execute_reply.started":"2025-10-28T06:20:36.797570Z","shell.execute_reply":"2025-10-28T06:20:36.824448Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train.diagnosis.value_counts().plot(kind='pie', autopct=\"%1.1f%%\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-28T06:20:36.826036Z","iopub.execute_input":"2025-10-28T06:20:36.826430Z","iopub.status.idle":"2025-10-28T06:20:37.230245Z","shell.execute_reply.started":"2025-10-28T06:20:36.826399Z","shell.execute_reply":"2025-10-28T06:20:37.229307Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sample.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-28T06:20:37.233430Z","iopub.execute_input":"2025-10-28T06:20:37.233725Z","iopub.status.idle":"2025-10-28T06:20:37.242160Z","shell.execute_reply.started":"2025-10-28T06:20:37.233701Z","shell.execute_reply":"2025-10-28T06:20:37.241400Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sample.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-28T06:20:37.242999Z","iopub.execute_input":"2025-10-28T06:20:37.243386Z","iopub.status.idle":"2025-10-28T06:20:37.261969Z","shell.execute_reply.started":"2025-10-28T06:20:37.243330Z","shell.execute_reply":"2025-10-28T06:20:37.260960Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-28T06:20:37.262808Z","iopub.execute_input":"2025-10-28T06:20:37.263060Z","iopub.status.idle":"2025-10-28T06:20:37.279473Z","shell.execute_reply.started":"2025-10-28T06:20:37.263038Z","shell.execute_reply":"2025-10-28T06:20:37.278634Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-28T06:20:37.280286Z","iopub.execute_input":"2025-10-28T06:20:37.280672Z","iopub.status.idle":"2025-10-28T06:20:37.301609Z","shell.execute_reply.started":"2025-10-28T06:20:37.280648Z","shell.execute_reply":"2025-10-28T06:20:37.300777Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train['image_path'] =  \"/kaggle/input/aptos2019-blindness-detection/train_images/\" + train['id_code'] +'.png'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-28T06:20:37.302513Z","iopub.execute_input":"2025-10-28T06:20:37.303053Z","iopub.status.idle":"2025-10-28T06:20:37.322409Z","shell.execute_reply.started":"2025-10-28T06:20:37.303021Z","shell.execute_reply":"2025-10-28T06:20:37.321410Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-28T06:20:37.323402Z","iopub.execute_input":"2025-10-28T06:20:37.323715Z","iopub.status.idle":"2025-10-28T06:20:37.345372Z","shell.execute_reply.started":"2025-10-28T06:20:37.323691Z","shell.execute_reply":"2025-10-28T06:20:37.344221Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test['file_path'] = \"/kaggle/input/aptos2019-blindness-detection/test_images/\"+test['id_code'] +'.png'\ntest","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-28T06:20:37.346482Z","iopub.execute_input":"2025-10-28T06:20:37.346870Z","iopub.status.idle":"2025-10-28T06:20:37.369031Z","shell.execute_reply.started":"2025-10-28T06:20:37.346838Z","shell.execute_reply":"2025-10-28T06:20:37.368399Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train = train.rename(columns={'image_path':'file_path', 'diagnosis':'label'})\ntrain","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-28T06:20:37.369818Z","iopub.execute_input":"2025-10-28T06:20:37.370149Z","iopub.status.idle":"2025-10-28T06:20:37.394077Z","shell.execute_reply.started":"2025-10-28T06:20:37.370115Z","shell.execute_reply":"2025-10-28T06:20:37.393386Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport pandas as pd\nfrom PIL import Image\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms, models\nfrom torchvision.models import resnet18","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-28T06:26:17.651146Z","iopub.execute_input":"2025-10-28T06:26:17.651480Z","iopub.status.idle":"2025-10-28T06:26:17.656365Z","shell.execute_reply.started":"2025-10-28T06:26:17.651457Z","shell.execute_reply":"2025-10-28T06:26:17.655567Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class EyeDataset(Dataset):\n    def __init__(self, df, transform):\n        self.df  = df.reset_index(drop=True)\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        img_path = self.df.loc[idx,'file_path']\n        label = self.df.loc[idx, 'label']\n\n        image = Image.open(img_path)\n\n        if self.transform:\n            image = self.transform(image)\n\n        return image, torch.tensor(label, dtype=torch.long)\n\n\ntransform = transforms.Compose([\n    transforms.Resize((224,224)),\n    transforms.RandomHorizontalFlip(),\n    transforms.RandomRotation(10),\n    transforms.ToTensor(),\n    transforms.Normalize(mean=[0.485,0.456,0.406],\n                         std =[0.229,0.224,0.225])\n])\n\ndataset = EyeDataset(train, transform=transform)\ntrain_laoder = DataLoader(dataset, batch_size=32, shuffle=True)\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-28T06:20:48.910058Z","iopub.execute_input":"2025-10-28T06:20:48.910441Z","iopub.status.idle":"2025-10-28T06:20:49.010310Z","shell.execute_reply.started":"2025-10-28T06:20:48.910419Z","shell.execute_reply":"2025-10-28T06:20:49.009260Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(device)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-28T06:20:49.011445Z","iopub.execute_input":"2025-10-28T06:20:49.011799Z","iopub.status.idle":"2025-10-28T06:20:49.044374Z","shell.execute_reply.started":"2025-10-28T06:20:49.011767Z","shell.execute_reply":"2025-10-28T06:20:49.043539Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = resnet18(weights=None)\nmodel.fc = nn.Linear(model.fc.in_features, train['label'].nunique())\nmodel = model.to(device)\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(), lr = 1e-4)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-28T06:26:22.834485Z","iopub.execute_input":"2025-10-28T06:26:22.835080Z","iopub.status.idle":"2025-10-28T06:26:23.315443Z","shell.execute_reply.started":"2025-10-28T06:26:22.835054Z","shell.execute_reply":"2025-10-28T06:26:23.314543Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"epochs = 5\nfor epoch in range(epochs):\n    model.train()\n    total_loss = 0\n    correct =  0\n    total = 0\n\n    for images, labels in train_laoder:\n        images, labels = images.to(device), labels.to(device)\n\n        optimizer.zero_grad()\n        outputs = model(images)\n        loss = criterion(outputs, labels)\n        loss.backward()\n        optimizer.step()\n\n        total_loss += loss.item()\n        _, preds = torch.max(outputs, 1)\n        correct += (preds==labels).sum().item()\n        total += labels.size(0)\n\n    acc = correct/total\n    print(f\"Epoch {epoch+1}/{epochs}, loss : {total_loss: .4f}, Acc: {acc:.4f}\")\n\ntorch.save(model.state_dict(), \"resnet_eye_model.pth\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-28T06:26:25.778581Z","iopub.execute_input":"2025-10-28T06:26:25.779055Z","iopub.status.idle":"2025-10-28T07:06:10.198642Z","shell.execute_reply.started":"2025-10-28T06:26:25.779028Z","shell.execute_reply":"2025-10-28T07:06:10.197816Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"val_tfms = transforms.Compose([\n    transforms.Resize((224, 224)),\n    transforms.ToTensor(),\n    transforms.Normalize(mean=[0.485, 0.456, 0.406],\n                         std=[0.229, 0.224, 0.225])\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-28T07:06:10.200188Z","iopub.execute_input":"2025-10-28T07:06:10.200914Z","iopub.status.idle":"2025-10-28T07:06:10.205249Z","shell.execute_reply.started":"2025-10-28T07:06:10.200889Z","shell.execute_reply":"2025-10-28T07:06:10.204409Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class TestDataset(Dataset):\n    def __init__(self, df, transform):\n        self.df = df.reset_index(drop=True)\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        image_path = self.df.loc[idx, 'file_path']\n        image = Image.open(image_path)\n        if self.transform:\n            image = self.transform(image)\n        return image\n\n\ntest_ds = TestDataset(test, transform=val_tfms)\ntest_loader = DataLoader(test_ds, batch_size= 32, shuffle=False)\n\nmodel.eval()\nall_preds = []\nwith torch.no_grad():\n    for images in test_loader:\n        images = images.to(device)\n        outputs = model(images)\n        preds = outputs.argmax(dim=1).detach().cpu().numpy()\n        all_preds.extend(preds)\n\nsub = pd.DataFrame({\n    'id_code':test['file_path'],\n    'prediction': all_preds\n})\nsub.head()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-28T07:06:10.206277Z","iopub.execute_input":"2025-10-28T07:06:10.206556Z","iopub.status.idle":"2025-10-28T07:08:27.068446Z","shell.execute_reply.started":"2025-10-28T07:06:10.206535Z","shell.execute_reply":"2025-10-28T07:08:27.067560Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sub['prediction'].value_counts().plot(kind='bar')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-28T07:08:27.070000Z","iopub.execute_input":"2025-10-28T07:08:27.070267Z","iopub.status.idle":"2025-10-28T07:08:27.226875Z","shell.execute_reply.started":"2025-10-28T07:08:27.070248Z","shell.execute_reply":"2025-10-28T07:08:27.225919Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}