{"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":[{"sourceType":"competition","sourceId":13836,"databundleVersionId":1718836},{"sourceType":"datasetVersion","sourceId":16327506,"datasetId":10466552,"databundleVersionId":17316457}],"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","trusted":true,"execution":{"iopub.status.busy":"2026-05-18T08:32:33.496552Z","iopub.execute_input":"2026-05-18T08:32:33.496884Z","iopub.status.idle":"2026-05-18T08:32:35.602730Z","shell.execute_reply.started":"2026-05-18T08:32:33.496861Z","shell.execute_reply":"2026-05-18T08:32:35.601431Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Import + Seed","metadata":{}},{"cell_type":"code","source":"import os, math, gc, glob \nimport random\nimport numpy as np\nimport pandas as pd \nfrom tqdm.auto import tqdm \n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim \nfrom torch.utils.data import Dataset, DataLoader\n\nfrom PIL import Image\nimport cv2 \nimport torchvision.transforms.v2 as T\nfrom torchvision import models, tv_tensors\n\nfrom torch.amp import GradScaler, autocast \nfrom torch.nn.utils import clip_grad_norm_\nfrom torch.optim.lr_scheduler import LambdaLR\nfrom sklearn.model_selection import train_test_split\nSEED =42\nrandom.seed(SEED); np.random.seed(SEED)\ntorch.manual_seed(SEED); torch.cuda.manual_seed_all(SEED)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark =False \n\ndevice = torch.device('cuda' if torch.cuda.is_available else  'cpu')\nprint(device)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-18T08:32:35.603209Z","iopub.status.idle":"2026-05-18T08:32:35.603514Z","shell.execute_reply.started":"2026-05-18T08:32:35.603328Z","shell.execute_reply":"2026-05-18T08:32:35.603343Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Config ","metadata":{}},{"cell_type":"code","source":"class CFG:\n    TRAIN_DIR = \"/kaggle/input/competitions/cassava-leaf-disease-classification/train_images\"\n    TEST_DIR = '/kaggle/input/competitions/cassava-leaf-disease-classification/test_images'\n    exts = '.jpg'\n    IMG_SIZE = 256\n    BATCH_SIZE = 16\n    NUM_EPOCHS = 50\n    WARMUP_EPOCHS =5 \n    WEIGHT_DECAY = 1e-4\n    EMA_DECAY = 0.999\n    NUM_WORKERS =2#os.cpu_count()\n    NUM_CLASSES = 5\n    LABEL_SMOOTH = 0.1\n    N_SPLITS = 5\n    PATIENCE = 5\n    MEAN = [0.485, 0.456, 0.406]\n    STD = [0.229, 0.224, 0.225]\nimg_paths = sorted([os.path.join(CFG.TRAIN_DIR, f)\n                                 for f in os.listdir(CFG.TRAIN_DIR)\n                                 if f.lower().endswith(CFG.exts)])\ntest_paths = sorted(\n  glob.glob(f'{CFG.TEST_DIR}/**/*.jpg')+  \n    glob.glob(f'{CFG.TEST_DIR}/*.jpg')+\n    glob.glob(f'{CFG.TEST_DIR}/**/*.png')\n)\ndf = pd.read_csv('/kaggle/input/competitions/cassava-leaf-disease-classification/train.csv')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-18T08:32:35.604395Z","iopub.status.idle":"2026-05-18T08:32:35.604681Z","shell.execute_reply.started":"2026-05-18T08:32:35.604562Z","shell.execute_reply":"2026-05-18T08:32:35.604577Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# EDA","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Offline Preprocessing ","metadata":{}},{"cell_type":"code","source":"SAVE_IMG_DIR = '/kaggle/working/processed/images'\nos.makedirs(SAVE_IMG_DIR, exist_ok = True)\nfor img_path in tqdm(img_paths , total = len(img_paths)):\n    name = os.path.splitext(os.path.basename(img_path))[0]\n    img = cv2.imread(img_path)\n    img = cv2.resize(img, dsize = (300,300), interpolation =cv2.INTER_AREA)\n    cv2.imwrite(os.path.join(SAVE_IMG_DIR, f'{name}.png'), img)\nimg_paths = sorted([os.path.join(SAVE_IMG_DIR, f)\n                                 for f in os.listdir(SAVE_IMG_DIR)])","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Dataset","metadata":{}},{"cell_type":"code","source":"class CassavaDataSet(Dataset):\n    def __init__(self, img_paths, labels, transform):\n        self.img_paths = img_paths\n        self.labels = labels\n        self.transform = transform\n    def __len__(self):\n        return len(self.img_paths)\n    def __getitem__(self, idx):\n        img = cv2.imread(self.img_paths[idx])\n        img= cv2.cvtColor(img , cv2.COLOR_BGR2RGB)\n        img = tv_tensors.ImageF.to_image(img))\n        if self.transform:\n            img = self.transform(img)\n        if self.labels is not None:\n            label = torch.tensor(self.labels[idx], dtype = torch.long)\n            return img, label\n        return img","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-18T08:32:35.605940Z","iopub.status.idle":"2026-05-18T08:32:35.606257Z","shell.execute_reply.started":"2026-05-18T08:32:35.606086Z","shell.execute_reply":"2026-05-18T08:32:35.606107Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Transform","metadata":{}},{"cell_type":"code","source":"train_tf = T.Compose([\n    T.RandomResizedCrop(size =(CFG.IMG_SIZE , CFG.IMG_SIZE), antialias = True), \n    T.RandomHorizontalFlip(p=0.5),\n    T.RandomVerticalFlip(p=0.2),\n    T.RandomAffine(degrees = 0.0 , translate = (0.05, 0.05), scale = (0.9, 1.1)),\n    T.ColorJitter(brightness = 0.2, contrast = 0.2, hue = 0.1),\n    T.GaussianBlur(kernel_size = (3,3), sigma= (0.1 , 1.0)),\n    T.ToDtype(torch.float32, scale =True),\n    T.Normalize( mean = CFG.MEAN , std =CFG.STD)\n])\nval_tf = T.Compose([\n    T.Resize(size =(CFG.IMG_SIZE , CFG.IMG_SIZE), antialias = True), \n    T.ToDtype(torch.float32, scale =True),\n    T.Normalize( mean = CFG.MEAN , std =CFG.STD)\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-18T08:32:35.607546Z","iopub.status.idle":"2026-05-18T08:32:35.608045Z","shell.execute_reply.started":"2026-05-18T08:32:35.607831Z","shell.execute_reply":"2026-05-18T08:32:35.607858Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Train - Val Spliting ","metadata":{}},{"cell_type":"code","source":"all_paths = np.array(sorted(glob.glob('/kaggle/working/processed/images/*.png')))\n#all_paths = np.array(img_paths)\nall_labels = df['label'].values\n\nprint('classes' , np.unique(all_labels))\nprint('images', len(all_paths))\n\ntr_paths, val_paths, tr_labels, val_labels = train_test_split(\n    all_paths, \n    all_labels, \n    test_size=0.2, \n    random_state=SEED, \n    stratify=all_labels \n)\n    \ntrain_ds = CassavaDataSet(tr_paths, tr_labels, transform =train_tf)\nval_ds = CassavaDataSet(val_paths, val_labels, transform = val_tf)\n\ntrain_loader = DataLoader(\n        train_ds,\n        batch_size  =CFG.BATCH_SIZE,\n        shuffle =True,\n        num_workers = CFG.NUM_WORKERS,\n        pin_memory = True\n    )\nval_loader = DataLoader(\n        val_ds,\n        batch_size  =CFG.BATCH_SIZE,\n        shuffle =False,\n        num_workers = CFG.NUM_WORKERS,\n        pin_memory = True\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-18T08:32:35.608876Z","iopub.status.idle":"2026-05-18T08:32:35.609232Z","shell.execute_reply.started":"2026-05-18T08:32:35.609041Z","shell.execute_reply":"2026-05-18T08:32:35.609065Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Model (Backbone + Head)","metadata":{}},{"cell_type":"code","source":"model = models.convnext_tiny(weights= 'DEFAULT')\nin_features_model = model.classifier[2].in_features\nmodel.classifier[2] = nn.Sequential(\n    nn.LayerNorm((in_features_model,), eps=1e-06, elementwise_affine=True),\n    nn.Dropout(0.2),\n    nn.Linear(in_features_model, CFG.NUM_CLASSES)\n)\nmodel = model.to(device)\n#if torch.cuda.device_count() > 1:\n  # model = nn.DataParallel(model)\noptimizer_grouped_parameters = [\n    {'params': nn.Sequential(model.features[0], model.features[1]).parameters(), 'lr': 1e-5}, # Stage 1\n    {'params': nn.Sequential(model.features[2], model.features[3]).parameters(), 'lr': 1e-5}, # Stage 2\n    {'params': nn.Sequential(model.features[4], model.features[5]).parameters(), 'lr': 1e-4}, # Stage 3\n    {'params': nn.Sequential(model.features[6], model.features[7]).parameters(), 'lr': 1e-4}, # Stage 4\n    {'params': model.classifier.parameters(), 'lr': 1e-3}                                    # FC Head\n]\n\noptimizer = optim.AdamW(optimizer_grouped_parameters, weight_decay=CFG.WEIGHT_DECAY, eps=1e-8)\n\n\ncriterion = nn.CrossEntropyLoss(label_smoothing=CFG.LABEL_SMOOTH)\n\ndef lr_lambda(ep):\n    if ep < CFG.WARMUP_EPOCHS:\n        return (ep + 1) / CFG.WARMUP_EPOCHS\n    prog = (ep - CFG.WARMUP_EPOCHS) / (CFG.NUM_EPOCHS - CFG.WARMUP_EPOCHS)\n    return 0.5 * (1 + np.cos(np.pi * prog))\n\nscheduler = LambdaLR(optimizer, lr_lambda)\nscaler = GradScaler()    ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-18T08:33:01.286203Z","iopub.execute_input":"2026-05-18T08:33:01.286938Z","iopub.status.idle":"2026-05-18T08:33:01.726161Z","shell.execute_reply.started":"2026-05-18T08:33:01.286905Z","shell.execute_reply":"2026-05-18T08:33:01.725533Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# EMA","metadata":{}},{"cell_type":"code","source":"class EMA:\n    def __init__(self, model, decay =0.999):\n        self.decay =decay\n        self.shadow = {k: v.detach().clone()\n                       for k, v in model.state_dict().items()\n                       if v.dtype.is_floating_point}\n        self._bk ={}\n    def update(self, model):\n        with torch.no_grad():\n            for k,v in model.state_dict().items():\n                if k in self.shadow:\n                    self.shadow[k].mul_(self.decay).add_(v.detach() , alpha = 1 -self.decay)\n    def apply(self, model):\n        self._bk = {k: model.state_dict()[k].detach().clone() for k in self.shadow}\n        for k in self.shadow:\n            model.state_dict()[k].copy_(self.shadow[k])\n    def restore(self,model):\n        for k in self._bk:\n            model.state_dict()[k].copy_(self._bk[k])\n\nema = EMA(model, CFG.EMA_DECAY)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-18T08:33:06.256148Z","iopub.execute_input":"2026-05-18T08:33:06.256575Z","iopub.status.idle":"2026-05-18T08:33:06.270339Z","shell.execute_reply.started":"2026-05-18T08:33:06.256539Z","shell.execute_reply":"2026-05-18T08:33:06.269676Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class EMA:\n    def __init__(self, model, decay):\n        self.decay = decay\n        self.shadow = {k: v.detach().clone()\n                      for k,v in model.state_dict().items()\n                      if v.dtype.is_floating_point}\n\n    def update(self, model):\n        with torch.no_grad():\n            for k,v in model.state_dict().items():\n                if k in self.shadow:\n                    self.shadow[k].mul_(self.decay).add_(v.detach(), alpha = 1 - self.decay)\n\n    def apply(s)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Evaluate ","metadata":{}},{"cell_type":"code","source":"def evaluate(model, dataloader, criterion, device):\n    model.eval() \n    val_loss = 0.0\n    correct = 0\n    total = 0\n    \n    with torch.no_grad():  \n        for imgs, labels in dataloader:\n            imgs, labels = imgs.to(device), labels.to(device)\n            \n            with torch.amp.autocast(device_type='cuda'):\n                outputs = model(imgs)\n                logits = outputs['logits'] if isinstance(outputs, dict) else outputs\n                loss = criterion(logits, labels)\n                \n            val_loss += loss.item()\n            preds = logits.argmax(dim=1)\n            correct += (preds == labels).sum().item()\n            total += labels.size(0)\n            \n    return val_loss / len(dataloader), correct / total","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-18T08:33:09.277589Z","iopub.execute_input":"2026-05-18T08:33:09.278180Z","iopub.status.idle":"2026-05-18T08:33:09.284184Z","shell.execute_reply.started":"2026-05-18T08:33:09.278133Z","shell.execute_reply":"2026-05-18T08:33:09.283452Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# For Loop","metadata":{}},{"cell_type":"code","source":"best_score = 0.0\nno_improve_epochs = 0\n\nprint(f\"🚀 Bắt đầu Train với {CFG.NUM_EPOCHS} Epochs trên thiết bị: {device}\")\n\nfor epoch in tqdm(range(CFG.NUM_EPOCHS), total=CFG.NUM_EPOCHS):\n    model.train()\n    train_loss = 0.0     \n    \n    for imgs, labels in train_loader:\n        imgs, labels = imgs.to(device), labels.to(device)\n        optimizer.zero_grad()\n        \n        with torch.amp.autocast(device_type='cuda'):\n            outputs = model(imgs)\n            logits = outputs['logits'] if isinstance(outputs, dict) else outputs\n            loss = criterion(logits, labels)\n            \n        scaler.scale(loss).backward()\n        scaler.unscale_(optimizer)\n        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n        scaler.step(optimizer)\n        scaler.update()\n        \n        ema.update(model)\n        train_loss += loss.item()\n        \n    train_loss /= len(train_loader)\n    \n    ema.apply(model) \n    val_loss, val_score = evaluate(model, val_loader, criterion, device)\n    \n    print(f\"Epoch {epoch+1}/{CFG.NUM_EPOCHS} | Train Loss: {train_loss:.4f} | Val Loss: {val_loss:.4f} | Val Acc: {val_score:.4f}\")\n    \n    if val_score > best_score:\n        best_score = val_score\n        no_improve_epochs = 0 \n        \n        # Mẹo: Lưu model gốc sạch sẽ, kể cả khi dùng DataParallel\n        raw_model = model.module if hasattr(model, \"module\") else model\n        torch.save(raw_model.state_dict(), \"best_model.pth\") \n        print(f\"🌟 Đã lưu Model xuất sắc nhất với Val Acc: {best_score:.4f}\")\n    else:\n        no_improve_epochs += 1\n        if no_improve_epochs >= CFG.PATIENCE:\n            print(f\"🛑 Kích hoạt Early Stopping tại Epoch {epoch+1}!\")\n            ema.restore(model)\n            break\n            \n    ema.restore(model) \n    scheduler.step()   \n    gc.collect()\n    torch.cuda.empty_cache()\n\nprint(f\"🏆 Quá trình hoàn tất! Điểm số cao nhất đạt được: {best_score:.4f}\")","metadata":{"execution":{"iopub.status.busy":"2026-05-18T04:37:15.294898Z","iopub.execute_input":"2026-05-18T04:37:15.295641Z","iopub.status.idle":"2026-05-18T04:37:32.697242Z","shell.execute_reply.started":"2026-05-18T04:37:15.295601Z","shell.execute_reply":"2026-05-18T04:37:32.696117Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Predict (TTA) ( In another notebook + Turn off Internet)","metadata":{}},{"cell_type":"code","source":"# 3. Định nghĩa bộ TTA\nmodel.load_state_dict(torch.load(\"/kaggle/input/datasets/anhqunng367/123456/best_model.pth\", map_location=device))\nmodel.eval() \n# Đảm bảo val_tf của cậu đang là một LIST các transform cơ bản (Resize, Normalize, ToTensor...)\n#  ĐÃ SỬA CHUẨN CÚ PHÁP: Tất cả các phép toán đều nằm gọn TRONG một cặp dấu ngoặc vuông []\nTTA_TF = [\n    val_tf,\n    T.Compose([T.RandomHorizontalFlip(p=1.0), val_tf]),\n    \n    T.Compose([T.RandomRotation((90, 90)), val_tf]),\n    \n    T.Compose([T.RandomRotation((-90, -90)), val_tf])\n]\nall_probs = []\n\n# 4. Vòng lặp TTA chạy qua tập Test\nfor tf in TTA_TF:\n    test_ds = CassavaDataSet(test_paths, labels=None, transform=tf)\n    \n    #  ĐÃ SỬA: shuffle=False (BẮT BUỘC), sửa lại tên biến batch_size\n    test_loader = DataLoader(\n        test_ds, jh\n        batch_size=CFG.BATCH_SIZE, \n        shuffle=False, \n        num_workers=CFG.NUM_WORKERS\n    )\n    \n    probs = []\n    with torch.no_grad():\n        for x in test_loader:\n            x = x.to(device)\n            \n            with torch.amp.autocast(device_type='cuda'):\n                outputs = model(x)\n                logits = outputs['logits'] if isinstance(outputs, dict) else outputs\n            probs.append(F.softmax(logits.float(), dim=1).cpu().numpy())\n            \n    all_probs.append(np.concatenate(probs, axis=0)) \n\nfinal_probs = np.mean(all_probs, axis=0)\npreds = final_probs.argmax(axis=1)\nsubmission = pd.DataFrame({\n    'image_id': [os.path.basename(p) for p in test_paths],\n    'label': preds\n})\nsubmission.to_csv('submission.csv', index=False)\nprint(\"🏆 Đã tạo file submission.csv thành công! Sẵn sàng nộp bài rồi Quân ơi!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-18T08:33:21.267550Z","iopub.execute_input":"2026-05-18T08:33:21.268861Z","iopub.status.idle":"2026-05-18T08:33:26.304440Z","shell.execute_reply.started":"2026-05-18T08:33:21.268785Z","shell.execute_reply":"2026-05-18T08:33:26.303402Z"}},"outputs":[],"execution_count":null}]}