{"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":3649,"databundleVersionId":46718,"sourceType":"competition"},{"sourceId":140376581,"sourceType":"kernelVersion"}],"dockerImageVersionId":30787,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.utils.data import DataLoader\n\n# Define a basic Residual Block for the ResNet architecture\nclass ResidualBlock(nn.Module):\n    def __init__(self, in_channels, out_channels, stride=1):\n        super(ResidualBlock, self).__init__()\n        # First convolutional layer in the residual block\n        self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)\n        self.bn1 = nn.BatchNorm2d(out_channels)\n        # Second convolutional layer\n        self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False)\n        self.bn2 = nn.BatchNorm2d(out_channels)\n\n        # If the input and output dimensions are different, we need a 1x1 convolution to match dimensions\n        self.shortcut = nn.Sequential()\n        if stride != 1 or in_channels != out_channels:\n            self.shortcut = nn.Sequential(\n                nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False),\n                nn.BatchNorm2d(out_channels)\n            )\n\n    def forward(self, x):\n        out = F.relu(self.bn1(self.conv1(x)))\n        out = self.bn2(self.conv2(out))\n        out += self.shortcut(x)  # Residual connection\n        out = F.relu(out)\n        return out\n\n# Define the full ResNet model\nclass ResNet(nn.Module):\n    def __init__(self, block, num_blocks, num_classes=10):\n        super(ResNet, self).__init__()\n        self.in_channels = 64\n\n        # Initial convolutional 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 with residual blocks\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        # Fully connected layer for classification\n        self.fc = nn.Linear(512, num_classes)\n\n    def _make_layer(self, block, out_channels, num_blocks, stride):\n        strides = [stride] + [1] * (num_blocks - 1)\n        layers = []\n        for stride in strides:\n            layers.append(block(self.in_channels, out_channels, stride))\n            self.in_channels = out_channels\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)  # Flatten the output\n        out = self.fc(out)\n        return out\n\n# Define the ResNet18 model (with 2 residual blocks in each layer)\ndef ResNet18():\n    return ResNet(ResidualBlock, [2, 2, 2, 2])\n\n# Load CIFAR-10 dataset\ntransform = transforms.Compose([\n    transforms.RandomHorizontalFlip(),\n    transforms.RandomCrop(32, padding=4),\n    transforms.ToTensor(),\n    transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2470, 0.2435, 0.2616)),\n])\n\ntrainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)\ntrainloader = DataLoader(trainset, batch_size=128, shuffle=True, num_workers=2)\n\ntestset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)\ntestloader = DataLoader(testset, batch_size=100, shuffle=False, num_workers=2)\n\n# Initialize the ResNet model\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nmodel = ResNet18().to(device)\n\n# Loss function and optimizer\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters(), lr=0.001)\n\n# Training loop\ndef train(model, trainloader, criterion, optimizer, device, epochs=10):\n    model.train()\n    for epoch in range(epochs):\n        running_loss = 0.0\n        for i, (inputs, labels) in enumerate(trainloader):\n            inputs, labels = inputs.to(device), labels.to(device)\n            \n            # Zero the parameter gradients\n            optimizer.zero_grad()\n            \n            # Forward pass\n            outputs = model(inputs)\n            loss = criterion(outputs, labels)\n            \n            # Backward pass and optimize\n            loss.backward()\n            optimizer.step()\n\n            running_loss += loss.item()\n            if i % 100 == 99:  # Print every 100 mini-batches\n                print(f'Epoch [{epoch+1}/{epochs}], Step [{i+1}/{len(trainloader)}], Loss: {running_loss / 100:.4f}')\n                running_loss = 0.0\n\n# Evaluation function\ndef evaluate(model, testloader, device):\n    model.eval()\n    correct = 0\n    total = 0\n    with torch.no_grad():\n        for inputs, labels in testloader:\n            inputs, labels = inputs.to(device), labels.to(device)\n            outputs = model(inputs)\n            _, predicted = torch.max(outputs.data, 1)\n            total += labels.size(0)\n            correct += (predicted == labels).sum().item()\n\n    print(f'Test Accuracy: {100 * correct / total:.2f}%')\n\n# Train the model\ntrain(model, trainloader, criterion, optimizer, device, epochs=100)\n\n# Evaluate the model\nevaluate(model, testloader, device)\n","metadata":{"execution":{"iopub.status.busy":"2024-10-05T13:26:28.803156Z","iopub.execute_input":"2024-10-05T13:26:28.803577Z","iopub.status.idle":"2024-10-05T14:07:55.548768Z","shell.execute_reply.started":"2024-10-05T13:26:28.803529Z","shell.execute_reply":"2024-10-05T14:07:55.547584Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"torch.save(model.state_dict(), 'cifar10_resnet.pth')","metadata":{"execution":{"iopub.status.busy":"2024-10-05T14:08:17.299949Z","iopub.execute_input":"2024-10-05T14:08:17.300864Z","iopub.status.idle":"2024-10-05T14:08:17.423415Z","shell.execute_reply.started":"2024-10-05T14:08:17.300823Z","shell.execute_reply":"2024-10-05T14:08:17.422370Z"},"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-05T14:08:35.812331Z","iopub.execute_input":"2024-10-05T14:08:35.812734Z","iopub.status.idle":"2024-10-05T14:11:28.587426Z","shell.execute_reply.started":"2024-10-05T14:08:35.812690Z","shell.execute_reply":"2024-10-05T14:11:28.586556Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport pandas as pd\nfrom PIL import Image\nimport torch\nimport torch.nn as nn\nimport torchvision.transforms as transforms\n\n# CIFAR-10 classes\ncifar10_classes = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\n\n# Residual Block used for ResNet\nclass ResidualBlock(nn.Module):\n    def __init__(self, in_channels, out_channels, stride=1):\n        super(ResidualBlock, self).__init__()\n        self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)\n        self.bn1 = nn.BatchNorm2d(out_channels)\n        self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False)\n        self.bn2 = nn.BatchNorm2d(out_channels)\n\n        # Shortcut connection to match the dimensions\n        self.shortcut = nn.Sequential()\n        if stride != 1 or in_channels != out_channels:\n            self.shortcut = nn.Sequential(\n                nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False),\n                nn.BatchNorm2d(out_channels)\n            )\n\n    def forward(self, x):\n        out = torch.relu(self.bn1(self.conv1(x)))\n        out = self.bn2(self.conv2(out))\n        out += self.shortcut(x)  # Residual connection\n        out = torch.relu(out)\n        return out\n\n# Define the full ResNet model\nclass ResNet(nn.Module):\n    def __init__(self, block, num_blocks, num_classes=10):\n        super(ResNet, self).__init__()\n        self.in_channels = 64\n\n        # Initial convolutional 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 with residual blocks\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        # Fully connected layer for classification\n        self.fc = nn.Linear(512, num_classes)\n\n    def _make_layer(self, block, out_channels, num_blocks, stride):\n        strides = [stride] + [1] * (num_blocks - 1)\n        layers = []\n        for stride in strides:\n            layers.append(block(self.in_channels, out_channels, stride))\n            self.in_channels = out_channels\n        return nn.Sequential(*layers)\n\n    def forward(self, x):\n        out = torch.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 = torch.nn.functional.avg_pool2d(out, 4)\n        out = out.view(out.size(0), -1)  # Flatten the output\n        out = self.fc(out)\n        return out\n\n# Define ResNet18 model\ndef ResNet18():\n    return ResNet(ResidualBlock, [2, 2, 2, 2])\n\n# Inference function to predict and save results to CSV\ndef inference(model, test_folder, device, output_csv='predictions.csv'):\n    model.eval()  # Set model to evaluation mode\n    results = []\n\n    # Transform definition (same as during training)\n    transform = transforms.Compose([\n        transforms.Resize((32, 32)),  # Ensure the images are resized to 32x32\n        transforms.ToTensor(),\n        transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2470, 0.2435, 0.2616)),\n    ])\n\n    # Iterate over all images in the test folder\n    for img_name in os.listdir(test_folder):\n        img_path = os.path.join(test_folder, img_name)\n        img = Image.open(img_path).convert('RGB')  # Load image and convert to RGB\n        \n        # Preprocess the image\n        img = transform(img)\n        img = img.unsqueeze(0).to(device)  # Add batch dimension and move to device\n\n        # Perform inference\n        with torch.no_grad():\n            outputs = model(img)\n            _, predicted = torch.max(outputs, 1)\n            predicted_class = cifar10_classes[predicted.item()]  # Map predicted number to class name\n\n        # Extract integer ID from filename (remove .png extension)\n        img_id = int(os.path.splitext(img_name)[0])\n\n        # Type check for the integer ID\n        if not isinstance(img_id, int):\n            raise ValueError(f\"Image ID '{img_name}' could not be converted to an integer.\")\n\n        # Save the result as a dictionary (id = integer file name, label = predicted class)\n        results.append({'id': img_id, 'label': predicted_class})\n\n    # Save the results to a CSV file\n    df = pd.DataFrame(results)\n    df.to_csv(output_csv, index=False)\n    print(f\"Predictions saved to {output_csv}\")\n\n# Example usage (Kaggle working directory for test data)\ntest_folder = '/kaggle/working/test'  # Change this to your test folder path\noutput_csv = '/kaggle/working/predictions.csv'\n\n# Initialize the ResNet model (same as in training)\nmodel = ResNet18()\n\n# Load the trained weights with strict=False\nmodel.load_state_dict(torch.load('/kaggle/working/cifar10_resnet.pth'), strict=False)  # Update with the actual path to your trained model weights\n\n# Move the model to the appropriate device (GPU or CPU)\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nmodel = model.to(device)\n\n# Perform inference and save the results\ninference(model, test_folder, device, output_csv)\n","metadata":{"execution":{"iopub.status.busy":"2024-10-05T14:14:28.089679Z","iopub.execute_input":"2024-10-05T14:14:28.090554Z","iopub.status.idle":"2024-10-05T14:31:40.270344Z","shell.execute_reply.started":"2024-10-05T14:14:28.090511Z","shell.execute_reply":"2024-10-05T14:31:40.269330Z"},"trusted":true},"execution_count":null,"outputs":[]}]}