{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceType":"competition","sourceId":3649,"databundleVersionId":46718}],"dockerImageVersionId":31329,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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","trusted":true,"execution":{"iopub.status.busy":"2026-04-02T12:22:31.777956Z","iopub.execute_input":"2026-04-02T12:22:31.778630Z","iopub.status.idle":"2026-04-02T12:22:31.785138Z","shell.execute_reply.started":"2026-04-02T12:22:31.778600Z","shell.execute_reply":"2026-04-02T12:22:31.784512Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-02T12:22:32.712351Z","iopub.execute_input":"2026-04-02T12:22:32.713134Z","iopub.status.idle":"2026-04-02T12:22:32.716322Z","shell.execute_reply.started":"2026-04-02T12:22:32.713105Z","shell.execute_reply":"2026-04-02T12:22:32.715535Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!apt-get install p7zip-full -y\n!7z x /kaggle/input/competitions/cifar-10/train.7z -o./","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-02T12:22:34.224801Z","iopub.execute_input":"2026-04-02T12:22:34.225543Z","iopub.status.idle":"2026-04-02T12:29:50.341143Z","shell.execute_reply.started":"2026-04-02T12:22:34.225513Z","shell.execute_reply":"2026-04-02T12:29:50.340313Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nimport pandas as pd\nimport os\nimport glob\nfrom PIL import Image\nfrom torch.utils.data import Dataset, DataLoader, random_split\nimport torchvision.transforms as transforms\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-02T12:29:53.734756Z","iopub.execute_input":"2026-04-02T12:29:53.735089Z","iopub.status.idle":"2026-04-02T12:29:53.740167Z","shell.execute_reply.started":"2026-04-02T12:29:53.735057Z","shell.execute_reply":"2026-04-02T12:29:53.739481Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class CIFAR10Kaggle(Dataset):\n    def __init__(self, csv_file, img_dir, transform=None):\n        self.df = pd.read_csv(csv_file)\n        self.img_dir = img_dir\n        self.transform = transform\n        self.label_mapping = {\n            'airplane':0, 'automobile':1, 'bird':2, 'cat':3, 'deer':4,\n            'dog':5, 'frog':6, 'horse':7, 'ship':8, 'truck':9\n        }\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        img_id = str(self.df.iloc[idx, 0])\n        img_name = os.path.join(self.img_dir, img_id + \".png\")\n        image = Image.open(img_name)\n        label = self.label_mapping[self.df.iloc[idx, 1]]\n        if self.transform:\n            image = self.transform(image)\n        return image, label","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-02T12:30:01.376180Z","iopub.execute_input":"2026-04-02T12:30:01.376840Z","iopub.status.idle":"2026-04-02T12:30:01.383003Z","shell.execute_reply.started":"2026-04-02T12:30:01.376811Z","shell.execute_reply":"2026-04-02T12:30:01.382065Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_csv = '/kaggle/input/competitions/cifar-10/trainLabels.csv'\ntrain_dir = './train' ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-02T12:30:03.555171Z","iopub.execute_input":"2026-04-02T12:30:03.556063Z","iopub.status.idle":"2026-04-02T12:30:03.559357Z","shell.execute_reply.started":"2026-04-02T12:30:03.556032Z","shell.execute_reply":"2026-04-02T12:30:03.558738Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from torchvision import models","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-02T12:30:05.129078Z","iopub.execute_input":"2026-04-02T12:30:05.129892Z","iopub.status.idle":"2026-04-02T12:30:05.133366Z","shell.execute_reply.started":"2026-04-02T12:30:05.129861Z","shell.execute_reply":"2026-04-02T12:30:05.132660Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 1. Define the device (This fixes your NameError)\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(f\"Using device: {device}\")\n\n# 2. Load the pre-trained ResNet18 model\nmodel = models.resnet18(weights=models.ResNet18_Weights.DEFAULT)\n\n# 3. Modify the final layer\n# ResNet-18's last layer is named 'fc' (Fully Connected)\nnum_features = model.fc.in_features \nmodel.fc = nn.Linear(num_features, 10) \n\n# 4. Move the model to the device\nmodel = model.to(device)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-02T12:30:06.812993Z","iopub.execute_input":"2026-04-02T12:30:06.813755Z","iopub.status.idle":"2026-04-02T12:30:07.023315Z","shell.execute_reply.started":"2026-04-02T12:30:06.813726Z","shell.execute_reply":"2026-04-02T12:30:07.022766Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Updated Transform for ResNet\ntransform = transforms.Compose([\n    transforms.Resize((64, 64)), # Upscaling helps pre-trained models\n    transforms.ToTensor(),\n    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) # ImageNet Stats\n])\n\n# Re-initialize datasets with the new transform\nfull_dataset = CIFAR10Kaggle(csv_file=train_csv, img_dir=train_dir, transform=transform)\ntrain_data, val_data = random_split(full_dataset, [45000, 5000])\ntrain_loader = DataLoader(train_data, batch_size=64, shuffle=True)\nval_loader = DataLoader(val_data, batch_size=64, shuffle=False)\n\n# Optimizer (Using a smaller learning rate for fine-tuning)\noptimizer = optim.Adam(model.parameters(), lr=0.0001) \ncriterion = nn.CrossEntropyLoss()\n\n# Training Loop\nfor epoch in range(5): # Pre-trained models converge very fast\n    model.train()\n    for i, (images, labels) in enumerate(train_loader):\n        images, labels = images.to(device), labels.to(device)\n        \n        optimizer.zero_grad()\n        outputs = model(images)\n        loss = criterion(outputs, labels)\n        loss.backward()\n        optimizer.step()\n        \n    # --- VALIDATION ---\n    model.eval()\n    correct, total = 0, 0\n    with torch.no_grad():\n        for images, labels in val_loader:\n            images, labels = images.to(device), labels.to(device)\n            outputs = model(images)\n            _, predicted = torch.max(outputs, 1)\n            total += labels.size(0)\n            correct += (predicted == labels).sum().item()\n    \n    print(f\"Epoch {epoch+1} | Val Accuracy: {100 * correct / total:.2f}%\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-02T12:30:09.550043Z","iopub.execute_input":"2026-04-02T12:30:09.550778Z","iopub.status.idle":"2026-04-02T12:33:32.014680Z","shell.execute_reply.started":"2026-04-02T12:30:09.550746Z","shell.execute_reply":"2026-04-02T12:33:32.013941Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Save the weights only (Recommended)\ntorch.save(model.state_dict(), 'cifar10_resnet18.pth')\nprint(\"Model saved to cifar10_resnet18.pth\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-02T12:36:26.183331Z","iopub.execute_input":"2026-04-02T12:36:26.184008Z","iopub.status.idle":"2026-04-02T12:36:26.247004Z","shell.execute_reply.started":"2026-04-02T12:36:26.183977Z","shell.execute_reply":"2026-04-02T12:36:26.246133Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}