{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.13.15","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[],"dockerImageVersionId":28755,"isInternetEnabled":false,"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\n\n# Use the kagglehub client library to attach Kaggle resources like competitions, datasets, and models to your session\n# Learn more about kagglehub: https://github.com/Kaggle/kagglehub/blob/main/README.md\n\nimport kagglehub\n# kagglehub.dataset_download('<owner>/<dataset-slug>')","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-10-10T15:31:24.679295Z","iopub.execute_input":"2026-10-10T15:31:24.679579Z","iopub.status.idle":"2026-10-10T15:31:24.694589Z","shell.execute_reply.started":"2026-10-10T15:31:24.679558Z","shell.execute_reply":"2026-10-10T15:31:24.693826Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n!pip -q install py7zr\n\nimport os\nimport gc\nimport random\nimport math\nimport time\nimport copy\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\nfrom PIL import Image\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms\n\n# Reproducibility\nSEED = 42\nrandom.seed(SEED)\nnp.random.seed(SEED)\ntorch.manual_seed(SEED)\ntorch.cuda.manual_seed_all(SEED)\n\nDEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(\"Device:\", DEVICE)\nif DEVICE.type == \"cuda\":\n    print(\"GPU:\", torch.cuda.get_device_name(0))\n\n# Mixed precision can speed up GPU training.\nUSE_AMP = DEVICE.type == \"cuda\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-10T15:31:24.719274Z","iopub.execute_input":"2026-10-10T15:31:24.71973Z","iopub.status.idle":"2026-10-10T15:31:27.981396Z","shell.execute_reply.started":"2026-10-10T15:31:24.719709Z","shell.execute_reply":"2026-10-10T15:31:27.980527Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nimport py7zr\n\nINPUT_ROOT = Path(\"/kaggle/input\")\nWORK_ROOT = Path(\"/kaggle/working\")\nEXTRACT_ROOT = WORK_ROOT / \"cifar10_data\"\nEXTRACT_ROOT.mkdir(parents=True, exist_ok=True)\n\ndef find_file(filename):\n    matches = list(INPUT_ROOT.rglob(filename))\n    if not matches:\n        raise FileNotFoundError(\n            f\"Cannot find {filename}. Add the CIFAR-10 competition \"\n            \"dataset through the notebook's Add Input menu.\"\n        )\n    return matches[0]\n\ntrain_archive = find_file(\"train.7z\")\ntest_archive = find_file(\"test.7z\")\nlabels_file = find_file(\"trainLabels.csv\")\nsample_file = find_file(\"sampleSubmission.csv\")\n\ndef extract_if_needed(archive_path, destination):\n    # Avoid extracting an archive again if its image folder is present.\n    folder_name = \"train\" if \"train.7z\" in str(archive_path) else \"test\"\n    expected = destination / folder_name\n    if expected.exists() and any(expected.glob(\"*.png\")):\n        print(\"Already extracted:\", expected)\n        return\n\n    print(\"Extracting:\", archive_path)\n    with py7zr.SevenZipFile(archive_path, mode=\"r\") as archive:\n        archive.extractall(path=destination)\n\nextract_if_needed(train_archive, EXTRACT_ROOT)\nextract_if_needed(test_archive, EXTRACT_ROOT)\n\n# Locate folders even if the archive uses a nested directory.\ndef find_image_folder(name):\n    candidates = list(EXTRACT_ROOT.rglob(name))\n    for candidate in candidates:\n        if candidate.is_dir() and any(candidate.glob(\"*.png\")):\n            return candidate\n    raise FileNotFoundError(f\"Could not locate extracted {name} image folder.\")\n\nTRAIN_DIR = find_image_folder(\"train\")\nTEST_DIR = find_image_folder(\"test\")\n\nlabels_df = pd.read_csv(labels_file)\nsample_df = pd.read_csv(sample_file)\n\nprint(\"Training images:\", len(labels_df))\nprint(\"Submission rows:\", len(sample_df))\nprint(\"Label columns:\", labels_df.columns.tolist())\nprint(\"Sample submission:\")\nprint(sample_df.head())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-10T15:31:27.983158Z","iopub.execute_input":"2026-10-10T15:31:27.98342Z","iopub.status.idle":"2026-10-10T15:31:28.915844Z","shell.execute_reply.started":"2026-10-10T15:31:27.983396Z","shell.execute_reply":"2026-10-10T15:31:28.915216Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nCLASS_NAMES = [\n    \"airplane\", \"automobile\", \"bird\", \"cat\", \"deer\",\n    \"dog\", \"frog\", \"horse\", \"ship\", \"truck\"\n]\nCLASS_TO_IDX = {name: i for i, name in enumerate(CLASS_NAMES)}\n\nassert {\"id\", \"label\"}.issubset(labels_df.columns), \\\n    \"Expected trainLabels.csv columns: id,label\"\nassert {\"id\", \"label\"}.issubset(sample_df.columns), \\\n    \"Expected sampleSubmission.csv columns: id,label\"\n\nlabels_df[\"label_idx\"] = labels_df[\"label\"].map(CLASS_TO_IDX)\nassert labels_df[\"label_idx\"].notna().all(), \"Unknown training label\"\n\n# CIFAR-10 normalization statistics.\nMEAN = (0.4914, 0.4822, 0.4465)\nSTD  = (0.2470, 0.2435, 0.2616)\n\ntrain_transform = transforms.Compose([\n    transforms.RandomCrop(32, padding=4, padding_mode=\"reflect\"),\n    transforms.RandomHorizontalFlip(),\n    transforms.ColorJitter(\n        brightness=0.15, contrast=0.15, saturation=0.15\n    ),\n    transforms.ToTensor(),\n    transforms.Normalize(MEAN, STD),\n    transforms.RandomErasing(\n        p=0.15, scale=(0.02, 0.12), ratio=(0.3, 3.3)\n    ),\n])\n\nvalid_transform = transforms.Compose([\n    transforms.ToTensor(),\n    transforms.Normalize(MEAN, STD),\n])\n\nclass CIFARCompetitionDataset(Dataset):\n    def __init__(self, image_dir, ids, labels=None, transform=None):\n        self.image_dir = Path(image_dir)\n        self.ids = [int(x) for x in ids]\n        self.labels = None if labels is None else np.asarray(labels, dtype=np.int64)\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.ids)\n\n    def __getitem__(self, index):\n        image_id = self.ids[index]\n        path = self.image_dir / f\"{image_id}.png\"\n\n        with Image.open(path) as im:\n            image = im.convert(\"RGB\")\n\n        if self.transform:\n            image = self.transform(image)\n\n        if self.labels is None:\n            return image, image_id\n        return image, int(self.labels[index])\n\n# Split the labeled data into training and validation sets.\n# Stratification preserves the class proportions in both sets.\nfrom sklearn.model_selection import train_test_split\n\nall_ids = labels_df[\"id\"].astype(int).to_numpy()\nall_labels = labels_df[\"label_idx\"].astype(int).to_numpy()\n\ntrain_ids, valid_ids, train_y, valid_y = train_test_split(\n    all_ids,\n    all_labels,\n    test_size=0.10,\n    random_state=SEED,\n    stratify=all_labels,\n)\n\nBATCH_SIZE = 128\nNUM_WORKERS = 2\n\ntrain_ds = CIFARCompetitionDataset(\n    TRAIN_DIR, train_ids, train_y, train_transform\n)\nvalid_ds = CIFARCompetitionDataset(\n    TRAIN_DIR, valid_ids, valid_y, valid_transform\n)\n\ntrain_loader = DataLoader(\n    train_ds, batch_size=BATCH_SIZE, shuffle=True,\n    num_workers=NUM_WORKERS, pin_memory=USE_AMP,\n    drop_last=True, persistent_workers=NUM_WORKERS > 0\n)\nvalid_loader = DataLoader(\n    valid_ds, batch_size=256, shuffle=False,\n    num_workers=NUM_WORKERS, pin_memory=USE_AMP,\n    persistent_workers=NUM_WORKERS > 0\n)\n\nprint(\"Training samples:\", len(train_ds))\nprint(\"Validation samples:\", len(valid_ds))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-10T15:31:28.916829Z","iopub.execute_input":"2026-10-10T15:31:28.917329Z","iopub.status.idle":"2026-10-10T15:31:28.966313Z","shell.execute_reply.started":"2026-10-10T15:31:28.917304Z","shell.execute_reply":"2026-10-10T15:31:28.965541Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nclass SEBlock(nn.Module):\n    def __init__(self, channels, reduction=8):\n        super().__init__()\n        hidden = max(channels // reduction, 8)\n        self.pool = nn.AdaptiveAvgPool2d(1)\n        self.fc = nn.Sequential(\n            nn.Linear(channels, hidden),\n            nn.SiLU(inplace=True),\n            nn.Linear(hidden, channels),\n            nn.Sigmoid(),\n        )\n\n    def forward(self, x):\n        b, c, _, _ = x.shape\n        scale = self.fc(self.pool(x).view(b, c)).view(b, c, 1, 1)\n        return x * scale\n\n\nclass ResidualBlock(nn.Module):\n    def __init__(self, in_channels, out_channels, stride=1, drop_prob=0.0):\n        super().__init__()\n\n        self.conv1 = nn.Conv2d(\n            in_channels, out_channels, 3,\n            stride=stride, padding=1, bias=False\n        )\n        self.bn1 = nn.BatchNorm2d(out_channels)\n        self.conv2 = nn.Conv2d(\n            out_channels, out_channels, 3,\n            stride=1, padding=1, bias=False\n        )\n        self.bn2 = nn.BatchNorm2d(out_channels)\n\n        self.se = SEBlock(out_channels)\n        self.drop_prob = drop_prob\n\n        if stride != 1 or in_channels != out_channels:\n            self.shortcut = nn.Sequential(\n                nn.Conv2d(\n                    in_channels, out_channels, 1,\n                    stride=stride, bias=False\n                ),\n                nn.BatchNorm2d(out_channels),\n            )\n        else:\n            self.shortcut = nn.Identity()\n\n    def forward(self, x):\n        identity = self.shortcut(x)\n\n        out = self.conv1(x)\n        out = self.bn1(out)\n        out = F.silu(out)\n\n        out = self.conv2(out)\n        out = self.bn2(out)\n        out = self.se(out)\n\n        # Stochastic depth: randomly skip the residual branch during training.\n        if self.training and self.drop_prob > 0:\n            keep_prob = 1.0 - self.drop_prob\n            mask = torch.empty(\n                (out.shape[0], 1, 1, 1),\n                device=out.device, dtype=out.dtype\n            ).bernoulli_(keep_prob)\n            out = out * mask / keep_prob\n\n        return F.silu(out + identity)\n\n\nclass CustomCIFARNet(nn.Module):\n    def __init__(self, num_classes=10):\n        super().__init__()\n\n        self.stem = nn.Sequential(\n            nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False),\n            nn.BatchNorm2d(64),\n            nn.SiLU(inplace=True),\n        )\n\n        self.stage1 = nn.Sequential(\n            ResidualBlock(64, 64, drop_prob=0.02),\n            ResidualBlock(64, 64, drop_prob=0.03),\n        )\n        self.stage2 = nn.Sequential(\n            ResidualBlock(64, 128, stride=2, drop_prob=0.04),\n            ResidualBlock(128, 128, drop_prob=0.06),\n        )\n        self.stage3 = nn.Sequential(\n            ResidualBlock(128, 256, stride=2, drop_prob=0.08),\n            ResidualBlock(256, 256, drop_prob=0.10),\n        )\n\n        self.pool = nn.AdaptiveAvgPool2d(1)\n        self.classifier = nn.Sequential(\n            nn.Flatten(),\n            nn.Dropout(0.20),\n            nn.Linear(256, num_classes),\n        )\n\n        self.apply(self._initialize)\n\n    @staticmethod\n    def _initialize(module):\n        if isinstance(module, nn.Conv2d):\n            nn.init.kaiming_normal_(\n                module.weight, mode=\"fan_out\", nonlinearity=\"relu\"\n            )\n        elif isinstance(module, nn.Linear):\n            nn.init.normal_(module.weight, mean=0.0, std=0.01)\n            if module.bias is not None:\n                nn.init.zeros_(module.bias)\n        elif isinstance(module, nn.BatchNorm2d):\n            nn.init.ones_(module.weight)\n            nn.init.zeros_(module.bias)\n\n    def forward(self, x):\n        x = self.stem(x)\n        x = self.stage1(x)\n        x = self.stage2(x)\n        x = self.stage3(x)\n        x = self.pool(x)\n        return self.classifier(x)\n\n\nmodel = CustomCIFARNet().to(DEVICE)\n\nparameter_count = sum(p.numel() for p in model.parameters())\nprint(f\"Trainable parameters: {parameter_count:,}\")\nprint(\"Pretrained weights: none\")\nprint(model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-10T15:31:28.96733Z","iopub.execute_input":"2026-10-10T15:31:28.967641Z","iopub.status.idle":"2026-10-10T15:31:29.032989Z","shell.execute_reply.started":"2026-10-10T15:31:28.96761Z","shell.execute_reply":"2026-10-10T15:31:29.032413Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nEPOCHS = 180\nLEARNING_RATE = 0.001\nWEIGHT_DECAY = 0.0005\nWARMUP_EPOCHS = 5\nCUTMIX_PROB = 0.50\nLABEL_SMOOTHING = 0.05\n\noptimizer = torch.optim.AdamW(\n    model.parameters(),\n    lr=LEARNING_RATE,\n    weight_decay=WEIGHT_DECAY,\n)\n\ndef lr_lambda(epoch):\n    if epoch < WARMUP_EPOCHS:\n        return float(epoch + 1) / WARMUP_EPOCHS\n\n    progress = (epoch - WARMUP_EPOCHS) / max(\n        1, EPOCHS - WARMUP_EPOCHS\n    )\n    return 0.5 * (1.0 + math.cos(math.pi * progress))\n\nscheduler = torch.optim.lr_scheduler.LambdaLR(\n    optimizer, lr_lambda=lr_lambda\n)\n\nscaler = torch.amp.GradScaler(\"cuda\", enabled=USE_AMP)\n\ncriterion = nn.CrossEntropyLoss(\n    label_smoothing=LABEL_SMOOTHING\n)\n\ndef cutmix_batch(images, targets, alpha=1.0):\n    batch_size = images.size(0)\n\n    if batch_size < 2 or random.random() > CUTMIX_PROB:\n        return images, targets, targets, 1.0\n\n    lam = np.random.beta(alpha, alpha)\n\n    permutation = torch.randperm(batch_size, device=images.device)\n    targets_b = targets[permutation]\n\n    height, width = images.shape[2], images.shape[3]\n    cut_ratio = math.sqrt(1.0 - lam)\n    cut_w = int(width * cut_ratio)\n    cut_h = int(height * cut_ratio)\n\n    center_x = random.randint(0, width - 1)\n    center_y = random.randint(0, height - 1)\n\n    x1 = max(0, center_x - cut_w // 2)\n    x2 = min(width, center_x + cut_w // 2)\n    y1 = max(0, center_y - cut_h // 2)\n    y2 = min(height, center_y + cut_h // 2)\n\n    mixed = images.clone()\n    mixed[:, :, y1:y2, x1:x2] = images[\n        permutation, :, y1:y2, x1:x2\n    ]\n\n    # Correct the mixing ratio for clipping at image boundaries.\n    box_area = (x2 - x1) * (y2 - y1)\n    lam_adjusted = 1.0 - box_area / float(width * height)\n\n    return mixed, targets, targets_b, lam_adjusted\n\n\n@torch.no_grad()\ndef evaluate(model, loader):\n    model.eval()\n    correct = 0\n    total = 0\n    loss_sum = 0.0\n\n    for images, targets in loader:\n        images = images.to(DEVICE, non_blocking=True)\n        targets = targets.to(DEVICE, non_blocking=True)\n\n        with torch.autocast(\n            device_type=DEVICE.type,\n            dtype=torch.float16,\n            enabled=USE_AMP,\n        ):\n            logits = model(images)\n            loss = F.cross_entropy(logits, targets)\n\n        loss_sum += loss.item() * targets.size(0)\n        correct += (logits.argmax(1) == targets).sum().item()\n        total += targets.size(0)\n\n    return loss_sum / total, correct / total","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-10T15:31:29.03476Z","iopub.execute_input":"2026-10-10T15:31:29.034974Z","iopub.status.idle":"2026-10-10T15:31:29.046608Z","shell.execute_reply.started":"2026-10-10T15:31:29.034956Z","shell.execute_reply":"2026-10-10T15:31:29.045807Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nBEST_PATH = WORK_ROOT / \"best_cifar10_custom_cnn.pth\"\n\nbest_val_acc = 0.0\nbest_epoch = 0\nhistory = []\n\nfor epoch in range(EPOCHS):\n    start_time = time.time()\n    model.train()\n\n    running_loss = 0.0\n    running_correct = 0\n    running_total = 0\n\n    for images, targets in train_loader:\n        images = images.to(DEVICE, non_blocking=True)\n        targets = targets.to(DEVICE, non_blocking=True)\n\n        images, target_a, target_b, lam = cutmix_batch(images, targets)\n\n        optimizer.zero_grad(set_to_none=True)\n\n        with torch.autocast(\n            device_type=DEVICE.type,\n            dtype=torch.float16,\n            enabled=USE_AMP,\n        ):\n            logits = model(images)\n            loss = (\n                lam * criterion(logits, target_a)\n                + (1.0 - lam) * criterion(logits, target_b)\n            )\n\n        scaler.scale(loss).backward()\n        scaler.unscale_(optimizer)\n        torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=5.0)\n        scaler.step(optimizer)\n        scaler.update()\n\n        running_loss += loss.item() * targets.size(0)\n\n        # Approximate training accuracy; CutMix batches have mixed labels.\n        running_correct += (\n            logits.argmax(1) == targets\n        ).sum().item()\n        running_total += targets.size(0)\n\n    scheduler.step()\n\n    val_loss, val_acc = evaluate(model, valid_loader)\n    train_loss = running_loss / running_total\n    train_acc = running_correct / running_total\n    current_lr = optimizer.param_groups[0][\"lr\"]\n    elapsed = time.time() - start_time\n\n    record = {\n        \"epoch\": epoch + 1,\n        \"train_loss\": train_loss,\n        \"train_acc\": train_acc,\n        \"val_loss\": val_loss,\n        \"val_acc\": val_acc,\n        \"lr\": current_lr,\n        \"seconds\": elapsed,\n    }\n    history.append(record)\n\n    if val_acc > best_val_acc:\n        best_val_acc = val_acc\n        best_epoch = epoch + 1\n        torch.save(model.state_dict(), BEST_PATH)\n\n    print(\n        f\"Epoch {epoch+1:03d}/{EPOCHS} | \"\n        f\"train loss {train_loss:.4f} | \"\n        f\"train acc {train_acc:.4f} | \"\n        f\"val loss {val_loss:.4f} | \"\n        f\"val acc {val_acc:.4f} | \"\n        f\"lr {current_lr:.6f} | \"\n        f\"{elapsed:.0f}s\"\n    )\n\n    # Keep a recoverable record of progress.\n    pd.DataFrame(history).to_csv(\n        WORK_ROOT / \"training_history.csv\", index=False\n    )\n\n    # Save an emergency checkpoint periodically.\n    if (epoch + 1) % 10 == 0:\n        torch.save(\n            {\n                \"epoch\": epoch + 1,\n                \"model_state_dict\": model.state_dict(),\n                \"optimizer_state_dict\": optimizer.state_dict(),\n                \"best_val_acc\": best_val_acc,\n            },\n            WORK_ROOT / \"latest_checkpoint.pth\",\n        )\n\nprint(f\"\\nBest validation accuracy: {best_val_acc:.4%}\")\nprint(f\"Best epoch: {best_epoch}\")\nprint(\"Best model:\", BEST_PATH)\n\nmodel.load_state_dict(torch.load(BEST_PATH, map_location=DEVICE))\nmodel.eval()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-10T15:31:29.047663Z","iopub.execute_input":"2026-10-10T15:31:29.048317Z","iopub.status.idle":"2026-10-10T16:55:39.274539Z","shell.execute_reply.started":"2026-10-10T15:31:29.048286Z","shell.execute_reply":"2026-10-10T16:55:39.273699Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\ntest_ids = sample_df[\"id\"].astype(int).to_numpy()\n\ntest_ds = CIFARCompetitionDataset(\n    TEST_DIR,\n    test_ids,\n    labels=None,\n    transform=valid_transform,\n)\n\ntest_loader = DataLoader(\n    test_ds,\n    batch_size=256,\n    shuffle=False,\n    num_workers=NUM_WORKERS,\n    pin_memory=USE_AMP,\n    persistent_workers=NUM_WORKERS > 0,\n)\n\n@torch.no_grad()\ndef predict_test(model, loader):\n    model.eval()\n    predictions = []\n    predicted_ids = []\n\n    for images, ids in loader:\n        images = images.to(DEVICE, non_blocking=True)\n\n        with torch.autocast(\n            device_type=DEVICE.type,\n            dtype=torch.float16,\n            enabled=USE_AMP,\n        ):\n            logits_original = model(images)\n            logits_flipped = model(torch.flip(images, dims=[3]))\n            logits = (logits_original + logits_flipped) / 2.0\n\n        predictions.extend(logits.argmax(dim=1).cpu().numpy().tolist())\n        predicted_ids.extend(ids.numpy().astype(int).tolist())\n\n    return predicted_ids, predictions\n\n\npredicted_ids, predicted_labels = predict_test(model, test_loader)\n\n# Map predicted integer labels back to competition class names.\nidx_to_class = {i: name for name, i in CLASS_TO_IDX.items()}\n\nprediction_df = pd.DataFrame({\n    \"id\": predicted_ids,\n    \"label\": [idx_to_class[int(x)] for x in predicted_labels],\n})\n\n# Preserve exactly the order of the official submission template.\nsubmission = sample_df[[\"id\"]].merge(\n    prediction_df, on=\"id\", how=\"left\", sort=False\n)\n\nassert len(submission) == len(sample_df)\nassert submission[\"label\"].notna().all()\nassert submission[\"id\"].equals(sample_df[\"id\"])\n\nSUBMISSION_PATH = WORK_ROOT / \"submission.csv\"\nsubmission.to_csv(SUBMISSION_PATH, index=False)\n\nprint(submission.head())\nprint(\"Submission rows:\", len(submission))\nprint(\"Saved to:\", SUBMISSION_PATH)\nprint(\"Label distribution:\")\nprint(submission[\"label\"].value_counts())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-10T16:55:39.27628Z","iopub.execute_input":"2026-10-10T16:55:39.276543Z","iopub.status.idle":"2026-10-10T16:56:57.088999Z","shell.execute_reply.started":"2026-10-10T16:55:39.276519Z","shell.execute_reply":"2026-10-10T16:56:57.087958Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\ncheck = pd.read_csv(SUBMISSION_PATH)\n\nassert list(check.columns) == [\"id\", \"label\"]\nassert len(check) == len(sample_df)\nassert check[\"id\"].equals(sample_df[\"id\"])\nassert check[\"label\"].isin(CLASS_NAMES).all()\nassert not check.isna().any().any()\n\nprint(\"Submission file passed basic checks.\")\nprint(\"File size:\", round(SUBMISSION_PATH.stat().st_size / 1e6, 2), \"MB\")\nprint(\"Unique predicted classes:\", check[\"label\"].nunique())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-10T16:56:57.090854Z","iopub.execute_input":"2026-10-10T16:56:57.0913Z","iopub.status.idle":"2026-10-10T16:56:57.202573Z","shell.execute_reply.started":"2026-10-10T16:56:57.091272Z","shell.execute_reply":"2026-10-10T16:56:57.201945Z"}},"outputs":[],"execution_count":null}]}