#!/usr/bin/env python3 import os, gc, json, math, argparse from pathlib import Path import numpy as np import pandas as pd from PIL import Image import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader from torchvision import transforms as T from torchvision.transforms import InterpolationMode import timm from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, classification_report PROJECT_DIR = Path(os.environ.get("PROJECT_DIR", "/kaggle/working/plantvillage_t4x2")) SPLIT_DIR = PROJECT_DIR / "splits" RUN_DIR = PROJECT_DIR / "runs" ENSEMBLE_DIR = PROJECT_DIR / "ensemble" OUT_DIR = PROJECT_DIR / "test_predictions" OUT_DIR.mkdir(parents=True, exist_ok=True) IMG_SIZE = 224 BATCH_SIZE = int(os.environ.get("TEST_BATCH_SIZE", "64")) NUM_WORKERS = int(os.environ.get("NUM_WORKERS", "2")) MEAN = (0.485, 0.456, 0.406) STD = (0.229, 0.224, 0.225) EXPERIMENTS = [ ("convnext", "color"), ("convnext", "segmented"), ("effnet", "color"), ("effnet", "segmented"), ] def ensure_hwc3(arr): arr = np.asarray(arr) if arr.ndim == 2: arr = np.repeat(arr[..., None], 3, axis=-1) elif arr.ndim == 3: if arr.shape[-1] == 4: arr = arr[..., :3] elif arr.shape[-1] == 1: arr = np.repeat(arr, 3, axis=-1) elif arr.shape[-1] != 3 and arr.shape[0] in (1, 3, 4): arr = np.transpose(arr, (1, 2, 0)) if arr.shape[-1] == 4: arr = arr[..., :3] if arr.shape[-1] == 1: arr = np.repeat(arr, 3, axis=-1) else: raise ValueError(f"Unsupported shape: {arr.shape}") if arr.dtype != np.uint8: if arr.max() <= 1.5: arr = arr * 255.0 arr = np.clip(arr, 0, 255).astype(np.uint8) return np.ascontiguousarray(arr) class LeafDataset(Dataset): def __init__(self, manifest_csv, representation): self.df = pd.read_csv(manifest_csv) self.rep = representation self.path_col = f"{representation}_path" self.tf = T.Compose([ T.Resize((IMG_SIZE, IMG_SIZE), interpolation=InterpolationMode.BILINEAR), T.ToTensor(), T.Normalize(MEAN, STD), ]) self.maps = {} def __len__(self): return len(self.df) def _map(self, p): if p not in self.maps: self.maps[p] = np.load(p, mmap_mode="r") return self.maps[p] def __getitem__(self, i): r = self.df.iloc[i] arr = self._map(r[self.path_col])[int(r["sample_idx"])] img = Image.fromarray(ensure_hwc3(np.array(arr, copy=True))) return self.tf(img), int(r["label"]), i class ECALayer(nn.Module): def __init__(self, channels, gamma=2, b=1): super().__init__() t = int(abs((math.log2(channels) + b) / gamma)) k = t if t % 2 else t + 1 k = max(3, k) self.avg = nn.AdaptiveAvgPool2d(1) self.conv = nn.Conv1d(1, 1, kernel_size=k, padding=(k-1)//2, bias=False) def forward(self, x): y = self.avg(x).squeeze(-1).transpose(-1, -2) y = self.conv(y).transpose(-1, -2).unsqueeze(-1) return x * torch.sigmoid(y).expand_as(x) class CBAM(nn.Module): def __init__(self, channels, reduction=16): super().__init__() hidden = max(8, channels // reduction) self.mlp = nn.Sequential( nn.Conv2d(channels, hidden, 1, bias=False), nn.ReLU(inplace=True), nn.Conv2d(hidden, channels, 1, bias=False), ) self.spatial = nn.Conv2d(2, 1, 7, padding=3, bias=False) def forward(self, x): ch = torch.sigmoid( self.mlp(F.adaptive_avg_pool2d(x, 1)) + self.mlp(F.adaptive_max_pool2d(x, 1)) ) x = x * ch sp = torch.sigmoid(self.spatial(torch.cat( [x.mean(1, keepdim=True), x.amax(1, keepdim=True)], dim=1 ))) return x * sp class GeM(nn.Module): def __init__(self, p=3.0, eps=1e-6): super().__init__() self.p = nn.Parameter(torch.ones(1) * p) self.eps = eps def forward(self, x): p = self.p.clamp(1.0, 8.0) x = F.relu(x).clamp(min=self.eps).pow(p) return F.adaptive_avg_pool2d(x, 1).pow(1.0 / p).flatten(1) class PlantDiseaseModel(nn.Module): def __init__(self, backbone, num_classes): super().__init__() timm_name = "convnext_tiny" if backbone == "convnext" else "efficientnet_b0" self.backbone = timm.create_model(timm_name, pretrained=False, features_only=True) c = self.backbone.feature_info.channels()[-1] self.attention = ECALayer(c) if backbone == "convnext" else CBAM(c) self.pool = GeM() hidden = min(512, c) self.head = nn.Sequential( nn.Linear(c, hidden), nn.BatchNorm1d(hidden), nn.ReLU(inplace=True), nn.Dropout(0.30), nn.Linear(hidden, num_classes), ) def forward(self, x): x = self.backbone(x)[-1] x = self.attention(x) x = self.pool(x) return self.head(x) def ckpt_path(backbone, rep): return RUN_DIR / f"{backbone}_{rep}" / "best.pt" def load_model(backbone, rep, device): p = ckpt_path(backbone, rep) if not p.exists(): raise FileNotFoundError(f"Missing checkpoint: {p}") ck = torch.load(p, map_location="cpu", weights_only=False) model = PlantDiseaseModel(backbone, int(ck["num_classes"])) model.load_state_dict(ck["model"], strict=True) model.to(device).eval() return model, ck @torch.no_grad() def predict(backbone, rep, split="test"): manifest = SPLIT_DIR / split / "manifest.csv" if not manifest.exists(): raise FileNotFoundError( f"Missing manifest: {manifest}\nRun training script --mode prepare first." ) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") ds = LeafDataset(manifest, rep) loader = DataLoader( ds, batch_size=BATCH_SIZE, shuffle=False, num_workers=NUM_WORKERS, pin_memory=torch.cuda.is_available() ) model, ck = load_model(backbone, rep, device) probs, ys, idxs = [], [], [] for x, y, idx in loader: x = x.to(device, non_blocking=True) with torch.cuda.amp.autocast(enabled=device.type == "cuda"): logits = model(x) probs.append(torch.softmax(logits.float(), 1).cpu().numpy()) ys.append(y.numpy()) idxs.extend(idx.tolist()) del model gc.collect() if torch.cuda.is_available(): torch.cuda.empty_cache() return np.concatenate(probs), np.concatenate(ys), np.asarray(idxs), ck, ds.df def metrics(y, probs): pred = probs.argmax(1) return { "accuracy": float(accuracy_score(y, pred)), "macro_f1": float(f1_score(y, pred, average="macro", zero_division=0)), "weighted_f1": float(f1_score(y, pred, average="weighted", zero_division=0)), "macro_precision": float(precision_score(y, pred, average="macro", zero_division=0)), "macro_recall": float(recall_score(y, pred, average="macro", zero_division=0)), } def save_predictions(name, probs, y, idx, ck, manifest_df): order = np.argsort(idx) probs, y = probs[order], y[order] pred = probs.argmax(1) class_names = ck["class_names"] d = OUT_DIR / name d.mkdir(parents=True, exist_ok=True) m = metrics(y, probs) (d / "metrics.json").write_text(json.dumps(m, indent=2), encoding="utf-8") report = classification_report( y, pred, target_names=class_names, output_dict=True, zero_division=0 ) pd.DataFrame(report).T.to_csv(d / "classification_report.csv") out = manifest_df.iloc[order].reset_index(drop=True).copy() out["pred_label"] = pred out["pred_class"] = [class_names[i] for i in pred] out["confidence"] = probs.max(1) out["correct"] = (pred == y).astype(int) out.to_csv(d / "predictions.csv", index=False) np.save(d / "probabilities.npy", probs) print(name, json.dumps(m, indent=2)) return m def test_all_models(): rows = [] for backbone, rep in EXPERIMENTS: p = ckpt_path(backbone, rep) if not p.exists(): print("[SKIP]", p) continue probs, y, idx, ck, df = predict(backbone, rep) m = save_predictions(f"{backbone}_{rep}", probs, y, idx, ck, df) rows.append({"backbone": backbone, "representation": rep, **m}) if not rows: raise RuntimeError("No best.pt checkpoints found.") summary = pd.DataFrame(rows).sort_values( ["macro_f1", "accuracy"], ascending=False ) summary.to_csv(OUT_DIR / "all_models_test_summary.csv", index=False) print(summary.to_string(index=False)) def test_saved_ensemble(): cfg_path = ENSEMBLE_DIR / "ensemble_config.json" if not cfg_path.exists(): raise FileNotFoundError( f"Missing ensemble config: {cfg_path}\n" "Run training script --mode ensemble first." ) cfg = json.loads(cfg_path.read_text()) cr = cfg["convnext"]["representation"] er = cfg["effnet"]["representation"] ac = float(cfg["alpha_convnext"]) ae = float(cfg["alpha_effnet"]) pc, yc, ic, cck, cdf = predict("convnext", cr) pe, ye, ie, eck, edf = predict("effnet", er) oc, oe = np.argsort(ic), np.argsort(ie) if not np.array_equal(ic[oc], ie[oe]): raise RuntimeError("Row indices do not align.") if not np.array_equal(yc[oc], ye[oe]): raise RuntimeError("Labels do not align.") pc, pe, y = pc[oc], pe[oe], yc[oc] pf = ac * pc + ae * pe fake_ck = {"class_names": cck["class_names"]} m = save_predictions("ensemble", pf, y, np.arange(len(y)), fake_ck, cdf.iloc[oc].reset_index(drop=True)) result = { "convnext_representation": cr, "effnet_representation": er, "alpha_convnext": ac, "alpha_effnet": ae, **m, } (OUT_DIR / "ensemble" / "ensemble_metrics_full.json").write_text( json.dumps(result, indent=2), encoding="utf-8" ) def main(): ap = argparse.ArgumentParser() ap.add_argument("--mode", required=True, choices=["all-models", "ensemble", "predict-one"]) ap.add_argument("--backbone", choices=["convnext", "effnet"]) ap.add_argument("--representation", choices=["color", "segmented"]) args = ap.parse_args() if args.mode == "all-models": test_all_models() elif args.mode == "ensemble": test_saved_ensemble() else: if not args.backbone or not args.representation: raise ValueError("--backbone and --representation are required.") probs, y, idx, ck, df = predict(args.backbone, args.representation) save_predictions(f"{args.backbone}_{args.representation}", probs, y, idx, ck, df) if __name__ == "__main__": main()