{"metadata":{"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":3649,"databundleVersionId":46718,"sourceType":"competition"}],"dockerImageVersionId":30776,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true},"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.10.14"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms\nfrom torch.utils.data import DataLoader\n","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.status.busy":"2024-10-02T07:22:50.703482Z","iopub.execute_input":"2024-10-02T07:22:50.703867Z","iopub.status.idle":"2024-10-02T07:22:55.205914Z","shell.execute_reply.started":"2024-10-02T07:22:50.703829Z","shell.execute_reply":"2024-10-02T07:22:55.205061Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Bottleneck(nn.Module):\n    expansion = 4\n\n    def __init__(self, in_planes, planes, stride=1):\n        super(Bottleneck, self).__init__()\n        self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)\n        self.bn1 = nn.BatchNorm2d(planes)\n        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)\n        self.bn2 = nn.BatchNorm2d(planes)\n        self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1, bias=False)\n        self.bn3 = nn.BatchNorm2d(planes * self.expansion)\n\n        self.shortcut = nn.Sequential()\n        if stride != 1 or in_planes != planes * self.expansion:\n            self.shortcut = nn.Sequential(\n                nn.Conv2d(in_planes, planes * self.expansion, kernel_size=1, stride=stride, bias=False),\n                nn.BatchNorm2d(planes * self.expansion)\n            )\n\n    def forward(self, x):\n        out = F.relu(self.bn1(self.conv1(x)))\n        out = F.relu(self.bn2(self.conv2(out)))\n        out = self.bn3(self.conv3(out))\n        out += self.shortcut(x)\n        out = F.relu(out)\n        return out\n","metadata":{"execution":{"iopub.status.busy":"2024-10-02T07:22:59.733500Z","iopub.execute_input":"2024-10-02T07:22:59.733956Z","iopub.status.idle":"2024-10-02T07:22:59.743788Z","shell.execute_reply.started":"2024-10-02T07:22:59.733922Z","shell.execute_reply":"2024-10-02T07:22:59.742806Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class ResNet(nn.Module):\n    def __init__(self, block, num_blocks, num_classes=10):\n        super(ResNet, self).__init__()\n        self.in_planes = 64\n\n        # Stem layer\n        self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)\n        self.bn1 = nn.BatchNorm2d(64)\n\n        # ResNet layers\n        self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)\n        self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)\n        self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)\n        self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)\n\n        # Final classifier layer\n        self.linear = nn.Linear(512 * block.expansion, num_classes)\n\n    def _make_layer(self, block, planes, num_blocks, stride):\n        strides = [stride] + [1] * (num_blocks - 1)\n        layers = []\n        for stride in strides:\n            layers.append(block(self.in_planes, planes, stride))\n            self.in_planes = planes * block.expansion\n        return nn.Sequential(*layers)\n\n    def forward(self, x):\n        out = F.relu(self.bn1(self.conv1(x)))\n        out = self.layer1(out)\n        out = self.layer2(out)\n        out = self.layer3(out)\n        out = self.layer4(out)\n        out = F.avg_pool2d(out, 4)\n        out = out.view(out.size(0), -1)\n        out = self.linear(out)\n        return out\n","metadata":{"execution":{"iopub.status.busy":"2024-10-02T07:23:03.545060Z","iopub.execute_input":"2024-10-02T07:23:03.545922Z","iopub.status.idle":"2024-10-02T07:23:03.556941Z","shell.execute_reply.started":"2024-10-02T07:23:03.545879Z","shell.execute_reply":"2024-10-02T07:23:03.555945Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def ResNet152():\n    return ResNet(Bottleneck, [3, 8, 36, 3])\n\nmodel = ResNet152()\n","metadata":{"execution":{"iopub.status.busy":"2024-10-02T07:23:08.314934Z","iopub.execute_input":"2024-10-02T07:23:08.315300Z","iopub.status.idle":"2024-10-02T07:23:08.873698Z","shell.execute_reply.started":"2024-10-02T07:23:08.315265Z","shell.execute_reply":"2024-10-02T07:23:08.872683Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# CIFAR-10 data loading and preprocessing\ntransform = transforms.Compose([\n    transforms.RandomCrop(32, padding=4),\n    transforms.RandomHorizontalFlip(),\n    transforms.ToTensor(),\n    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n])\n\ntrainset = datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)\ntrainloader = DataLoader(trainset, batch_size=128, shuffle=True, num_workers=2)\n\ntestset = datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)\ntestloader = DataLoader(testset, batch_size=100, shuffle=False, num_workers=2)\n","metadata":{"execution":{"iopub.status.busy":"2024-10-02T07:23:13.105145Z","iopub.execute_input":"2024-10-02T07:23:13.105880Z","iopub.status.idle":"2024-10-02T07:23:22.647872Z","shell.execute_reply.started":"2024-10-02T07:23:13.105841Z","shell.execute_reply":"2024-10-02T07:23:22.646869Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"criterion = nn.CrossEntropyLoss()\noptimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=5e-4)\n\n# Scheduler for learning rate decay\nscheduler = optim.lr_scheduler.StepLR(optimizer, step_size=30, gamma=0.1)\n","metadata":{"execution":{"iopub.status.busy":"2024-10-02T07:23:43.621268Z","iopub.execute_input":"2024-10-02T07:23:43.622127Z","iopub.status.idle":"2024-10-02T07:23:43.629700Z","shell.execute_reply.started":"2024-10-02T07:23:43.622083Z","shell.execute_reply":"2024-10-02T07:23:43.628616Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel.to(device)\n\ndef train(epoch):\n    model.train()\n    running_loss = 0.0\n    for batch_idx, (inputs, targets) in enumerate(trainloader):\n        inputs, targets = inputs.to(device), targets.to(device)\n        optimizer.zero_grad()\n        outputs = model(inputs)\n        loss = criterion(outputs, targets)\n        loss.backward()\n        optimizer.step()\n        \n        running_loss += loss.item()\n        if batch_idx % 100 == 99:    # print every 100 mini-batches\n            print(f'[Epoch {epoch + 1}, Batch {batch_idx + 1}] loss: {running_loss / 100:.3f}')\n            running_loss = 0.0\n\ndef test():\n    model.eval()\n    correct = 0\n    total = 0\n    with torch.no_grad():\n        for inputs, targets in testloader:\n            inputs, targets = inputs.to(device), targets.to(device)\n            outputs = model(inputs)\n            _, predicted = outputs.max(1)\n            total += targets.size(0)\n            correct += predicted.eq(targets).sum().item()\n    \n    print(f'Accuracy of the network on the test images: {100 * correct / total:.2f}%')\n","metadata":{"execution":{"iopub.status.busy":"2024-10-02T07:23:45.937704Z","iopub.execute_input":"2024-10-02T07:23:45.938112Z","iopub.status.idle":"2024-10-02T07:23:46.244662Z","shell.execute_reply.started":"2024-10-02T07:23:45.938074Z","shell.execute_reply":"2024-10-02T07:23:46.243718Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for epoch in range(60):  # 100 epochs for training\n    train(epoch)\n    test()\n    scheduler.step()  # Adjust learning rate\ntorch.save(model.state_dict(), 'resnet152_cifar10_weights.pt')\nprint(\"Model weights saved successfully.\")\n    \n","metadata":{"execution":{"iopub.status.busy":"2024-10-02T07:23:50.401767Z","iopub.execute_input":"2024-10-02T07:23:50.402124Z","iopub.status.idle":"2024-10-02T10:49:37.767719Z","shell.execute_reply.started":"2024-10-02T07:23:50.402092Z","shell.execute_reply":"2024-10-02T10:49:37.766575Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\n# Fine-tuning strategies\n# Using a learning rate scheduler for fine-tuning\nscheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.1)\n\n# Training loop (fine-tuning included)\nnum_epochs = 15  # Increase the number of epochs for better results\nfor epoch in range(num_epochs):\n    model.train()\n    running_loss = 0.0\n    for inputs, targets in trainloader:\n        inputs, targets = inputs.to(device), targets.to(device)\n        optimizer.zero_grad()\n        outputs = model(inputs)\n        loss = criterion(outputs, targets)\n        loss.backward()\n        optimizer.step()\n        running_loss += loss.item()\n\n    # Scheduler step after each epoch\n    scheduler.step()\n\n    # Print training progress\n    print(f\"Epoch {epoch+1}/{num_epochs}, Loss: {running_loss/len(trainloader)}\")\n\nprint(\"Training and fine-tuning completed.\")","metadata":{"execution":{"iopub.status.busy":"2024-10-02T10:56:09.154345Z","iopub.execute_input":"2024-10-02T10:56:09.154800Z","iopub.status.idle":"2024-10-02T11:44:27.382922Z","shell.execute_reply.started":"2024-10-02T10:56:09.154751Z","shell.execute_reply":"2024-10-02T11:44:27.381865Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Save model weights after training\ntorch.save(model.state_dict(), 'resnet152_cifar10_weights_best.pt')\nprint(\"Model weights saved successfully.\")","metadata":{"execution":{"iopub.status.busy":"2024-10-02T11:45:11.946404Z","iopub.execute_input":"2024-10-02T11:45:11.946803Z","iopub.status.idle":"2024-10-02T11:45:12.355893Z","shell.execute_reply.started":"2024-10-02T11:45:11.946758Z","shell.execute_reply":"2024-10-02T11:45:12.354983Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install  py7zr\n# Required Imports\nimport py7zr\nimport os\nfrom tqdm import tqdm\nimport pandas as pd\nfrom PIL import Image\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nimport torchvision.transforms as transforms\n\n# Decompressing data\nwith py7zr.SevenZipFile('/kaggle/input/cifar-10/test.7z', mode='r') as z:\n    z.extractall('/kaggle/working/')\n\n# Sorting filenames and extracting IDs from filenames\ntest_filenames = [os.path.join('/kaggle/working/test', f) for f in os.listdir('/kaggle/working/test')]\ntest_filenames.sort(key=lambda x: int(x.split('/')[-1].split('.')[0]))","metadata":{"execution":{"iopub.status.busy":"2024-10-02T11:45:34.245558Z","iopub.execute_input":"2024-10-02T11:45:34.246305Z","iopub.status.idle":"2024-10-02T11:48:16.631660Z","shell.execute_reply.started":"2024-10-02T11:45:34.246266Z","shell.execute_reply":"2024-10-02T11:48:16.630796Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nfrom torchvision import transforms\nfrom torch.utils.data import DataLoader, Dataset\nfrom PIL import Image\nimport os\nimport pandas as pd\nfrom tqdm import tqdm\n\n# Custom CIFAR-10 Test Dataset class\nclass CIFAR10TestDataset(Dataset):\n    def __init__(self, filenames, transform=None):\n        self.filenames = filenames\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.filenames)\n\n    def __getitem__(self, idx):\n        img_path = self.filenames[idx]\n        img = Image.open(img_path)\n        \n        if self.transform:\n            img = self.transform(img)\n        \n        img_id = int(os.path.basename(img_path).split('.')[0])  # Extract image ID from filename\n        return img, img_id\n\n# Define the test transforms (for inference)\ntest_transforms = transforms.Compose([\n    transforms.Resize((32, 32)),  # CIFAR-10 images are 32x32\n    transforms.ToTensor(),\n    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n])\n\n# Test directory containing images\ntest_dir = '/kaggle/working/test'  # Change this path based on your dataset location\ntest_filenames = [os.path.join(test_dir, f) for f in os.listdir(test_dir)]\ntest_filenames.sort(key=lambda x: int(os.path.basename(x).split('.')[0]))  # Sort by image ID\n\ntest_dataset = CIFAR10TestDataset(test_filenames, transform=test_transforms)\ntest_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)\n\n# CIFAR-10 classes\nclasses = ['airplane', 'automobile', 'bird', 'cat', 'deer', \n           'dog', 'frog', 'horse', 'ship', 'truck']\n\n# Define the ResNet152 architecture (as per your provided code)\nclass Bottleneck(nn.Module):\n    expansion = 4\n    def __init__(self, in_planes, planes, stride=1):\n        super(Bottleneck, self).__init__()\n        self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)\n        self.bn1 = nn.BatchNorm2d(planes)\n        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)\n        self.bn2 = nn.BatchNorm2d(planes)\n        self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1, bias=False)\n        self.bn3 = nn.BatchNorm2d(planes * self.expansion)\n\n        self.shortcut = nn.Sequential()\n        if stride != 1 or in_planes != planes * self.expansion:\n            self.shortcut = nn.Sequential(\n                nn.Conv2d(in_planes, planes * self.expansion, kernel_size=1, stride=stride, bias=False),\n                nn.BatchNorm2d(planes * self.expansion)\n            )\n\n    def forward(self, x):\n        out = F.relu(self.bn1(self.conv1(x)))\n        out = F.relu(self.bn2(self.conv2(out)))\n        out = self.bn3(self.conv3(out))\n        out += self.shortcut(x)\n        out = F.relu(out)\n        return out\n\nclass ResNet(nn.Module):\n    def __init__(self, block, num_blocks, num_classes=10):\n        super(ResNet, self).__init__()\n        self.in_planes = 64\n\n        # Stem layer\n        self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)\n        self.bn1 = nn.BatchNorm2d(64)\n\n        # ResNet layers\n        self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)\n        self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)\n        self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)\n        self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)\n\n        # Final classifier layer\n        self.linear = nn.Linear(512 * block.expansion, num_classes)\n\n    def _make_layer(self, block, planes, num_blocks, stride):\n        strides = [stride] + [1] * (num_blocks - 1)\n        layers = []\n        for stride in strides:\n            layers.append(block(self.in_planes, planes, stride))\n            self.in_planes = planes * block.expansion\n        return nn.Sequential(*layers)\n\n    def forward(self, x):\n        out = F.relu(self.bn1(self.conv1(x)))\n        out = self.layer1(out)\n        out = self.layer2(out)\n        out = self.layer3(out)\n        out = self.layer4(out)\n        out = F.avg_pool2d(out, 4)\n        out = out.view(out.size(0), -1)\n        out = self.linear(out)\n        return out\n\ndef ResNet152():\n    return ResNet(Bottleneck, [3, 8, 36, 3])\n\n# Load model\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel = ResNet152().to(device)\nmodel.load_state_dict(torch.load('/kaggle/working/resnet152_cifar10_weights_best.pt'))  # Adjust path if needed\nmodel.eval()\n\n# Perform inference on test set\npredictions = []\nwith torch.no_grad():\n    for imgs, img_ids in tqdm(test_loader):\n        imgs = imgs.to(device)\n        outputs = model(imgs)\n        _, preds = torch.max(outputs, 1)\n        preds = preds.cpu().numpy()\n        for img_id, pred in zip(img_ids, preds):\n            predictions.append((img_id, classes[pred]))\n\n# Save predictions to a CSV file\nsubmission_df = pd.DataFrame(predictions, columns=['id', 'label'])\nsubmission_df.to_csv('resnet152_cifar10_predictions.csv', index=False)\n\nprint(\"Predictions saved to resnet152_cifar10_predictions.csv\")\n","metadata":{"execution":{"iopub.status.busy":"2024-10-02T11:49:06.658579Z","iopub.execute_input":"2024-10-02T11:49:06.659521Z","iopub.status.idle":"2024-10-02T11:58:25.649181Z","shell.execute_reply.started":"2024-10-02T11:49:06.659481Z","shell.execute_reply":"2024-10-02T11:58:25.648244Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nfrom torchvision import transforms\nfrom torch.utils.data import DataLoader, Dataset\nfrom PIL import Image\nimport os\nimport pandas as pd\nfrom tqdm import tqdm\n\n# Custom CIFAR-10 Test Dataset class\nclass CIFAR10TestDataset(Dataset):\n    def __init__(self, filenames, transform=None):\n        self.filenames = filenames\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.filenames)\n\n    def __getitem__(self, idx):\n        img_path = self.filenames[idx]\n        img = Image.open(img_path)\n        \n        if self.transform:\n            img = self.transform(img)\n        \n        img_id = int(os.path.basename(img_path).split('.')[0])  # Extract image ID from filename as integer\n        return img, img_id\n\n# Define the test transforms (for inference)\ntest_transforms = transforms.Compose([\n    transforms.Resize((32, 32)),  # CIFAR-10 images are 32x32\n    transforms.ToTensor(),\n    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n])\n\n# Test directory containing images\ntest_dir = '/kaggle/working/test'  # Change this path based on your dataset location\ntest_filenames = [os.path.join(test_dir, f) for f in os.listdir(test_dir)]\ntest_filenames.sort(key=lambda x: int(os.path.basename(x).split('.')[0]))  # Sort by image ID\n\ntest_dataset = CIFAR10TestDataset(test_filenames, transform=test_transforms)\ntest_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)\n\n# CIFAR-10 classes\nclasses = ['airplane', 'automobile', 'bird', 'cat', 'deer', \n           'dog', 'frog', 'horse', 'ship', 'truck']\n\n# Define the ResNet152 architecture\nclass Bottleneck(nn.Module):\n    expansion = 4\n    def __init__(self, in_planes, planes, stride=1):\n        super(Bottleneck, self).__init__()\n        self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)\n        self.bn1 = nn.BatchNorm2d(planes)\n        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)\n        self.bn2 = nn.BatchNorm2d(planes)\n        self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1, bias=False)\n        self.bn3 = nn.BatchNorm2d(planes * self.expansion)\n\n        self.shortcut = nn.Sequential()\n        if stride != 1 or in_planes != planes * self.expansion:\n            self.shortcut = nn.Sequential(\n                nn.Conv2d(in_planes, planes * self.expansion, kernel_size=1, stride=stride, bias=False),\n                nn.BatchNorm2d(planes * self.expansion)\n            )\n\n    def forward(self, x):\n        out = F.relu(self.bn1(self.conv1(x)))\n        out = F.relu(self.bn2(self.conv2(out)))\n        out = self.bn3(self.conv3(out))\n        out += self.shortcut(x)\n        out = F.relu(out)\n        return out\n\nclass ResNet(nn.Module):\n    def __init__(self, block, num_blocks, num_classes=10):\n        super(ResNet, self).__init__()\n        self.in_planes = 64\n\n        # Stem layer\n        self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)\n        self.bn1 = nn.BatchNorm2d(64)\n\n        # ResNet layers\n        self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)\n        self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)\n        self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)\n        self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)\n\n        # Final classifier layer\n        self.linear = nn.Linear(512 * block.expansion, num_classes)\n\n    def _make_layer(self, block, planes, num_blocks, stride):\n        strides = [stride] + [1] * (num_blocks - 1)\n        layers = []\n        for stride in strides:\n            layers.append(block(self.in_planes, planes, stride))\n            self.in_planes = planes * block.expansion\n        return nn.Sequential(*layers)\n\n    def forward(self, x):\n        out = F.relu(self.bn1(self.conv1(x)))\n        out = self.layer1(out)\n        out = self.layer2(out)\n        out = self.layer3(out)\n        out = self.layer4(out)\n        out = F.avg_pool2d(out, 4)\n        out = out.view(out.size(0), -1)\n        out = self.linear(out)\n        return out\n\ndef ResNet152():\n    return ResNet(Bottleneck, [3, 8, 36, 3])\n\n# Load model\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel = ResNet152().to(device)\nmodel.load_state_dict(torch.load('/kaggle/working/resnet152_cifar10_weights_best.pt'))  # Adjust path if needed\nmodel.eval()\n\n# Perform inference on test set\npredictions = []\nwith torch.no_grad():\n    for imgs, img_ids in tqdm(test_loader):\n        imgs = imgs.to(device)\n        outputs = model(imgs)\n        _, preds = torch.max(outputs, 1)\n        preds = preds.cpu().numpy()\n        for img_id, pred in zip(img_ids, preds):\n            predictions.append((int(img_id), classes[pred]))  # Ensure img_id is an integer\n\n# Save predictions to a CSV file for Kaggle submission\nsubmission_df = pd.DataFrame(predictions, columns=['id', 'label'])\n\n# Now we will clean the \"id\" column by removing the \"tensor()\" part and keeping only the numeric value\nsubmission_df['id'] = submission_df['id'].astype(int)  # Ensure 'id' is integer\n\n# Save the cleaned dataframe\nsubmission_df.to_csv('resnet152_cifar10_predictionsup.csv', index=False)\n\nprint(\"Predictions saved to resnet152_cifar10_predictions.csv\")\n","metadata":{"execution":{"iopub.status.busy":"2024-10-02T12:53:20.108674Z","iopub.execute_input":"2024-10-02T12:53:20.109067Z","iopub.status.idle":"2024-10-02T13:02:25.143303Z","shell.execute_reply.started":"2024-10-02T12:53:20.109032Z","shell.execute_reply":"2024-10-02T13:02:25.142334Z"},"trusted":true},"execution_count":null,"outputs":[]}]}