{"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":"gpu","dataSources":[{"sourceId":13836,"databundleVersionId":1718836,"isSourceIdPinned":false,"sourceType":"competition"},{"sourceId":13809889,"sourceType":"datasetVersion","datasetId":8793656}],"dockerImageVersionId":31193,"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\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":"code","source":"import os\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\n\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms, models\n\nDEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\nIMG_SIZE = 512\nBATCH_SIZE = 16\nNUM_CLASSES = 5\nN_FOLDS = 5\n\nDATA_DIR = \"/kaggle/input/cassava-leaf-disease-classification\"\nTEST_DIR = os.path.join(DATA_DIR, \"test_images\")\nSAMPLE_SUB = os.path.join(DATA_DIR, \"sample_submission.csv\")\n\nMODELS_DIR = \"/kaggle/input/cassava-resnet-fold-models\"\n\nprint(\"Device:\", DEVICE)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-20T23:13:55.591409Z","iopub.execute_input":"2025-11-20T23:13:55.591622Z","iopub.status.idle":"2025-11-20T23:14:04.034961Z","shell.execute_reply.started":"2025-11-20T23:13:55.591604Z","shell.execute_reply":"2025-11-20T23:14:04.034235Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class CassavaTestDataset(Dataset):\n    def __init__(self, df, img_dir, transforms=None):\n        self.df = df.reset_index(drop=True)\n        self.img_dir = img_dir\n        self.transforms = transforms\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        row = self.df.iloc[idx]\n        img_path = os.path.join(self.img_dir, row[\"image_id\"])\n        image = Image.open(img_path)\n        if image.mode != \"RGB\":\n            image = image.convert(\"RGB\")\n        if self.transforms:\n            image = self.transforms(image)\n        return image, row[\"image_id\"]\n\nval_transforms = transforms.Compose([\n    transforms.Resize((IMG_SIZE, IMG_SIZE)),\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-11-20T23:14:08.162920Z","iopub.execute_input":"2025-11-20T23:14:08.163630Z","iopub.status.idle":"2025-11-20T23:14:08.172143Z","shell.execute_reply.started":"2025-11-20T23:14:08.163598Z","shell.execute_reply":"2025-11-20T23:14:08.171381Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def build_model(num_classes=NUM_CLASSES):\n    model = models.resnet50(weights=None)\n    in_features = model.fc.in_features\n    model.fc = nn.Linear(in_features, num_classes)\n    return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-20T23:14:27.567940Z","iopub.execute_input":"2025-11-20T23:14:27.568674Z","iopub.status.idle":"2025-11-20T23:14:27.573045Z","shell.execute_reply.started":"2025-11-20T23:14:27.568651Z","shell.execute_reply":"2025-11-20T23:14:27.572173Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sub_df = pd.read_csv(SAMPLE_SUB)\ntest_df = sub_df.copy()\n\ntest_dataset = CassavaTestDataset(test_df, TEST_DIR, transforms=val_transforms)\ntest_loader = DataLoader(\n    test_dataset,\n    batch_size=BATCH_SIZE,\n    shuffle=False,\n    num_workers=4,\n    pin_memory=True\n)\n\nlen(test_df), test_df.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-20T23:14:37.400271Z","iopub.execute_input":"2025-11-20T23:14:37.400828Z","iopub.status.idle":"2025-11-20T23:14:37.428697Z","shell.execute_reply.started":"2025-11-20T23:14:37.400805Z","shell.execute_reply":"2025-11-20T23:14:37.428121Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"all_preds = np.zeros((len(test_df), NUM_CLASSES), dtype=np.float32)\n\nfor fold in range(N_FOLDS):\n    print(f\"Loading model for fold {fold}...\")\n    \n    model = build_model().to(DEVICE)\n    model_path = os.path.join(MODELS_DIR, f\"best_model_fold{fold}.pth\")\n    state = torch.load(model_path, map_location=DEVICE)\n    model.load_state_dict(state)\n    model.eval()\n\n    fold_preds = []\n\n    with torch.no_grad():\n        for images, image_ids in test_loader:\n            images = images.to(DEVICE)\n            outputs = model(images)\n            probs = torch.softmax(outputs, dim=1)\n            fold_preds.append(probs.cpu().numpy())\n\n    fold_preds = np.concatenate(fold_preds, axis=0)\n    all_preds += fold_preds / N_FOLDS \n\npred_labels = all_preds.argmax(axis=1)\nsub_df[\"label\"] = pred_labels\nsub_df.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-20T23:14:56.046422Z","iopub.execute_input":"2025-11-20T23:14:56.047022Z","iopub.status.idle":"2025-11-20T23:15:04.031519Z","shell.execute_reply.started":"2025-11-20T23:14:56.046974Z","shell.execute_reply":"2025-11-20T23:15:04.030789Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sub_df.to_csv(\"submission.csv\", index=False)\nprint(\"submission.csv saved!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-20T23:15:13.235909Z","iopub.execute_input":"2025-11-20T23:15:13.236289Z","iopub.status.idle":"2025-11-20T23:15:13.248717Z","shell.execute_reply.started":"2025-11-20T23:15:13.236259Z","shell.execute_reply":"2025-11-20T23:15:13.247761Z"}},"outputs":[],"execution_count":null}]}