{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":118873,"databundleVersionId":14227970,"sourceType":"competition"}],"dockerImageVersionId":31236,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport os","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-28T12:00:49.507097Z","iopub.execute_input":"2025-12-28T12:00:49.507708Z","iopub.status.idle":"2025-12-28T12:00:49.511297Z","shell.execute_reply.started":"2025-12-28T12:00:49.507678Z","shell.execute_reply":"2025-12-28T12:00:49.510531Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-28T12:00:49.512870Z","iopub.execute_input":"2025-12-28T12:00:49.513402Z","iopub.status.idle":"2025-12-28T12:00:49.526321Z","shell.execute_reply.started":"2025-12-28T12:00:49.513381Z","shell.execute_reply":"2025-12-28T12:00:49.525785Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_index = pd.read_csv('/kaggle/input/cifar-10neucalssification/train_labels.csv')\ntrain_index.head(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-28T12:00:49.526985Z","iopub.execute_input":"2025-12-28T12:00:49.527215Z","iopub.status.idle":"2025-12-28T12:00:49.569339Z","shell.execute_reply.started":"2025-12-28T12:00:49.527160Z","shell.execute_reply":"2025-12-28T12:00:49.568566Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"val_index = pd.read_csv('/kaggle/input/cifar-10neucalssification/val_labels.csv')\nval_index.head(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-28T12:00:49.570285Z","iopub.execute_input":"2025-12-28T12:00:49.570491Z","iopub.status.idle":"2025-12-28T12:00:49.583232Z","shell.execute_reply.started":"2025-12-28T12:00:49.570470Z","shell.execute_reply":"2025-12-28T12:00:49.582643Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"label_decode = ['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-28T12:00:49.584919Z","iopub.execute_input":"2025-12-28T12:00:49.585147Z","iopub.status.idle":"2025-12-28T12:00:49.589045Z","shell.execute_reply.started":"2025-12-28T12:00:49.585126Z","shell.execute_reply":"2025-12-28T12:00:49.588145Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def base_path(BASE_PATH,data_index):\n    data_index['full_path'] = data_index['filename'].apply(lambda x: os.path.join(BASE_PATH, x))\n    # 2. Collect the files and their labels\n    image_paths = data_index['full_path'].tolist()\n    labels = data_index['label'].tolist()\n    return image_paths,labels\n    ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-28T12:00:49.589998Z","iopub.execute_input":"2025-12-28T12:00:49.590395Z","iopub.status.idle":"2025-12-28T12:00:49.604686Z","shell.execute_reply.started":"2025-12-28T12:00:49.590375Z","shell.execute_reply":"2025-12-28T12:00:49.604147Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 3. Visualize images with labels\ndef visualize_images(image_paths, labels, num_images=9, figsize=(15, 15)):\n    \"\"\"\n    Visualize images in a grid with their labels\n    \n    Parameters:\n    - image_paths: list of image file paths\n    - labels: list of corresponding labels\n    - num_images: number of images to display (default 9)\n    - figsize: figure size for the plot\n    \"\"\"\n    # Limit to available images or requested number\n    num_images = min(num_images, len(image_paths))\n    \n    # Calculate grid dimensions\n    cols = 3\n    rows = (num_images + cols - 1) // cols\n    \n    fig, axes = plt.subplots(rows, cols, figsize=figsize)\n    axes = axes.flatten() if num_images > 1 else [axes]\n    \n    for idx in range(num_images):\n        try:\n            # Load and display image\n            img = Image.open(image_paths[idx])\n            axes[idx].imshow(img)\n            axes[idx].axis('off')\n            axes[idx].set_title(f'Label: {label_decode[labels[idx]]}', fontsize=12, fontweight='bold')\n        except Exception as e:\n            axes[idx].text(0.5, 0.5, f'Error loading image\\n{e}', \n                          ha='center', va='center')\n            axes[idx].axis('off')\n    \n    # Hide unused subplots\n    for idx in range(num_images, len(axes)):\n        axes[idx].axis('off')\n    \n    plt.tight_layout()\n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-28T12:00:49.605670Z","iopub.execute_input":"2025-12-28T12:00:49.605906Z","iopub.status.idle":"2025-12-28T12:00:49.623001Z","shell.execute_reply.started":"2025-12-28T12:00:49.605883Z","shell.execute_reply":"2025-12-28T12:00:49.622214Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_data,train_label = base_path(\"/kaggle/input/cifar-10neucalssification/train/\",train_index)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-28T12:00:49.623857Z","iopub.execute_input":"2025-12-28T12:00:49.624119Z","iopub.status.idle":"2025-12-28T12:00:49.676914Z","shell.execute_reply.started":"2025-12-28T12:00:49.624097Z","shell.execute_reply":"2025-12-28T12:00:49.676345Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(train_data[0])\nprint(label_decode[train_label[0]])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-28T12:00:49.677801Z","iopub.execute_input":"2025-12-28T12:00:49.678060Z","iopub.status.idle":"2025-12-28T12:00:49.682222Z","shell.execute_reply.started":"2025-12-28T12:00:49.678026Z","shell.execute_reply":"2025-12-28T12:00:49.681457Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Visualize the first 10 images\nvisualize_images(train_data, train_label, num_images=10)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-28T12:00:49.683122Z","iopub.execute_input":"2025-12-28T12:00:49.683456Z","iopub.status.idle":"2025-12-28T12:00:50.570776Z","shell.execute_reply.started":"2025-12-28T12:00:49.683418Z","shell.execute_reply":"2025-12-28T12:00:50.569981Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"val_data,val_label = base_path(\"/kaggle/input/cifar-10neucalssification/val/\",val_index)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-28T12:00:50.571720Z","iopub.execute_input":"2025-12-28T12:00:50.572086Z","iopub.status.idle":"2025-12-28T12:00:50.585303Z","shell.execute_reply.started":"2025-12-28T12:00:50.572060Z","shell.execute_reply":"2025-12-28T12:00:50.584631Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(val_data[0])\nprint(label_decode[val_label[0]])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-28T12:00:50.586280Z","iopub.execute_input":"2025-12-28T12:00:50.586539Z","iopub.status.idle":"2025-12-28T12:00:50.601112Z","shell.execute_reply.started":"2025-12-28T12:00:50.586507Z","shell.execute_reply":"2025-12-28T12:00:50.600532Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"visualize_images(val_data, val_label, num_images=10)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-28T12:00:50.603548Z","iopub.execute_input":"2025-12-28T12:00:50.603814Z","iopub.status.idle":"2025-12-28T12:00:51.147860Z","shell.execute_reply.started":"2025-12-28T12:00:50.603794Z","shell.execute_reply":"2025-12-28T12:00:51.147104Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Reshape the Training Data**","metadata":{}},{"cell_type":"code","source":"class ImageDataset(Dataset):\n    def __init__(self, image_paths, labels, transform=None):\n        self.image_paths = image_paths\n        self.labels = labels\n        self.transform = transform\n        \n        # Convert labels to unique integers\n        self.unique_labels = list(set(labels))\n        self.label_to_idx = {label: idx for idx, label in enumerate(self.unique_labels)}\n        \n    def __len__(self):\n        return len(self.image_paths)\n    \n    def __getitem__(self, idx):\n        img = Image.open(self.image_paths[idx]).convert('RGB')\n        label = self.label_to_idx[self.labels[idx]]\n        \n        if self.transform:\n            img = self.transform(img)\n            \n        return img, label","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-28T12:00:51.148888Z","iopub.execute_input":"2025-12-28T12:00:51.149321Z","iopub.status.idle":"2025-12-28T12:00:51.155193Z","shell.execute_reply.started":"2025-12-28T12:00:51.149286Z","shell.execute_reply":"2025-12-28T12:00:51.154512Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Define transforms\ntrain_transform = transforms.Compose([\n    transforms.Resize((32, 32)),\n    transforms.RandomHorizontalFlip(),\n    transforms.RandomRotation(15),\n    transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2),\n    transforms.RandomAffine(degrees=0, translate=(0.1, 0.1)),\n    transforms.ToTensor(),\n])\n\n# Keep validation transform simple (no augmentation)\nval_transform = transforms.Compose([\n    transforms.Resize((32, 32)),\n    transforms.ToTensor(),\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-28T12:00:51.156212Z","iopub.execute_input":"2025-12-28T12:00:51.156460Z","iopub.status.idle":"2025-12-28T12:00:51.172208Z","shell.execute_reply.started":"2025-12-28T12:00:51.156436Z","shell.execute_reply":"2025-12-28T12:00:51.171486Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_set = ImageDataset(train_data, train_label, transform=train_transform)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-28T12:00:51.173117Z","iopub.execute_input":"2025-12-28T12:00:51.173387Z","iopub.status.idle":"2025-12-28T12:00:51.188003Z","shell.execute_reply.started":"2025-12-28T12:00:51.173360Z","shell.execute_reply":"2025-12-28T12:00:51.187331Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_loader = DataLoader(train_set, batch_size=32, shuffle=True)\n\n# Test it\nprint(f\"Dataset size: {len(train_set)}\")\nprint(f\"Number of classes: {len(train_set.unique_labels)}\")\nprint(f\"Classes: {train_set.unique_labels}\")\n\n# Get one batch\nimages, labels = next(iter(train_loader))\nprint(f\"\\nBatch image shape: {images.shape}\")\nprint(f\"Batch labels shape: {labels.shape}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-28T12:00:51.188937Z","iopub.execute_input":"2025-12-28T12:00:51.189160Z","iopub.status.idle":"2025-12-28T12:00:51.304031Z","shell.execute_reply.started":"2025-12-28T12:00:51.189140Z","shell.execute_reply":"2025-12-28T12:00:51.303406Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"val_set = ImageDataset(val_data, val_label, transform=val_transform)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-28T12:00:51.304957Z","iopub.execute_input":"2025-12-28T12:00:51.305246Z","iopub.status.idle":"2025-12-28T12:00:51.309849Z","shell.execute_reply.started":"2025-12-28T12:00:51.305215Z","shell.execute_reply":"2025-12-28T12:00:51.309285Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"val_loader = DataLoader(val_set, batch_size=32, shuffle=True)\n\n# Test it\nprint(f\"Dataset size: {len(val_set)}\")\nprint(f\"Number of classes: {len(val_set.unique_labels)}\")\nprint(f\"Classes: {val_set.unique_labels}\")\n\n# Get one batch\nimages, labels = next(iter(val_loader))\nprint(f\"\\nBatch image shape: {images.shape}\")\nprint(f\"Batch labels shape: {labels.shape}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-28T12:00:51.310962Z","iopub.execute_input":"2025-12-28T12:00:51.311243Z","iopub.status.idle":"2025-12-28T12:00:51.404625Z","shell.execute_reply.started":"2025-12-28T12:00:51.311216Z","shell.execute_reply":"2025-12-28T12:00:51.403921Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import random_split\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-28T12:00:51.405534Z","iopub.execute_input":"2025-12-28T12:00:51.405781Z","iopub.status.idle":"2025-12-28T12:00:51.409594Z","shell.execute_reply.started":"2025-12-28T12:00:51.405759Z","shell.execute_reply":"2025-12-28T12:00:51.408913Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Simple Small CNN for 32x32 images\nclass SmallCNN(nn.Module):\n    def __init__(self, num_classes):\n        super(SmallCNN, self).__init__()\n        self.features = nn.Sequential(\n            nn.Conv2d(3, 32, 3, padding=1),\n            nn.BatchNorm2d(32),\n            nn.ReLU(),\n            nn.Conv2d(32, 32, 3, padding=1),\n            nn.BatchNorm2d(32),\n            nn.ReLU(),\n            nn.MaxPool2d(2, 2),\n            nn.Dropout(0.2),\n            \n            nn.Conv2d(32, 64, 3, padding=1),\n            nn.BatchNorm2d(64),\n            nn.ReLU(),\n            nn.Conv2d(64, 64, 3, padding=1),\n            nn.BatchNorm2d(64),\n            nn.ReLU(),\n            nn.MaxPool2d(2, 2),\n            nn.Dropout(0.3),\n        )\n        self.classifier = nn.Sequential(\n            nn.Flatten(),\n            nn.Linear(64 * 8 * 8, 256),\n            nn.ReLU(),\n            nn.Dropout(0.5),\n            nn.Linear(256, num_classes)\n        )\n    def forward(self, x):\n        x = self.features(x)\n        x = self.classifier(x)\n        return x","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-28T12:04:03.245606Z","iopub.execute_input":"2025-12-28T12:04:03.246367Z","iopub.status.idle":"2025-12-28T12:04:03.252452Z","shell.execute_reply.started":"2025-12-28T12:04:03.246337Z","shell.execute_reply":"2025-12-28T12:04:03.251722Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Setup (using your existing train_loader and val_loader)\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nnum_classes = len(train_set.unique_labels)\nmodel = SmallCNN(num_classes).to(device)\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters(),lr=0.0001)\n\nprint(f\"Device: {device}\")\nprint(f\"Classes: {num_classes}\")\nprint(f\"Train: {len(train_set)}, Val: {len(val_set)}\\n\")\n\n# Training\nnum_epochs = 35\n\nfor epoch in range(num_epochs):\n    # Train\n    model.train()\n    train_loss = 0\n    train_correct = 0\n    train_total = 0\n    \n    for images, labels in 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        train_loss += loss.item()\n        _, predicted = outputs.max(1)\n        train_total += labels.size(0)\n        train_correct += predicted.eq(labels).sum().item()\n    \n    # Validate\n    model.eval()\n    val_loss = 0\n    val_correct = 0\n    val_total = 0\n    \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            loss = criterion(outputs, labels)\n            \n            val_loss += loss.item()\n            _, predicted = outputs.max(1)\n            val_total += labels.size(0)\n            val_correct += predicted.eq(labels).sum().item()\n    \n    train_acc = 100. * train_correct / train_total\n    val_acc = 100. * val_correct / val_total\n    \n    print(f\"Epoch {epoch+1}/{num_epochs}\")\n    print(f\"  Train: Loss={train_loss/len(train_loader):.3f}, Acc={train_acc:.2f}%\")\n    print(f\"  Val:   Loss={val_loss/len(val_loader):.3f}, Acc={val_acc:.2f}%\\n\")\n\nprint(\"Training completed!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-28T12:04:06.205573Z","iopub.execute_input":"2025-12-28T12:04:06.205946Z","execution_failed":"2025-12-28T12:36:00.355Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def predict_image(image_path, model, device):\n    \"\"\"\n    Predict the label of an image\n    \n    Args:\n        image_path: Path to the image file\n        model: Trained model\n        device: Device to run prediction on\n    \n    Returns:\n        predicted_label: The predicted class label\n        confidence: Confidence score (probability)\n    \"\"\"\n    # Define the same transform used during training\n    transform = transforms.Compose([\n        transforms.Resize((32, 32)),\n        transforms.ToTensor(),\n    ])\n    \n    # Load and preprocess image\n    image = Image.open(image_path).convert('RGB')\n    image = transform(image)\n    image = image.unsqueeze(0)  # Add batch dimension\n    image = image.to(device)\n    \n    # Make prediction\n    model.eval()\n    with torch.no_grad():\n        output = model(image)\n        probabilities = torch.softmax(output, dim=1)\n        confidence, predicted_idx = torch.max(probabilities, 1)\n    \n    # Get the label name\n    idx_to_label = {idx: label for label, idx in train_set.label_to_idx.items()}\n    predicted_label = idx_to_label[predicted_idx.item()]\n    \n    return predicted_label, confidence.item()","metadata":{"trusted":true,"execution":{"execution_failed":"2025-12-28T12:36:00.355Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Example usage:\n# Single prediction\ntest_image_path = '/kaggle/input/cifar-10neucalssification/test/00020.png'\nimage = Image.open(test_image_path).convert('RGB')\nplt.imshow(image)\nplt.show()\npredicted_label, confidence = predict_image(test_image_path, model, device)\nprint(f\"Predicted: {predicted_label} , Decode: {label_decode[predicted_label]}\")\nprint(f\"Confidence: {confidence*100:.2f}%\")","metadata":{"trusted":true,"execution":{"execution_failed":"2025-12-28T12:36:00.355Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_data = pd.read_csv('/kaggle/input/cifar-10neucalssification/sample_submission.csv')\ntest_data.head(5)","metadata":{"trusted":true,"execution":{"execution_failed":"2025-12-28T12:36:00.355Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_data['full_path'] = test_data['filename'].apply(lambda x: os.path.join(\"/kaggle/input/cifar-10neucalssification/test/\", x))\nimage_paths = test_data['full_path'].tolist()\nprint(image_paths[0])","metadata":{"trusted":true,"execution":{"execution_failed":"2025-12-28T12:36:00.355Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def predict_multiple(image_paths, model, device):\n    \"\"\"Predict labels for multiple images\"\"\"\n    results = []\n    for img_path in image_paths:\n        label, conf = predict_image(img_path, model, device)\n        results.append({\n            'image_path': img_path,\n            'predicted_label': label,\n            'confidence': conf\n        })\n    return results","metadata":{"trusted":true,"execution":{"execution_failed":"2025-12-28T12:36:00.356Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"results = predict_multiple(image_paths,model,device)\npredicted_labels = [item['predicted_label'] for item in results]","metadata":{"trusted":true,"execution":{"execution_failed":"2025-12-28T12:36:00.356Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"col0 = pd.read_csv(\"/kaggle/input/cifar-10neucalssification/sample_submission.csv\").drop(['label'],axis=1)","metadata":{"trusted":true,"execution":{"execution_failed":"2025-12-28T12:36:00.356Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"col1 = pd.Series(predicted_labels, name='label')\nsubmission = pd.concat([col0,col1],axis = 1)\nsubmission.to_csv(\"submission.csv\",index=False)","metadata":{"trusted":true,"execution":{"execution_failed":"2025-12-28T12:36:00.356Z"}},"outputs":[],"execution_count":null}]}