{"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":126119,"databundleVersionId":14953781,"isSourceIdPinned":false}],"dockerImageVersionId":31287,"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-02-23T16:18:15.850007Z","iopub.execute_input":"2026-02-23T16:18:15.850385Z","iopub.status.idle":"2026-02-23T16:18:20.463854Z","shell.execute_reply.started":"2026-02-23T16:18:15.850351Z","shell.execute_reply":"2026-02-23T16:18:20.463120Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport re\nimport cv2\nimport timm\nimport torch\nimport random\nimport tifffile as tiff\nimport numpy as np\nimport pandas as pd\nimport torch.nn as nn\n\nfrom pathlib import Path\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import f1_score\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.cuda.amp import autocast, GradScaler","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-23T16:18:20.465327Z","iopub.execute_input":"2026-02-23T16:18:20.465664Z","iopub.status.idle":"2026-02-23T16:18:20.470203Z","shell.execute_reply.started":"2026-02-23T16:18:20.465606Z","shell.execute_reply":"2026-02-23T16:18:20.469521Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def seed_everything(seed=42):\n    random.seed(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed_all(seed)\n    torch.backends.cudnn.deterministic = True\n    torch.backends.cudnn.benchmark = False\n\nseed_everything(42)\n\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-23T16:18:20.471267Z","iopub.execute_input":"2026-02-23T16:18:20.471517Z","iopub.status.idle":"2026-02-23T16:18:20.485428Z","shell.execute_reply.started":"2026-02-23T16:18:20.471490Z","shell.execute_reply":"2026-02-23T16:18:20.484688Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"BASE = Path(\"/kaggle/input/competitions/beyond-visible-spectrum-ai-for-agriculture-2026/Kaggle_Prepared/train\")\n\nrecords = []\n\nfor rgb in sorted((BASE/\"RGB\").glob(\"*.png\")):\n    name = rgb.stem\n    label = name.split(\"_\")[0]\n\n    records.append({\n        \"id\": name,\n        \"label\": label,\n        \"RGB_path\": str(rgb),\n        \"MS_path\": str(BASE/\"MS\"/f\"{name}.tif\"),\n        \"HS_path\": str(BASE/\"HS\"/f\"{name}.tif\")\n    })\n\ndf = pd.DataFrame(records)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-23T16:18:20.487528Z","iopub.execute_input":"2026-02-23T16:18:20.487839Z","iopub.status.idle":"2026-02-23T16:18:20.519076Z","shell.execute_reply.started":"2026-02-23T16:18:20.487819Z","shell.execute_reply":"2026-02-23T16:18:20.518346Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\ndf[\"fold\"] = -1\n\nfor fold, (_, val_idx) in enumerate(skf.split(df, df[\"label\"])):\n    df.loc[val_idx, \"fold\"] = fold","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-23T16:18:20.520059Z","iopub.execute_input":"2026-02-23T16:18:20.520384Z","iopub.status.idle":"2026-02-23T16:18:20.532285Z","shell.execute_reply.started":"2026-02-23T16:18:20.520351Z","shell.execute_reply":"2026-02-23T16:18:20.531509Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def load_rgb(path):\n    img = cv2.imread(path)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    img = cv2.resize(img,(128,128))\n    return img.astype(\"float32\")/255.0","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-23T16:18:20.533375Z","iopub.execute_input":"2026-02-23T16:18:20.533932Z","iopub.status.idle":"2026-02-23T16:18:20.539263Z","shell.execute_reply.started":"2026-02-23T16:18:20.533904Z","shell.execute_reply":"2026-02-23T16:18:20.538458Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"HS_START = 10\nHS_END = 111   # exclusive → gives 101 bands\n\ndef load_hs_clean(path):\n    hs = tiff.imread(path).astype(\"float32\")\n    hs = hs[:,:,HS_START:HS_END]\n    return hs","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-23T16:18:20.540025Z","iopub.execute_input":"2026-02-23T16:18:20.540247Z","iopub.status.idle":"2026-02-23T16:18:20.550040Z","shell.execute_reply.started":"2026-02-23T16:18:20.540226Z","shell.execute_reply":"2026-02-23T16:18:20.549330Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def compute_indices(ms):\n    blue  = ms[:,:,0]\n    green = ms[:,:,1]\n    red   = ms[:,:,2]\n    rededge = ms[:,:,3]\n    nir   = ms[:,:,4]\n\n    ndvi = (nir - red) / (nir + red + 1e-6)\n    ndre = (nir - rededge) / (nir + rededge + 1e-6)\n\n    return np.stack([ndvi, ndre], axis=-1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-23T16:18:20.550870Z","iopub.execute_input":"2026-02-23T16:18:20.551126Z","iopub.status.idle":"2026-02-23T16:18:20.560329Z","shell.execute_reply.started":"2026-02-23T16:18:20.551106Z","shell.execute_reply":"2026-02-23T16:18:20.559771Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"label_map = {\"Health\":0,\"Other\":1,\"Rust\":2}\n\nclass MultiModalDataset(Dataset):\n    def __init__(self, df, fold, train=True):\n        self.train = train\n        self.df = df[df.fold!=fold] if train else df[df.fold==fold]\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        row = self.df.iloc[idx]\n\n        # RGB\n        rgb = load_rgb(row.RGB_path)\n        rgb = torch.tensor(rgb).permute(2,0,1).float()\n\n        # MS\n        ms = tiff.imread(row.MS_path).astype(\"float32\")\n        indices = compute_indices(ms)\n        ms = np.concatenate([ms, indices], axis=-1)\n        ms = torch.tensor(ms).permute(2,0,1).float()\n\n        # HS\n        hs = load_hs_clean(row.HS_path)\n        hs = torch.tensor(hs).permute(2,0,1).float()\n\n        label = torch.tensor(label_map[row.label])\n        return rgb, ms, hs, label","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-23T16:18:20.561165Z","iopub.execute_input":"2026-02-23T16:18:20.561392Z","iopub.status.idle":"2026-02-23T16:18:20.571475Z","shell.execute_reply.started":"2026-02-23T16:18:20.561372Z","shell.execute_reply":"2026-02-23T16:18:20.570860Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class RGBEncoder(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.backbone = timm.create_model(\n            \"convnext_tiny\",\n            pretrained=True,\n            num_classes=0\n        )\n\n    def forward(self,x):\n        return self.backbone(x)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-23T16:18:20.573695Z","iopub.execute_input":"2026-02-23T16:18:20.574005Z","iopub.status.idle":"2026-02-23T16:18:20.585431Z","shell.execute_reply.started":"2026-02-23T16:18:20.573983Z","shell.execute_reply":"2026-02-23T16:18:20.584749Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class MSEncoder(nn.Module):\n    def __init__(self, in_ch=7):\n        super().__init__()\n\n        self.net = nn.Sequential(\n            nn.Conv2d(in_ch,32,3,padding=1),\n            nn.BatchNorm2d(32),\n            nn.ReLU(),\n\n            nn.Conv2d(32,64,3,padding=1),\n            nn.BatchNorm2d(64),\n            nn.ReLU(),\n\n            nn.AdaptiveAvgPool2d(1)\n        )\n\n        self.fc = nn.Linear(64,768)\n\n    def forward(self,x):\n        x = self.net(x).flatten(1)\n        return self.fc(x)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-23T16:18:20.586299Z","iopub.execute_input":"2026-02-23T16:18:20.586546Z","iopub.status.idle":"2026-02-23T16:18:20.597109Z","shell.execute_reply.started":"2026-02-23T16:18:20.586521Z","shell.execute_reply":"2026-02-23T16:18:20.596453Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class HSEncoder(nn.Module):\n    def __init__(self, bands=101):\n        super().__init__()\n\n        # Spectral compression per pixel\n        self.spectral = nn.Conv1d(bands, 64, kernel_size=1)\n\n        # Spatial CNN\n        self.spatial = nn.Sequential(\n            nn.Conv2d(64, 64, 3, padding=1),\n            nn.BatchNorm2d(64),\n            nn.ReLU(),\n            nn.AdaptiveAvgPool2d(1)\n        )\n\n        self.fc = nn.Linear(64, 768)\n\n    def forward(self, x):\n        # x: [B, Bands, H, W]\n\n        B, C, H, W = x.shape\n\n        # reshape so Conv1d works along spectral dimension\n        x = x.view(B, C, -1)          # [B, Bands, H*W]\n        x = self.spectral(x)          # [B, 64, H*W]\n\n        # reshape back to spatial\n        x = x.view(B, 64, H, W)\n\n        x = self.spatial(x)\n        x = x.flatten(1)\n\n        return self.fc(x)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-23T16:18:20.597893Z","iopub.execute_input":"2026-02-23T16:18:20.598202Z","iopub.status.idle":"2026-02-23T16:18:20.609195Z","shell.execute_reply.started":"2026-02-23T16:18:20.598182Z","shell.execute_reply":"2026-02-23T16:18:20.608512Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class FusionAttention(nn.Module):\n    def __init__(self, dim=768):\n        super().__init__()\n\n        self.gate = nn.Sequential(\n            nn.Linear(dim*3, dim),\n            nn.ReLU(),\n            nn.Linear(dim,3),\n            nn.Softmax(dim=1)\n        )\n\n    def forward(self,r,m,h):\n        concat = torch.cat([r,m,h],1)\n        weights = self.gate(concat)\n\n        fused = (\n            weights[:,0:1]*r +\n            weights[:,1:2]*m +\n            weights[:,2:3]*h\n        )\n        return fused","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-23T16:18:20.610189Z","iopub.execute_input":"2026-02-23T16:18:20.610408Z","iopub.status.idle":"2026-02-23T16:18:20.625247Z","shell.execute_reply.started":"2026-02-23T16:18:20.610387Z","shell.execute_reply":"2026-02-23T16:18:20.624490Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class FusionNet(nn.Module):\n    def __init__(self):\n        super().__init__()\n\n        self.rgb = RGBEncoder()\n        self.ms  = MSEncoder()\n        self.hs  = HSEncoder()\n\n        self.fusion = FusionAttention(768)\n\n        self.classifier = nn.Sequential(\n            nn.Linear(768,256),\n            nn.ReLU(),\n            nn.Dropout(0.5),\n            nn.Linear(256,3)\n        )\n\n    def forward(self,rgb,ms,hs):\n        r = self.rgb(rgb)\n        m = self.ms(ms)\n        h = self.hs(hs)\n\n        fused = self.fusion(r,m,h)\n        return self.classifier(fused)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-23T16:18:20.626249Z","iopub.execute_input":"2026-02-23T16:18:20.626516Z","iopub.status.idle":"2026-02-23T16:18:20.638681Z","shell.execute_reply.started":"2026-02-23T16:18:20.626485Z","shell.execute_reply":"2026-02-23T16:18:20.638088Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"EPOCHS = 25\nBATCH_SIZE = 8\n\nbest_scores = []\n\nfor fold in range(5):\n\n    print(f\"\\n===== FOLD {fold} =====\")\n\n    train_ds = MultiModalDataset(df,fold,True)\n    val_ds   = MultiModalDataset(df,fold,False)\n\n    train_loader = DataLoader(train_ds,BATCH_SIZE,shuffle=True,num_workers=2)\n    val_loader   = DataLoader(val_ds,BATCH_SIZE,shuffle=False,num_workers=2)\n\n    model = FusionNet().to(device)\n\n    optimizer = torch.optim.AdamW(model.parameters(),lr=3e-4,weight_decay=1e-4)\n    scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer,EPOCHS)\n    criterion = nn.CrossEntropyLoss(label_smoothing=0.1)\n    scaler = GradScaler()\n\n    best_f1 = 0\n    patience = 5\n    wait = 0\n\n    for epoch in range(EPOCHS):\n\n        model.train()\n\n        for rgb,ms,hs,y in train_loader:\n\n            rgb,ms,hs,y = rgb.to(device),ms.to(device),hs.to(device),y.to(device)\n\n            optimizer.zero_grad()\n\n            with autocast():\n                loss = criterion(model(rgb,ms,hs),y)\n\n            scaler.scale(loss).backward()\n            torch.nn.utils.clip_grad_norm_(model.parameters(),1.0)\n            scaler.step(optimizer)\n            scaler.update()\n\n        scheduler.step()\n\n        # Validation\n        model.eval()\n        preds,targets = [],[]\n\n        with torch.no_grad():\n            for rgb,ms,hs,y in val_loader:\n                out = model(rgb.to(device),ms.to(device),hs.to(device))\n                preds += out.argmax(1).cpu().tolist()\n                targets += y.tolist()\n\n        f1 = f1_score(targets,preds,average=\"macro\")\n        print(f\"Epoch {epoch+1} | F1={f1:.4f}\")\n\n        if f1 > best_f1:\n            best_f1 = f1\n            wait = 0\n            torch.save(model.state_dict(),f\"fold{fold}.pth\")\n        else:\n            wait += 1\n            if wait >= patience:\n                print(\"Early stopping\")\n                break\n\n    best_scores.append(best_f1)\n\nprint(\"CV Mean F1:\", np.mean(best_scores))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-23T16:18:20.639413Z","iopub.execute_input":"2026-02-23T16:18:20.639665Z","iopub.status.idle":"2026-02-23T16:22:26.068742Z","shell.execute_reply.started":"2026-02-23T16:18:20.639636Z","shell.execute_reply":"2026-02-23T16:22:26.067912Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"VAL_PATH = \"/kaggle/input/competitions/beyond-visible-spectrum-ai-for-agriculture-2026/Kaggle_Prepared/val\"\n\nval_ids = sorted([\n    f for f in os.listdir(f\"{VAL_PATH}/HS\")\n    if re.fullmatch(r\"val_[0-9a-f]{8}\\.tif\", f)\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-23T16:22:58.483142Z","iopub.execute_input":"2026-02-23T16:22:58.483435Z","iopub.status.idle":"2026-02-23T16:22:58.488305Z","shell.execute_reply.started":"2026-02-23T16:22:58.483408Z","shell.execute_reply":"2026-02-23T16:22:58.487688Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class TestDataset(Dataset):\n    def __init__(self, root, ids):\n        self.root=root\n        self.ids=ids\n\n    def __len__(self):\n        return len(self.ids)\n\n    def __getitem__(self,i):\n        name=self.ids[i]\n\n        rgb=torch.tensor(\n            load_rgb(f\"{self.root}/RGB/{name.replace('.tif','.png')}\")\n        ).permute(2,0,1).float()\n\n        ms=tiff.imread(f\"{self.root}/MS/{name}\")\n        indices=compute_indices(ms)\n        ms=np.concatenate([ms,indices],axis=-1)\n        ms=torch.tensor(ms).permute(2,0,1).float()\n\n        hs=load_hs_clean(f\"{self.root}/HS/{name}\")\n        hs=torch.tensor(hs).permute(2,0,1).float()\n\n        return name,rgb,ms,hs","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-23T16:22:26.077672Z","iopub.execute_input":"2026-02-23T16:22:26.077947Z","iopub.status.idle":"2026-02-23T16:22:26.090999Z","shell.execute_reply.started":"2026-02-23T16:22:26.077914Z","shell.execute_reply":"2026-02-23T16:22:26.090362Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"loader = DataLoader(TestDataset(VAL_PATH,val_ids),8,False)\n\nmodels=[]\nfor fold in range(5):\n    m=FusionNet().to(device)\n    m.load_state_dict(torch.load(f\"fold{fold}.pth\"))\n    m.eval()\n    models.append(m)\n\ninv={0:\"Health\",1:\"Other\",2:\"Rust\"}\nrows=[]\n\nwith torch.no_grad():\n    for names,rgb,ms,hs in loader:\n\n        rgb,ms,hs=rgb.to(device),ms.to(device),hs.to(device)\n\n        logits=0\n        for m in models:\n            logits += m(rgb,ms,hs)\n\n        logits/=5\n        preds=logits.argmax(1).cpu().tolist()\n\n        for n,p in zip(names,preds):\n            rows.append((n,inv[p]))\n\nsub=pd.DataFrame(rows,columns=[\"Id\",\"Category\"])\nsub.to_csv(\"submission.csv\",index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-23T16:22:26.092495Z","iopub.execute_input":"2026-02-23T16:22:26.092769Z","iopub.status.idle":"2026-02-23T16:22:40.780486Z","shell.execute_reply.started":"2026-02-23T16:22:26.092748Z","shell.execute_reply":"2026-02-23T16:22:40.779718Z"}},"outputs":[],"execution_count":null}]}