from pathlib import Path import numpy as np import yaml from ultralytics import YOLO WEIGHTS = Path("/media/rtx5090/Scripts/runs/detect/training_stats/reverse_study/All_minus_Intrinsics_merged/RTX5090/run_5/weights/best.pt") DATA = "/media/rtx5090/IRIS/Real_Test_Set/dataset.yaml" PROJECT = WEIGHTS.parent.parent / "evaluation" # Path to the ORIGINAL training dataset.yaml whose class mapping is suspected to be wrong. TRAIN_YAML = Path("/media/rtx5090/IRIS/Reverse_Ablation/All_minus_Intrinsics_merged/yolo/dataset.yaml") CORRECTED_YAML_OUT = TRAIN_YAML.parent / "dataset_corrected.yaml" def main(): PROJECT.mkdir(exist_ok=True) print(f"Evaluating {WEIGHTS}") model = YOLO(WEIGHTS) metrics = model.val( data=DATA, split="test", imgsz=1024, batch=16, device=0, workers=8, project=str(PROJECT), name=WEIGHTS.parent.parent.name, exist_ok=True, save_json=True, plots=True, verbose=True, ) box = metrics.box print("\nResults") print(f"mAP50 : {box.map50:.4f}") print(f"mAP50-95 : {box.map:.4f}") print(f"Precision : {box.mp:.4f}") print(f"Recall : {box.mr:.4f}") print(f"F1 : {box.f1.mean():.4f}") # --- Extract raw confusion matrix --- # Shape: (nc+1, nc+1). Rows = predicted, columns = true. Last row/col = background. cm = metrics.confusion_matrix.matrix names = metrics.names # dict {index: name}, from DATA yaml (test set) nc = len(names) if cm.shape[0] != nc + 1: raise ValueError( f"Unexpected confusion matrix shape {cm.shape} for nc={nc}. " "Aborting mapping inference; check Ultralytics version compatibility." ) np.save(PROJECT / WEIGHTS.parent.parent.name / "confusion_matrix_raw.npy", cm) print(f"\nRaw confusion matrix saved to {PROJECT / WEIGHTS.parent.parent.name / 'confusion_matrix_raw.npy'}") # --- Derive candidate mapping: for each TRUE class j, which class i is most often predicted? --- class_block = cm[:nc, :nc] # exclude background row/col predicted_for_true = np.argmax(class_block, axis=0) # length nc, index = predicted class confidence = np.max(class_block, axis=0) / (class_block.sum(axis=0) + 1e-9) # --- Check bijection --- unique, counts = np.unique(predicted_for_true, return_counts=True) is_bijection = len(unique) == nc and set(unique) == set(range(nc)) print("\nCandidate mapping (true_class -> predicted_class, confidence):") for j in range(nc): i = predicted_for_true[j] flag = "" if confidence[j] > 0.5 else " <-- LOW CONFIDENCE" print(f" {names[j]:<28s} -> {names[i]:<28s} (conf={confidence[j]:.2f}){flag}") if not is_bijection: collisions = {v: (unique[unique == v], np.where(predicted_for_true == v)[0]) for v in unique if counts[unique.tolist().index(v)] > 1} print("\nWARNING: mapping is not a valid bijection. The following predicted classes") print("receive votes from more than one true class, or some class received none:") for j in range(nc): if list(predicted_for_true).count(predicted_for_true[j]) > 1: print(f" true={names[j]} -> predicted={names[predicted_for_true[j]]} (collision)") print("\nDo not trust the auto-generated yaml below without manual review.") print("Recommend inspecting raw counts in confusion_matrix_raw.npy for ambiguous rows,") print("and cross-checking against rendered synthetic images for the classes involved.") # --- Build corrected names list --- # new_names[i] = name of the true class that training-index i actually represents new_names = [None] * nc for j in range(nc): i = predicted_for_true[j] new_names[i] = names[j] if any(n is None for n in new_names): unmapped = [idx for idx, n in enumerate(new_names) if n is None] print(f"\nWARNING: training indices with no inferred mapping: {unmapped}") print("These cannot be safely written. Inspect manually before using the corrected yaml.") # --- Write corrected yaml, preserving original structure --- with open(TRAIN_YAML) as f: train_yaml = yaml.safe_load(f) train_yaml["names"] = {i: (new_names[i] if new_names[i] is not None else f"UNRESOLVED_{i}") for i in range(nc)} with open(CORRECTED_YAML_OUT, "w") as f: yaml.dump(train_yaml, f, sort_keys=False, allow_unicode=True) print(f"\nCorrected dataset.yaml written to {CORRECTED_YAML_OUT}") print("This file is a candidate correction, not a verified one. Review before retraining.") if __name__ == "__main__": main()