{"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"}],"dockerImageVersionId":30776,"isInternetEnabled":true,"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-02T15:47:47.711449Z","iopub.execute_input":"2024-10-02T15:47:47.711868Z","iopub.status.idle":"2024-10-02T15:47:47.719821Z","shell.execute_reply.started":"2024-10-02T15:47:47.711818Z","shell.execute_reply":"2024-10-02T15:47:47.718889Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Import necessary libraries\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.utils.data import DataLoader, Dataset\nfrom PIL import Image\nimport os\nimport shutil","metadata":{"execution":{"iopub.status.busy":"2024-10-02T15:47:47.721573Z","iopub.execute_input":"2024-10-02T15:47:47.722185Z","iopub.status.idle":"2024-10-02T15:47:47.733133Z","shell.execute_reply.started":"2024-10-02T15:47:47.72214Z","shell.execute_reply":"2024-10-02T15:47:47.732333Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install -q py7zr","metadata":{"execution":{"iopub.status.busy":"2024-10-02T15:47:47.734125Z","iopub.execute_input":"2024-10-02T15:47:47.7344Z","iopub.status.idle":"2024-10-02T15:47:59.175273Z","shell.execute_reply.started":"2024-10-02T15:47:47.734371Z","shell.execute_reply":"2024-10-02T15:47:59.173972Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from py7zr import unpack_7zarchive\n# Directly unpack the 7z file without re-registering the format\nshutil.unpack_archive(\"/kaggle/input/cifar-10/test.7z\", \"/kaggle/temp/test\")","metadata":{"execution":{"iopub.status.busy":"2024-10-02T15:49:01.4332Z","iopub.execute_input":"2024-10-02T15:49:01.434261Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define data augmentation and normalization for training and testing\ntransform_train = transforms.Compose([\n    transforms.RandomCrop(32, padding=4),\n    transforms.RandomHorizontalFlip(),\n    transforms.ToTensor(),\n    transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n])\n\ntransform_test = transforms.Compose([\n    transforms.ToTensor(),\n    transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n])","metadata":{"execution":{"iopub.status.busy":"2024-10-02T15:47:59.650263Z","iopub.status.idle":"2024-10-02T15:47:59.650654Z","shell.execute_reply.started":"2024-10-02T15:47:59.650459Z","shell.execute_reply":"2024-10-02T15:47:59.650479Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load CIFAR-10 training set\ntrainset = torchvision.datasets.CIFAR10(root='/kaggle/working/data', train=True, download=True, transform=transform_train)\ntrainloader = DataLoader(trainset, batch_size=128, shuffle=True, num_workers=2)","metadata":{"execution":{"iopub.status.busy":"2024-10-02T15:47:59.652019Z","iopub.status.idle":"2024-10-02T15:47:59.652356Z","shell.execute_reply.started":"2024-10-02T15:47:59.652185Z","shell.execute_reply":"2024-10-02T15:47:59.652202Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define the basic block for ResNet\nclass BasicBlock(nn.Module):\n    def __init__(self, in_channels, out_channels, stride=1):\n        super(BasicBlock, self).__init__()\n        self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1)\n        self.bn1 = nn.BatchNorm2d(out_channels)\n        self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)\n        self.bn2 = nn.BatchNorm2d(out_channels)\n        self.shortcut = nn.Sequential()\n\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),\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)\n        out = torch.relu(out)\n        return out\n\n# Define the ResNet model\nclass ResNet(nn.Module):\n    def __init__(self, num_classes=10):\n        super(ResNet, self).__init__()\n        self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1)\n        self.bn1 = nn.BatchNorm2d(64)\n        self.layer1 = self._make_layer(64, 128, stride=2)\n        self.layer2 = self._make_layer(128, 256, stride=2)\n        \n        # Using AdaptiveAvgPool2d to always output a 1x1 feature map\n        self.avg_pool = nn.AdaptiveAvgPool2d((1, 1))\n        \n        # Adjusting the fully connected layer input size\n        self.fc = nn.Linear(256, num_classes)\n\n    def _make_layer(self, in_channels, out_channels, stride):\n        layers = []\n        layers.append(BasicBlock(in_channels, out_channels, stride))\n        layers.append(BasicBlock(out_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.avg_pool(out)  # Use adaptive pooling to get 1x1 output\n        out = out.view(out.size(0), -1)  # Flatten the output\n        out = self.fc(out)  # Pass it through the fully connected layer\n        return out","metadata":{"execution":{"iopub.status.busy":"2024-10-02T15:47:59.653558Z","iopub.status.idle":"2024-10-02T15:47:59.653931Z","shell.execute_reply.started":"2024-10-02T15:47:59.65375Z","shell.execute_reply":"2024-10-02T15:47:59.653769Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Initialize weights function\ndef initialize_weights(model):\n    for m in model.modules():\n        if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):\n            nn.init.kaiming_normal_(m.weight)\n        elif isinstance(m, nn.BatchNorm2d):\n            nn.init.constant_(m.weight, 1)\n            nn.init.constant_(m.bias, 0)\n\n# Instantiate and initialize the ResNet model\nnet = ResNet(num_classes=10)\ninitialize_weights(net)","metadata":{"execution":{"iopub.status.busy":"2024-10-02T15:47:59.655186Z","iopub.status.idle":"2024-10-02T15:47:59.655515Z","shell.execute_reply.started":"2024-10-02T15:47:59.655348Z","shell.execute_reply":"2024-10-02T15:47:59.655365Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Set device (GPU if available, otherwise CPU)\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nnet.to(device)\n\n# Define loss function and optimizer\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(net.parameters(), lr=0.001)","metadata":{"execution":{"iopub.status.busy":"2024-10-02T15:47:59.65667Z","iopub.status.idle":"2024-10-02T15:47:59.657026Z","shell.execute_reply.started":"2024-10-02T15:47:59.656852Z","shell.execute_reply":"2024-10-02T15:47:59.65687Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Training loop\ndef train_model(net, trainloader, num_epochs=25):\n    for epoch in range(num_epochs):\n        running_loss = 0.0\n        net.train()\n        for i, data in enumerate(trainloader, 0):\n            inputs, labels = data\n            inputs, labels = inputs.to(device), labels.to(device)\n            \n            # Zero the parameter gradients\n            optimizer.zero_grad()\n\n            # Forward + backward + optimize\n            outputs = net(inputs)\n            loss = criterion(outputs, labels)\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}, {i + 1}] loss: {running_loss / 100:.3f}')\n                running_loss = 0.0\n    print('Finished Training')\n\n# Train the model for 25 epochs\ntrain_model(net, trainloader, num_epochs=25)","metadata":{"execution":{"iopub.status.busy":"2024-10-02T15:47:59.658559Z","iopub.status.idle":"2024-10-02T15:47:59.65893Z","shell.execute_reply.started":"2024-10-02T15:47:59.658752Z","shell.execute_reply":"2024-10-02T15:47:59.658771Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Custom dataset class for Kaggle test images (30,000 images)\nclass CIFAR10TestDataset(Dataset):\n    def __init__(self, root_dir, transform=None):\n        self.root_dir = root_dir\n        self.image_files = sorted(os.listdir(root_dir))  # List of all test images (30,000)\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.image_files)  # Should return 30,000\n\n    def __getitem__(self, idx):\n        image_path = os.path.join(self.root_dir, self.image_files[idx])\n        image = Image.open(image_path)  # Open image as PIL\n        if self.transform:\n            image = self.transform(image)\n        return image","metadata":{"execution":{"iopub.status.busy":"2024-10-02T15:47:59.661Z","iopub.status.idle":"2024-10-02T15:47:59.661359Z","shell.execute_reply.started":"2024-10-02T15:47:59.661179Z","shell.execute_reply":"2024-10-02T15:47:59.661197Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load the 30,000 Kaggle test images\ntest_data_path = \"/kaggle/temp/test/test\"\ncifar10_test_dataset = CIFAR10TestDataset(test_data_path, transform=transform_test)\ntestloader = DataLoader(cifar10_test_dataset, batch_size=100, shuffle=False, num_workers=2)","metadata":{"execution":{"iopub.status.busy":"2024-10-02T15:47:59.662761Z","iopub.status.idle":"2024-10-02T15:47:59.663106Z","shell.execute_reply.started":"2024-10-02T15:47:59.662933Z","shell.execute_reply":"2024-10-02T15:47:59.662951Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Class names (corresponding to the CIFAR-10 dataset)\nclasses = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\n\n# Generate predictions for Kaggle submission\ndef generate_kaggle_submission(net, testloader):\n    net.eval()\n    predictions = []\n    image_ids = []\n    with torch.no_grad():\n        for i, images in enumerate(testloader):\n            images = images.to(device)\n            outputs = net(images)\n            _, predicted = torch.max(outputs.data, 1)\n            predicted = predicted.cpu().numpy()\n            predicted_classes = [classes[p] for p in predicted]  # Map numeric labels to class names\n            predictions.extend(predicted_classes)\n            image_ids.extend(list(range(i * testloader.batch_size + 1, (i + 1) * testloader.batch_size + 1)))  # Adjust IDs to start from 1\n    \n    # Prepare the submission DataFrame\n    submission = pd.DataFrame({'id': image_ids, 'label': predictions})\n    submission.to_csv('submission.csv', index=False)\n    print('Kaggle submission file generated: submission.csv')\n\n# Generate the Kaggle submission file\ngenerate_kaggle_submission(net, testloader)\n\n# Check the contents of the submission file\n!head submission.csv","metadata":{"execution":{"iopub.status.busy":"2024-10-02T15:47:59.664981Z","iopub.status.idle":"2024-10-02T15:47:59.665306Z","shell.execute_reply.started":"2024-10-02T15:47:59.665141Z","shell.execute_reply":"2024-10-02T15:47:59.665158Z"},"trusted":true},"execution_count":null,"outputs":[]}]}