{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.13.15","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[],"dockerImageVersionId":28755,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Inference with my own trained weights: ResNeXt50 + label smoothing (384 px, no TTA)\n\nThis notebook predicts the test images with **one model that I trained myself**: ResNeXt50, fold 0, 384 px, 8 epochs, trained with label smoothing 0.1 (Modification A). It does not use any of the winners' released weights.\n\n**Result:** Private score **0.8779** and Public score **0.8792**. The validation accuracy of the same weights on fold 0 was 0.87986.\n\n| Weights | Validation | Private LB | Public LB |\n|---|---|---|---|\n| Baseline (`inference-own-resnext-384`) | 0.87388 | 0.8742 | 0.8706 |\n| **Label smoothing (this notebook)** | **0.87986** | **0.8779** | **0.8792** |\n\nLabel smoothing was better than the baseline on validation and on both leaderboard splits. This is a single run on one fold, so I treat it as an observation and not as proof.\n\n**Code:** Identical to `inference-own-resnext-384`, which explains it step by step. The only difference is the attached weights dataset (`cassava-resnext-fold0-384-labelsmooth`) and the path to its `.pth` file. There is no test-time augmentation here. Images are resized to 384 x 384, normalised, and the class with the highest probability is submitted.\n\n**Related notebooks:**\n* Training notebook for these weights: https://www.kaggle.com/code/ananyaamadhursharma/train-label-smoothing-384\n* Baseline weights inference: https://www.kaggle.com/code/ananyaamadhursharma/inference-own-resnext-384\n* Same weights with flip TTA: `inference-own-resnext-384-labelsmooth-tta` on my profile\n* Full winning ensemble: https://www.kaggle.com/code/ananyaamadhursharma/final-version-inference","metadata":{}},{"cell_type":"code","source":"import os\n\nprint(\"Input folders:\", os.listdir(\"/kaggle/input\"))\nprint()\nfor root, dirs, files in os.walk(\"/kaggle/input\"):\n    for f in files:\n        if f.endswith(\".pth\"):\n            print(\"WEIGHTS:\", os.path.join(root, f))","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-10-14T18:30:23.249979Z","iopub.execute_input":"2026-10-14T18:30:23.250296Z","iopub.status.idle":"2026-10-14T18:31:05.425705Z","shell.execute_reply.started":"2026-10-14T18:30:23.250258Z","shell.execute_reply":"2026-10-14T18:31:05.424901Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ====================================================\n# Inference with my own trained ResNeXt50 (fold 0, 384 px)\n# ====================================================\nimport os, sys\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader, Dataset\nfrom albumentations import Compose, Normalize, Resize\nfrom albumentations.pytorch import ToTensorV2\n\n# timm is normally preinstalled on Kaggle; these paths are a fallback\nsys.path.append('../input/pytorch-image-models/pytorch-image-models-master')\nimport timm\n\n# ---------------- settings ----------------\nWEIGHTS_PATH = \"/kaggle/input/datasets/ananyaamadhursharma/cassava-resnext-fold0-384-labelsmooth/resnext50_32x4d_fold0_best.pth\"\nSIZE = 384      # must match the training image size\n\n# find the competition test folder (the paths differ between setups)\ncandidates = [\n    \"../input/cassava-leaf-disease-classification/test_images/\",\n    \"/kaggle/input/cassava-leaf-disease-classification/test_images/\",\n    \"/kaggle/input/competitions/cassava-leaf-disease-classification/test_images/\",\n]\nTEST_DIR = next(p for p in candidates if os.path.exists(p))\nprint(\"Using test folder:\", TEST_DIR)\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nprint(\"Device:\", device)\n\n# ---------------- model (same structure as training) ----------------\nclass CustomResNext(nn.Module):\n    def __init__(self, model_name='resnext50_32x4d', pretrained=False):\n        super().__init__()\n        self.model = timm.create_model(model_name, pretrained=pretrained)\n        n_features = self.model.fc.in_features\n        self.model.fc = nn.Linear(n_features, 5)\n\n    def forward(self, x):\n        return self.model(x)\n\n# ---------------- dataset ----------------\nclass TestDataset(Dataset):\n    def __init__(self, files, transform=None):\n        self.files = files\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.files)\n\n    def __getitem__(self, idx):\n        image = cv2.imread(self.files[idx])\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n        return self.transform(image=image)['image']\n\n# same transform as validation in training: Resize + Normalize\ntransform = Compose([\n    Resize(SIZE, SIZE),\n    Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n    ToTensorV2(),\n])\n\n# ---------------- load my trained weights ----------------\nmodel = CustomResNext(pretrained=False)\nstate = torch.load(WEIGHTS_PATH, map_location=\"cpu\", weights_only=False)\nmodel.load_state_dict(state['model'])\nmodel.to(device)\nmodel.eval()\nprint(\"My trained weights loaded.\")\n\n# ---------------- predict ----------------\nimage_ids = sorted(os.listdir(TEST_DIR))\nfiles = [TEST_DIR + i for i in image_ids]\nloader = DataLoader(TestDataset(files, transform), batch_size=16,\n                    shuffle=False, num_workers=2, pin_memory=True)\n\nprobs = []\nwith torch.no_grad():\n    for images in loader:\n        out = model(images.to(device))\n        probs.append(out.softmax(1).cpu().numpy())\nprobs = np.concatenate(probs)\n\n# ---------------- save submission ----------------\nsubmission = pd.DataFrame({\"image_id\": image_ids, \"label\": probs.argmax(1)})\nsubmission.to_csv(\"submission.csv\", index=False)\nprint(submission.head())\nprint(\"Rows:\", len(submission))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-14T18:31:13.580673Z","iopub.execute_input":"2026-10-14T18:31:13.580997Z","iopub.status.idle":"2026-10-14T18:32:02.924128Z","shell.execute_reply.started":"2026-10-14T18:31:13.580964Z","shell.execute_reply":"2026-10-14T18:32:02.923099Z"}},"outputs":[],"execution_count":null}]}