{"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":13836,"databundleVersionId":1718836,"sourceType":"competition"},{"sourceId":151268,"sourceType":"modelInstanceVersion","modelInstanceId":128445,"modelId":151320},{"sourceId":152105,"sourceType":"modelInstanceVersion","isSourceIdPinned":true,"modelInstanceId":129178,"modelId":152041},{"sourceId":152465,"sourceType":"modelInstanceVersion","isSourceIdPinned":true,"modelInstanceId":129489,"modelId":152347}],"dockerImageVersionId":30787,"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","execution":{"iopub.status.busy":"2024-10-30T11:26:52.336202Z","iopub.execute_input":"2024-10-30T11:26:52.336803Z","iopub.status.idle":"2024-10-30T11:27:21.218811Z","shell.execute_reply.started":"2024-10-30T11:26:52.336767Z","shell.execute_reply":"2024-10-30T11:27:21.217857Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torchvision import models, transforms\nfrom torch.utils.data import Dataset, DataLoader\nfrom sklearn.model_selection import train_test_split\nfrom PIL import Image\nimport pandas as pd\nimport os\nfrom tqdm import tqdm\nimport copy","metadata":{"execution":{"iopub.status.busy":"2024-10-30T11:27:21.220723Z","iopub.execute_input":"2024-10-30T11:27:21.221128Z","iopub.status.idle":"2024-10-30T11:27:26.176202Z","shell.execute_reply.started":"2024-10-30T11:27:21.221094Z","shell.execute_reply":"2024-10-30T11:27:26.175424Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_image_dir = \"/kaggle/input/cassava-leaf-disease-classification/test_images\"","metadata":{"execution":{"iopub.status.busy":"2024-10-30T11:27:26.177260Z","iopub.execute_input":"2024-10-30T11:27:26.177668Z","iopub.status.idle":"2024-10-30T11:27:26.181906Z","shell.execute_reply.started":"2024-10-30T11:27:26.177635Z","shell.execute_reply":"2024-10-30T11:27:26.181033Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df = pd.read_csv('../input/cassava-leaf-disease-classification/sample_submission.csv')\ntest_df.head()","metadata":{"execution":{"iopub.status.busy":"2024-10-30T11:27:26.183980Z","iopub.execute_input":"2024-10-30T11:27:26.184264Z","iopub.status.idle":"2024-10-30T11:27:26.220898Z","shell.execute_reply.started":"2024-10-30T11:27:26.184233Z","shell.execute_reply":"2024-10-30T11:27:26.219948Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class TestDataset(Dataset):\n    def __init__(self, dataframe, image_dir, transform=None):\n        self.dataframe = dataframe\n        self.image_dir = image_dir\n        self.transform = transform\n    \n    def __len__(self):\n        return len(self.dataframe)\n    \n    def __getitem__(self, idx):\n        # Get image file name (ID) from the dataframe\n        img_name = self.dataframe.iloc[idx, 0]  # Image ID\n        img_path = os.path.join(self.image_dir, img_name)\n        image = Image.open(img_path).convert('RGB')\n        \n        if self.transform:\n            image = self.transform(image)\n        \n        return image, img_name","metadata":{"execution":{"iopub.status.busy":"2024-10-30T11:27:26.221985Z","iopub.execute_input":"2024-10-30T11:27:26.222363Z","iopub.status.idle":"2024-10-30T11:27:26.229354Z","shell.execute_reply.started":"2024-10-30T11:27:26.222326Z","shell.execute_reply":"2024-10-30T11:27:26.228427Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_transforms = transforms.Compose([\n    transforms.Resize(256),\n    transforms.CenterCrop(224),\n    transforms.ToTensor(),\n    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n])","metadata":{"execution":{"iopub.status.busy":"2024-10-30T11:27:26.230585Z","iopub.execute_input":"2024-10-30T11:27:26.231193Z","iopub.status.idle":"2024-10-30T11:27:26.239508Z","shell.execute_reply.started":"2024-10-30T11:27:26.231142Z","shell.execute_reply":"2024-10-30T11:27:26.238677Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_dataset = TestDataset(test_df, test_image_dir, transform=test_transforms)\ntest_loader = DataLoader(test_dataset, batch_size=32, shuffle=False, num_workers=4)","metadata":{"execution":{"iopub.status.busy":"2024-10-30T11:27:26.240799Z","iopub.execute_input":"2024-10-30T11:27:26.241387Z","iopub.status.idle":"2024-10-30T11:27:26.246734Z","shell.execute_reply.started":"2024-10-30T11:27:26.241339Z","shell.execute_reply":"2024-10-30T11:27:26.245772Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = models.resnet50(pretrained=False)\nnum_ftrs = model.fc.in_features\nmodel.fc = nn.Linear(num_ftrs, 5)\n\n# Load your trained model weights\nmodel.load_state_dict(torch.load(\"/kaggle/input/casava-aug/pytorch/default/1/cassava_leaf_best_model_fine_aug.pth\"))\nmodel = model.to('cuda' if torch.cuda.is_available() else 'cpu')\n\n# Set the model to evaluation mode\nmodel.eval()","metadata":{"execution":{"iopub.status.busy":"2024-10-30T11:27:26.247994Z","iopub.execute_input":"2024-10-30T11:27:26.248838Z","iopub.status.idle":"2024-10-30T11:27:27.958188Z","shell.execute_reply.started":"2024-10-30T11:27:26.248794Z","shell.execute_reply":"2024-10-30T11:27:27.957048Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = []\nimage_ids = []\n\nwith torch.no_grad():\n    for images, img_names in tqdm(test_loader):\n        images = images.to('cuda' if torch.cuda.is_available() else 'cpu')\n        \n        # Get predictions from the model\n        outputs = model(images)\n        _, preds = torch.max(outputs, 1)  # Get the index of the max log-probability (predicted label)\n        \n        # Collect predictions and image IDs\n        predictions.extend(preds.cpu().numpy())  # Move predictions to CPU and convert to numpy\n        image_ids.extend(img_names)\n\n# Ensure predictions and image_ids have the same length\nassert len(predictions) == len(image_ids)","metadata":{"execution":{"iopub.status.busy":"2024-10-30T11:27:27.959483Z","iopub.execute_input":"2024-10-30T11:27:27.959869Z","iopub.status.idle":"2024-10-30T11:27:28.878771Z","shell.execute_reply.started":"2024-10-30T11:27:27.959827Z","shell.execute_reply":"2024-10-30T11:27:28.877648Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df = pd.DataFrame({\n    'image_id': image_ids,         # Image IDs from the test set\n    'label': predictions     # Predicted labels for each image\n})\n\n# Save the DataFrame as a CSV file without the index\nsubmission_df.to_csv('submission.csv', index=False)\n\nprint(\"Submission file saved as 'submission.csv'\")","metadata":{"execution":{"iopub.status.busy":"2024-10-30T11:27:28.882285Z","iopub.execute_input":"2024-10-30T11:27:28.882605Z","iopub.status.idle":"2024-10-30T11:27:28.893648Z","shell.execute_reply.started":"2024-10-30T11:27:28.882570Z","shell.execute_reply":"2024-10-30T11:27:28.892678Z"},"trusted":true},"execution_count":null,"outputs":[]}]}