File size: 4,710 Bytes
fde6d70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
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()