nextgenyeild-api / experiments /evaluate_external_realistic.py
Hassan132's picture
Deploy NextGenYeild API to Hugging Face Spaces
c54c1bf
Raw History Blame Contribute Delete
13.9 kB
"""
NextGenYeild - Phase 6: Realistic & Out-of-Distribution Field Evaluation
========================================================================
Evaluates the trained linear probe head (nextgenyeild_wgsp_head_v1.pth) on top of
frozen FoMo4Wheat ViT-B/14 representations across:
1. WGSP-Smartphone-Data: Handheld mobile photography across all 6 stages.
2. Pakistani Field Imagery (Kaggle Peshawar Dataset): Natural field conditions,
local soil backgrounds, early vegetative weeks, and weed presence diagnostics.
"""
import os
import sys
import argparse
import json
import time
from pathlib import Path
from PIL import Image
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, Dataset
from torchvision.datasets import ImageFolder
from tqdm import tqdm
import numpy as np
from sklearn.metrics import classification_report, confusion_matrix, f1_score, accuracy_score
PROJECT_ROOT = Path(__file__).resolve().parent.parent
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
from FoMo4Wheat.models.vision_transformer import vit_base
from FoMo4Wheat.data.transforms import make_classification_eval_transform
from experiments.train_classifier import GrowthStageLinearHead, CLASSES
STAGE_NAMES = [
"0_tillering",
"1_jointing",
"2_booting",
"3_anthesis",
"4_grain_filling",
"5_maturity"
]
def load_pipeline(backbone_path: Path, head_path: Path, device: torch.device):
"""Loads aligned frozen FoMo4Wheat ViT backbone and trained linear head."""
if not backbone_path.exists():
raise FileNotFoundError(f"Backbone checkpoint missing: {backbone_path}")
if not head_path.exists():
raise FileNotFoundError(f"Linear head checkpoint missing: {head_path}")
# Backbone
backbone = vit_base(
patch_size=14,
img_size=518,
init_values=1.0,
ffn_layer="swiglu",
block_chunks=4,
num_register_tokens=4,
)
raw_obj = torch.load(str(backbone_path), map_location="cpu", weights_only=False)
sd = raw_obj.state_dict() if isinstance(raw_obj, torch.nn.Module) else raw_obj
if isinstance(sd, dict) and "teacher" in sd:
sd = sd["teacher"]
clean_sd = {k.replace("module.", "").replace("backbone.", ""): v for k, v in sd.items()}
backbone.load_state_dict(clean_sd, strict=True)
for p in backbone.parameters():
p.requires_grad = False
backbone = backbone.to(device).half()
backbone.eval()
# Head
checkpoint = torch.load(str(head_path), map_location=device, weights_only=False)
head = GrowthStageLinearHead(in_features=1536, num_classes=6).to(device)
head.load_state_dict(checkpoint["state_dict"])
head.eval()
return backbone, head, checkpoint
class CustomImageDataset(Dataset):
"""Dataset for arbitrary folder of images with transform."""
def __init__(self, image_paths: list[Path], transform=None):
self.image_paths = image_paths
self.transform = transform
def __len__(self):
return len(self.image_paths)
def __getitem__(self, idx):
path = self.image_paths[idx]
try:
img = Image.open(path).convert("RGB")
if self.transform:
img = self.transform(img)
return img, str(path), True
except Exception as e:
# Return dummy tensor if corrupted
dummy = torch.zeros(3, 518, 518)
return dummy, str(path), False
def extract_features_and_predict(images: torch.Tensor, backbone: nn.Module, head: nn.Module):
"""Infers logits and probabilities for a batch of images."""
feats_dict = backbone.forward_features(images)
cls_tok = feats_dict["x_norm_clstoken"]
patch_toks = feats_dict["x_norm_patchtokens"]
mean_patch = torch.mean(patch_toks, dim=1)
pooled = torch.cat([cls_tok, mean_patch], dim=-1).float()
logits = head(pooled)
probs = F.softmax(logits, dim=-1)
return logits, probs
def evaluate_stage_dataset(dataset_dir: Path, backbone: nn.Module, head: nn.Module, device: torch.device, batch_size: int = 32):
"""Evaluates an ImageFolder dataset structured across 6 growth stages."""
print(f"\n==================================================================")
print(f"EVALUATING 6-STAGE DATASET: {dataset_dir.name}")
print(f"Path: {dataset_dir}")
print(f"==================================================================")
transform = make_classification_eval_transform(resize_size=518, crop_size=518)
dataset = ImageFolder(str(dataset_dir), transform=transform)
loader = DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=2)
all_preds = []
all_labels = []
all_confs = []
all_probs = []
start_time = time.time()
with torch.no_grad():
for images, labels in tqdm(loader, desc=f"Evaluating {dataset_dir.name}"):
images = images.to(device).half()
_, probs = extract_features_and_predict(images, backbone, head)
confs, preds = torch.max(probs, dim=-1)
all_preds.extend(preds.cpu().numpy())
all_labels.extend(labels.numpy())
all_confs.extend(confs.cpu().numpy())
all_probs.extend(probs.cpu().numpy())
total_time = time.time() - start_time
acc = accuracy_score(all_labels, all_preds)
macro_f1 = f1_score(all_labels, all_preds, average="macro")
weighted_f1 = f1_score(all_labels, all_preds, average="weighted")
all_confs = np.array(all_confs)
print("\n" + "=" * 65)
print(f"RESULTS FOR {dataset_dir.name}:")
print(f" • Total Images : {len(all_labels):,}")
print(f" • Top-1 Accuracy : {acc * 100:.2f}%")
print(f" • Macro F1-Score : {macro_f1:.4f}")
print(f" • Weighted F1-Score : {weighted_f1:.4f}")
print(f" • Mean Confidence : {all_confs.mean() * 100:.2f}% (Std: {all_confs.std() * 100:.2f}%)")
print(f" • High Conf (>= 85%) : {(all_confs >= 0.85).mean() * 100:.1f}%")
print(f" • Low Conf (< 60%) : {(all_confs < 0.60).mean() * 100:.1f}%")
print(f" • Total Latency : {total_time:.2f}s ({total_time / len(all_labels) * 1000:.1f} ms/image)")
print("=" * 65)
print("\nPer-Class Breakdown:")
report_dict = classification_report(all_labels, all_preds, target_names=dataset.classes, output_dict=True)
report_text = classification_report(all_labels, all_preds, target_names=dataset.classes, digits=4)
print(report_text)
cm = confusion_matrix(all_labels, all_preds)
col_title = "True \\ Pred"
header = f"{col_title:18s}" + "".join([f"{c[:10]:>11s}" for c in dataset.classes])
print(header)
print("-" * len(header))
for idx, row in enumerate(cm):
row_str = "".join([f"{val:11d}" for val in row])
print(f"{dataset.classes[idx]:18s}{row_str}")
print("=" * 65)
return {
"dataset_name": dataset_dir.name,
"dataset_path": str(dataset_dir),
"total_images": len(all_labels),
"accuracy": float(acc),
"macro_f1": float(macro_f1),
"weighted_f1": float(weighted_f1),
"mean_confidence": float(all_confs.mean()),
"confidence_std": float(all_confs.std()),
"high_confidence_pct": float((all_confs >= 0.85).mean() * 100),
"low_confidence_pct": float((all_confs < 0.60).mean() * 100),
"confusion_matrix": cm.tolist(),
"classification_report": report_dict,
"latency_ms_per_image": float(total_time / len(all_labels) * 1000),
}
def evaluate_unlabeled_field_folder(folder_path: Path, category_name: str, backbone: nn.Module, head: nn.Module, device: torch.device, batch_size: int = 32):
"""Evaluates an arbitrary field image folder (e.g. Peshawar Wheat or Weeds)."""
valid_exts = {".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG"}
image_paths = sorted([p for p in folder_path.rglob("*") if p.is_file() and p.suffix in valid_exts])
if not image_paths:
print(f"No valid images found in {folder_path}")
return None
print(f"\n==================================================================")
print(f"EVALUATING FIELD FOLDER: {category_name} ({len(image_paths):,} images)")
print(f"Path: {folder_path}")
print(f"==================================================================")
transform = make_classification_eval_transform(resize_size=518, crop_size=518)
dataset = CustomImageDataset(image_paths, transform=transform)
loader = DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=2)
pred_counts = {stage: 0 for stage in STAGE_NAMES}
confs = []
confs_by_stage = {stage: [] for stage in STAGE_NAMES}
start_time = time.time()
with torch.no_grad():
for images, paths, valids in tqdm(loader, desc=f"Inferring {category_name}"):
if isinstance(valids, torch.Tensor):
valid_mask = valids.bool()
else:
valid_mask = torch.tensor(valids, dtype=torch.bool)
if not valid_mask.any():
continue
images = images[valid_mask].to(device).half()
_, probs = extract_features_and_predict(images, backbone, head)
batch_confs, batch_preds = torch.max(probs, dim=-1)
for p, c in zip(batch_preds.cpu().numpy(), batch_confs.cpu().numpy()):
stage = STAGE_NAMES[p]
pred_counts[stage] += 1
confs.append(float(c))
confs_by_stage[stage].append(float(c))
total = len(confs)
confs = np.array(confs)
print("\n" + "=" * 65)
print(f"PREDICTED STAGE DISTRIBUTION FOR {category_name}:")
print(f" • Total Images Evaluated : {total:,}")
print(f" • Overall Mean Conf : {confs.mean()*100:.2f}% (Std: {confs.std()*100:.2f}%)")
print(f" • High Conf (>= 85%) : {(confs >= 0.85).mean()*100:.1f}%")
print(f" • Low Conf (< 60%) : {(confs < 0.60).mean()*100:.1f}%")
print("-" * 65)
print("Stage Distribution:")
for stage in STAGE_NAMES:
cnt = pred_counts[stage]
pct = (cnt / total) * 100 if total > 0 else 0
avg_c = np.mean(confs_by_stage[stage])*100 if cnt > 0 else 0
bar = "█" * int(pct / 2.5)
print(f" {stage:16s} : {cnt:5d} ({pct:5.1f}%) | Mean Conf: {avg_c:5.1f}% | {bar}")
print("=" * 65)
return {
"category_name": category_name,
"folder_path": str(folder_path),
"total_images": total,
"stage_distribution": pred_counts,
"stage_percentages": {s: (pred_counts[s]/total)*100 for s in STAGE_NAMES},
"mean_confidence": float(confs.mean()),
"confidence_std": float(confs.std()),
"high_confidence_pct": float((confs >= 0.85).mean()*100),
"low_confidence_pct": float((confs < 0.60).mean()*100),
}
def main():
parser = argparse.ArgumentParser(description="Evaluate NextGenYeild Model on Realistic External Datasets (Phase 6)")
parser.add_argument("--backbone", type=str, default="weight/FoMo4Wheat_base.pth")
parser.add_argument("--head", type=str, default="weight/nextgenyeild_wgsp_head_v1.pth")
parser.add_argument("--smartphone-dir", type=str, default="data/external/smartphone")
parser.add_argument("--peshawar-dir", type=str, default="data/external/peshawar")
parser.add_argument("--output-json", type=str, default="data/external/phase6_evaluation_results.json")
parser.add_argument("--batch-size", type=int, default=32)
args = parser.parse_args()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Executing Phase 6 Evaluation on device: {device}")
backbone_path = PROJECT_ROOT / args.backbone
head_path = PROJECT_ROOT / args.head
backbone, head, meta = load_pipeline(backbone_path, head_path, device)
print(f"Loaded Head Checkpoint: {meta.get('model_version', 'fomo4wheat-wgsp-v1')}")
results = {
"model_version": meta.get("model_version", "fomo4wheat-wgsp-v1"),
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
"evaluations": {}
}
# 1. Benchmark on Mobile Photography (WGSP-Smartphone-Data)
sp_dir = PROJECT_ROOT / args.smartphone_dir
# Check if stage subfolders exist
has_stages = all((sp_dir / stage).exists() for stage in STAGE_NAMES)
if has_stages:
print("\n>>> Running Smartphone Evaluation (WGSP-Smartphone-Data)...")
sp_res = evaluate_stage_dataset(sp_dir, backbone, head, device, args.batch_size)
results["evaluations"]["wgsp_smartphone"] = sp_res
else:
print(f"\n[INFO] Smartphone directory {sp_dir} does not yet have all 6 stage folders. Skipping.")
# 2. Pakistani Field Domain Testing (Peshawar Dataset)
pesh_dir = PROJECT_ROOT / args.peshawar_dir
wheat_dir = pesh_dir / "wheat"
weeds_dir = pesh_dir / "weeds"
if wheat_dir.exists() and any(wheat_dir.iterdir()):
print("\n>>> Running Pakistani Field Evaluation (Peshawar Wheat)...")
wheat_res = evaluate_unlabeled_field_folder(wheat_dir, "Pakistani Field Wheat (Peshawar)", backbone, head, device, args.batch_size)
results["evaluations"]["peshawar_wheat"] = wheat_res
if weeds_dir.exists() and any(weeds_dir.iterdir()):
print("\n>>> Running Pakistani Field Evaluation (Peshawar Weeds Diagnostics)...")
weed_res = evaluate_unlabeled_field_folder(weeds_dir, "Pakistani Field Weeds (Diagnostics)", backbone, head, device, args.batch_size)
results["evaluations"]["peshawar_weeds"] = weed_res
out_file = PROJECT_ROOT / args.output_json
out_file.parent.mkdir(parents=True, exist_ok=True)
with open(out_file, "w") as f:
json.dump(results, f, indent=2)
print(f"\nPhase 6 Evaluation Summary saved to: {out_file}")
if __name__ == "__main__":
main()