Download experiments/evaluate_classifier.py from dormant78612/nextgenyeild-api: direct link, hf CLI and curl.
- Browser
- Download file 8.9 kB
-
https://huggingface.co/spaces/dormant78612/nextgenyeild-api/resolve/main/experiments/evaluate_classifier.py
- Command line
-
hf download hf://spaces/dormant78612/nextgenyeild-api/experiments/evaluate_classifier.py
-
curl -L -o evaluate_classifier.py https://huggingface.co/spaces/dormant78612/nextgenyeild-api/resolve/main/experiments/evaluate_classifier.py
8.9 kB
| import os | |
| import sys | |
| import argparse | |
| import json | |
| 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 | |
| from torchvision.datasets import ImageFolder | |
| from tqdm import tqdm | |
| from sklearn.metrics import classification_report, confusion_matrix, f1_score, accuracy_score | |
| # Ensure project root is in sys.path | |
| 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.utils.utils import load_pretrained_weights | |
| from FoMo4Wheat.data.transforms import make_classification_eval_transform | |
| from experiments.train_classifier import GrowthStageLinearHead, CLASSES | |
| STAGE_DESCRIPTIONS = { | |
| "0_tillering": "Early vegetative growth; multiple side shoots developing from base.", | |
| "1_jointing": "Stem elongation begins; first node detectable above soil.", | |
| "2_booting": "Flag leaf sheath swelling as the wheat spike develops inside.", | |
| "3_anthesis": "Flowering stage; yellow anthers extruded, pollination underway.", | |
| "4_grain_filling": "Kernel development (milk to dough stages); green turns pale.", | |
| "5_maturity": "Crop fully ripe; grain hard, golden-brown canopy ready for harvest.", | |
| } | |
| def load_pipeline(backbone_path: Path, head_path: Path, device: torch.device): | |
| """Loads frozen FoMo4Wheat ViT backbone and trained linear head.""" | |
| if not backbone_path.exists(): | |
| raise FileNotFoundError(f"Backbone weights not found: {backbone_path}") | |
| if not head_path.exists(): | |
| raise FileNotFoundError(f"Head checkpoint not found: {head_path}") | |
| # 1. 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 param in backbone.parameters(): | |
| param.requires_grad = False | |
| backbone = backbone.to(device).half() | |
| backbone.eval() | |
| # 2. Linear Head | |
| checkpoint = torch.load(head_path, map_location=device, weights_only=False) | |
| in_features = checkpoint.get("in_features", 1536) | |
| num_classes = checkpoint.get("num_classes", 6) | |
| head = GrowthStageLinearHead(in_features=in_features, num_classes=num_classes).to(device) | |
| head.load_state_dict(checkpoint["state_dict"]) | |
| head.eval() | |
| return backbone, head, checkpoint | |
| def predict_single_image( | |
| image_path: Path, | |
| backbone: nn.Module, | |
| head: nn.Module, | |
| device: torch.device, | |
| ): | |
| """Performs inference on a single image and returns probabilities and predicted stage.""" | |
| transform = make_classification_eval_transform(resize_size=518, crop_size=518) | |
| img = Image.open(image_path).convert("RGB") | |
| tensor = transform(img).unsqueeze(0).to(device).half() | |
| with torch.no_grad(): | |
| feats_dict = backbone.forward_features(tensor) | |
| 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).squeeze(0).cpu().numpy() | |
| top_idx = int(probs.argmax()) | |
| top_stage = CLASSES[top_idx] | |
| confidence = float(probs[top_idx]) | |
| result = { | |
| "image_path": str(image_path), | |
| "predicted_stage": top_stage, | |
| "confidence": confidence, | |
| "stage_description": STAGE_DESCRIPTIONS.get(top_stage, ""), | |
| "stage_probabilities": {CLASSES[i]: float(probs[i]) for i in range(len(CLASSES))}, | |
| } | |
| return result | |
| def evaluate_folder( | |
| dataset_dir: Path, | |
| backbone: nn.Module, | |
| head: nn.Module, | |
| batch_size: int, | |
| device: torch.device, | |
| ): | |
| """Evaluates pipeline across an ImageFolder structured directory.""" | |
| 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 = [] | |
| print(f"\nEvaluating folder: {dataset_dir} ({len(dataset):,} images)...") | |
| with torch.no_grad(): | |
| for images, labels in tqdm(loader, desc="Inference"): | |
| images = images.to(device).half() | |
| 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) | |
| preds = torch.argmax(logits, dim=-1).cpu().numpy() | |
| all_preds.extend(preds) | |
| all_labels.extend(labels.numpy()) | |
| 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") | |
| print("\n" + "=" * 65) | |
| print(f"EVALUATION SUMMARY ({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 : {weighted_f1:.4f}") | |
| print("=" * 65) | |
| print("\nPer-Class Classification Report:") | |
| report = classification_report(all_labels, all_preds, target_names=dataset.classes, digits=4) | |
| print(report) | |
| 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 { | |
| "folder": str(dataset_dir), | |
| "total": len(all_labels), | |
| "accuracy": float(acc), | |
| "macro_f1": float(macro_f1), | |
| "weighted_f1": float(weighted_f1), | |
| "confusion_matrix": cm.tolist(), | |
| "report": report, | |
| } | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Evaluate NextGenYeild WGSP Growth-Stage Classifier") | |
| parser.add_argument("--backbone", type=str, default="weight/FoMo4Wheat_base.pth", help="Backbone checkpoint") | |
| parser.add_argument("--head", type=str, default="weight/nextgenyeild_wgsp_head_v1.pth", help="Linear head checkpoint") | |
| parser.add_argument("--eval-dir", type=str, default=None, help="Directory of images to evaluate (ImageFolder)") | |
| parser.add_argument("--image", type=str, default=None, help="Single image file for inference") | |
| parser.add_argument("--batch-size", type=int, default=32, help="Evaluation batch size") | |
| args = parser.parse_args() | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| 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 model version: {meta.get('model_version', 'fomo4wheat-wgsp-v1')}") | |
| if args.image: | |
| image_path = Path(args.image) | |
| if not image_path.exists(): | |
| image_path = PROJECT_ROOT / args.image | |
| if not image_path.exists(): | |
| raise FileNotFoundError(f"Image not found: {image_path}") | |
| result = predict_single_image(image_path, backbone, head, device) | |
| print("\n" + "=" * 60) | |
| print(f"SINGLE IMAGE PREDICTION: {image_path.name}") | |
| print(f" • Predicted Stage : {result['predicted_stage']} ({result['confidence']*100:.2f}% confidence)") | |
| print(f" • Description : {result['stage_description']}") | |
| print("\n Class Probabilities:") | |
| for stage, p in result["stage_probabilities"].items(): | |
| bar = "█" * int(p * 30) | |
| print(f" {stage:16s} : {p*100:6.2f}% | {bar}") | |
| print("=" * 60) | |
| elif args.eval_dir: | |
| eval_path = Path(args.eval_dir) | |
| evaluate_folder(eval_path, backbone, head, args.batch_size, device) | |
| else: | |
| # Default: evaluate on test set | |
| default_test = PROJECT_ROOT / "data" / "test" | |
| if default_test.exists(): | |
| evaluate_folder(default_test, backbone, head, args.batch_size, device) | |
| else: | |
| print("Please specify --image or --eval-dir") | |
| if __name__ == "__main__": | |
| main() | |