{"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":"gpu","dataSources":[{"sourceId":13836,"databundleVersionId":1718836,"sourceType":"competition"},{"sourceId":149624,"sourceType":"modelInstanceVersion","modelInstanceId":127014,"modelId":149959}],"dockerImageVersionId":30786,"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\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\". This means it gets stored in the history view, but not for the next execution\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-29T00:12:40.692486Z","iopub.execute_input":"2024-10-29T00:12:40.693421Z","iopub.status.idle":"2024-10-29T00:12:40.698196Z","shell.execute_reply.started":"2024-10-29T00:12:40.693370Z","shell.execute_reply":"2024-10-29T00:12:40.697241Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport pandas as pd\nfrom PIL import Image\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms\nimport matplotlib.pyplot as plt\nfrom torch.utils.data import DataLoader\n\n\n","metadata":{"execution":{"iopub.status.busy":"2024-10-29T00:12:40.699985Z","iopub.execute_input":"2024-10-29T00:12:40.700654Z","iopub.status.idle":"2024-10-29T00:12:40.714884Z","shell.execute_reply.started":"2024-10-29T00:12:40.700605Z","shell.execute_reply":"2024-10-29T00:12:40.713785Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = (\n    \"cuda\"\n    if torch.cuda.is_available()\n    else \"mps\"\n    if torch.backends.mps.is_available()\n    else \"cpu\"\n)\nprint(f\"Using {device} device\")","metadata":{"execution":{"iopub.status.busy":"2024-10-29T00:12:40.717065Z","iopub.execute_input":"2024-10-29T00:12:40.717391Z","iopub.status.idle":"2024-10-29T00:12:40.725598Z","shell.execute_reply.started":"2024-10-29T00:12:40.717358Z","shell.execute_reply":"2024-10-29T00:12:40.724682Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Dataset Class\n\nclass CassavaDataset(Dataset):\n    def __init__(self, csv_file, img_dir, transform=None):\n        self.labels_df = pd.read_csv(csv_file)\n        self.img_dir = img_dir\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.labels_df)\n\n    def __getitem__(self, idx):\n        # Get image path and append name found in csv\n        img_name = os.path.join(self.img_dir, self.labels_df.iloc[idx, 0])\n        image = Image.open(img_name)\n        # Get label from csv\n        label = self.labels_df.iloc[idx, 1]\n\n        if self.transform:\n            image = self.transform(image)\n        return image, label\n\n(image_height, image_width) = 128, 128\n\ntransform = transforms.Compose([\n    transforms.Resize((image_height, image_width)),  # Resize all images to 600*800 (does not changne anything)\n    transforms.ToTensor(),  # Convert the image to a tensor (H x W x C) -> (C x H x W)\n    transforms.Normalize(mean=[0.485, 0.456, 0.406],  # Normalization values for pre-trained models\n                         std=[0.229, 0.224, 0.225])\n])","metadata":{"execution":{"iopub.status.busy":"2024-10-29T00:12:40.726554Z","iopub.execute_input":"2024-10-29T00:12:40.726869Z","iopub.status.idle":"2024-10-29T00:12:40.736218Z","shell.execute_reply.started":"2024-10-29T00:12:40.726836Z","shell.execute_reply":"2024-10-29T00:12:40.735249Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"(image_height, image_width) = 128, 128\n\n\n# 2. Model:\n\nclass SimpleNet(nn.Module):\n    def __init__(self, num_classes=5):\n        super(SimpleNet, self).__init__()\n        self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, stride=1, padding=1)  # 1st layer\n        self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1)  # 2nd layer\n        self.conv3 = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1)  # 3rd layer\n        self.pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)  # Pooling layer\n        # The amount of times that may pooling is performed has an imact on the size of the feature maps.\n        # Hence, the size of the dense layers is dependent on the original image size and amount of times max-pooling is applied\n        self.fc1 = nn.Linear(128 * image_height//pow(2, 3) * image_width//pow(2, 3), 256)  # Fully connected layer\n        self.fc2 = nn.Linear(256, num_classes)  # Output layer\n\n    def forward(self, x):\n        x = self.pool(F.relu(self.conv1(x)))  # Output: (batch_size, 32, 300, 400)\n        x = self.pool(F.relu(self.conv2(x)))  # Output: (batch_size, 64, 150, 200)\n        x = self.pool(F.relu(self.conv3(x)))  # Output: (batch_size, 128, 75, 100)\n        x = x.view(x.size(0), -1)  # Flatten while keeping batch size\n        x = F.relu(self.fc1(x))  # Fully connected layer\n        x = self.fc2(x)  # Output layer\n        return x\n        \nmyModel = SimpleNet(5).to(device)\n\ncriterion = nn.CrossEntropyLoss()\n\noptimizer = torch.optim.Adam(myModel.parameters(), lr=0.001)","metadata":{"execution":{"iopub.status.busy":"2024-10-29T00:12:40.738268Z","iopub.execute_input":"2024-10-29T00:12:40.738685Z","iopub.status.idle":"2024-10-29T00:12:40.831014Z","shell.execute_reply.started":"2024-10-29T00:12:40.738640Z","shell.execute_reply":"2024-10-29T00:12:40.830180Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\n\nis_training = os.getenv('KAGGLE_KERNEL_RUN_TYPE') == 'Interactive'\nif is_training:\n    print(\"Running in training mode.\")\nelse:\n    print(\"Running in testing/submission mode.\")\n","metadata":{"execution":{"iopub.status.busy":"2024-10-29T00:12:40.832252Z","iopub.execute_input":"2024-10-29T00:12:40.832625Z","iopub.status.idle":"2024-10-29T00:12:40.838504Z","shell.execute_reply.started":"2024-10-29T00:12:40.832581Z","shell.execute_reply":"2024-10-29T00:12:40.837456Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"myModel = SimpleNet(5).to(device)\n\nmyModel.load_state_dict(torch.load(\"/kaggle/input/my-trainde-cassave-model/pytorch/default/1/myModel.pt\", weights_only=False))\n\nmyModel.eval()\n\ntestImage = Image.open('/kaggle/input/cassava-leaf-disease-classification/test_images/2216849948.jpg')\ninput_tensor = transform(testImage)\ninput_batch = input_tensor.unsqueeze(0).to(device)\n\nprint(input_batch)\n\nwith torch.no_grad():\n    print(type(input_batch))\n    output = myModel(input_batch)\n\n_, predicted_class = torch.max(output, 1)\n\nprint(predicted_class.item())\n\n\n\n# 4. Predict on test data\ntest_df = pd.read_csv('../input/cassava-leaf-disease-classification/sample_submission.csv')\ntest_dataset = CassavaDataset(\"/kaggle/input/cassava-leaf-disease-classification/sample_submission.csv\", \"/kaggle/input/cassava-leaf-disease-classification/test_images\", transform=transform)\ntest_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n\n# myDataloader = DataLoader(myCassavaDataset, batch_size=32, shuffle=True, num_workers=4)\n\n# Predict on test data\npredictions = []\nwith torch.no_grad():  # Disable gradient computation for inference\n    for images, _ in test_loader:\n        images = images.to(device)\n        \n        outputs = myModel(images)  # Forward pass\n        _, preds = torch.max(outputs, 1)  # Get the predicted class\n        predictions.extend(preds.cpu().numpy())  # Store predictions\n\n# Convert predictions to a NumPy array\npredictions = np.array(predictions)\n\n\n\n\n# 5. Create submission file\ntest_df['label'] = predictions\ntest_df.to_csv('submission.csv', index=False)\nprint(\"Submission file created!\")","metadata":{"execution":{"iopub.status.busy":"2024-10-29T00:12:40.882058Z","iopub.execute_input":"2024-10-29T00:12:40.882360Z","iopub.status.idle":"2024-10-29T00:12:41.045862Z","shell.execute_reply.started":"2024-10-29T00:12:40.882326Z","shell.execute_reply":"2024-10-29T00:12:41.044923Z"},"trusted":true},"execution_count":null,"outputs":[]}]}