Datasets:
Download scripts/evaluate_locked_test.py from ImtiazulIslam/bdfd9-v3-fabric-defect-classification: direct link, hf CLI and curl.
- Browser
- Download file 3.11 kB
-
https://huggingface.co/datasets/ImtiazulIslam/bdfd9-v3-fabric-defect-classification/resolve/main/scripts/evaluate_locked_test.py
- Command line
-
hf download hf://datasets/ImtiazulIslam/bdfd9-v3-fabric-defect-classification/scripts/evaluate_locked_test.py
-
curl -L -o evaluate_locked_test.py https://huggingface.co/datasets/ImtiazulIslam/bdfd9-v3-fabric-defect-classification/resolve/main/scripts/evaluate_locked_test.py
3.11 kB
| #!/usr/bin/env python3 | |
| """One-time final evaluation of the preselected model on the locked test split.""" | |
| from pathlib import Path | |
| import argparse, csv, json, sys | |
| import numpy as np | |
| import torch | |
| from torch.utils.data import DataLoader | |
| HERE=Path(__file__).resolve().parent | |
| ROOT=HERE.parent | |
| sys.path.insert(0,str(HERE)) | |
| from train_multilabel import CLASSES, FabricDataset, make_model, collect, scores, scores_by_fabric_type | |
| def main(): | |
| ap=argparse.ArgumentParser() | |
| ap.add_argument("--run-dir",required=True,help="Selected experiment directory under experiments/") | |
| ap.add_argument("--batch-size",type=int,default=32) | |
| ap.add_argument("--workers",type=int,default=4) | |
| ap.add_argument("--confirm-final-test",action="store_true",help="Explicitly confirm architecture and validation thresholds are frozen") | |
| a=ap.parse_args() | |
| if not a.confirm_final_test: raise SystemExit("Refusing test access: freeze model/threshold selection, then pass --confirm-final-test") | |
| run=Path(a.run_dir) | |
| if not run.is_absolute(): run=ROOT/"experiments"/run | |
| result_path=run/"results.json"; ckpt_path=run/"best_checkpoint.pt" | |
| if not result_path.is_file() or not ckpt_path.is_file(): raise SystemExit("Selected run must contain results.json and best_checkpoint.pt") | |
| result=json.loads(result_path.read_text()) | |
| if result.get("test_evaluation","").startswith("COMPLETED"): raise SystemExit("Test evaluation already exists; refusing a second look") | |
| device=torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| ck=torch.load(ckpt_path,map_location=device,weights_only=False) | |
| cfg=ck["args"] | |
| model=make_model(cfg["model"],len(CLASSES),pretrained=False).to(device) | |
| model.load_state_dict(ck["state_dict"]) | |
| test=FabricDataset("test",cfg["size"],False) | |
| loader=DataLoader(test,batch_size=a.batch_size,shuffle=False,num_workers=a.workers,pin_memory=device.type=="cuda",persistent_workers=a.workers>0) | |
| y,p,names=collect(model,loader,device) | |
| thresholds=np.asarray([result["thresholds_from_validation"][c] for c in CLASSES],dtype=np.float32) | |
| metrics=scores(y,p,thresholds) | |
| out={"model":cfg["model"],"seed":cfg["seed"],"checkpoint_epoch":ck["epoch"],"thresholds_from_validation":result["thresholds_from_validation"],"test_metrics_locked_final":metrics,"test_metrics_by_fabric_type":scores_by_fabric_type(y,p,thresholds,names),"test_samples":len(names),"warning":"Single final test evaluation after validation-only selection; do not use these results to revise model or thresholds."} | |
| (run/"locked_test_results.json").write_text(json.dumps(out,indent=2)) | |
| with open(run/"locked_test_predictions.csv","w",newline="") as f: | |
| w=csv.writer(f);w.writerow(["filename"]+[f"true_{c}" for c in CLASSES]+[f"prob_{c}" for c in CLASSES]) | |
| w.writerows([[name]+list(map(int,y[i]))+list(map(float,p[i])) for i,name in enumerate(names)]) | |
| result["test_evaluation"]="COMPLETED ONCE by evaluate_locked_test.py" | |
| result["test_metrics_locked_final"]=metrics | |
| result["test_metrics_by_fabric_type"]=out["test_metrics_by_fabric_type"] | |
| result_path.write_text(json.dumps(result,indent=2)) | |
| print(json.dumps(out,indent=2)) | |
| if __name__=="__main__": main() | |