File size: 4,911 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
from pathlib import Path
import numpy as np
import pandas as pd
from ultralytics import YOLO


ROOT = Path("/media/rtx5090/Scripts/runs/detect/training_stats/sota_study/SynthRender_Robotics/")
DATA = "/media/z4/DATASETS/SIM2REAL_ROBOTICS/yolo/dataset.yaml"

PROJECT = ROOT / "evaluation"
CSV_PATH = PROJECT / "evaluation_results.csv"

METRICS = [
    "mAP50",
    "mAP50_95",
    "precision",
    "recall",
    "f1",
]

# Bootstrap settings
N_BOOT = 10000
CI_LEVEL = 0.95
BOOT_SEED = 42


def summarize_group(group, metrics=METRICS, n_boot=N_BOOT, ci=CI_LEVEL, seed=BOOT_SEED):
    rng = np.random.default_rng(seed)
    out = {}
    for metric in metrics:
        data = group[metric].to_numpy(dtype=float)
        n = data.size

        out[(metric, "mean")] = data.mean()
        out[(metric, "std")] = data.std(ddof=1) if n > 1 else np.nan
        out[(metric, "min")] = data.min()
        out[(metric, "max")] = data.max()
        out[(metric, "n")] = n

        if n >= 2:
            idx = rng.integers(0, n, size=(n_boot, n))
            boot_means = data[idx].mean(axis=1)
            lo, hi = np.percentile(
                boot_means, [(1 - ci) / 2 * 100, (1 - (1 - ci) / 2) * 100]
            )
        else:
            lo, hi = np.nan, np.nan

        out[(metric, "ci_lo")] = lo
        out[(metric, "ci_hi")] = hi

    return pd.Series(out)


def main():

    PROJECT.mkdir(exist_ok=True)

    results = []

    # Structure:
    # ROOT/
    # ├── experiment/
    # │   ├── computer/
    # │   │   ├── run_1/
    # │   │   ├── run_2/

    for experiment_dir in sorted(ROOT.iterdir()):

        if not experiment_dir.is_dir():
            continue

        if experiment_dir.name == "evaluation":
            continue

        experiment = experiment_dir.name

        # Computer/workstation level
        for computer_dir in sorted(experiment_dir.iterdir()):

            if not computer_dir.is_dir():
                continue

            computer = computer_dir.name

            # Run level
            for run in sorted(computer_dir.glob("run_*")):

                if not run.is_dir():
                    continue

                weights = run / "weights" / "best.pt"

                if not weights.exists():
                    print(
                        f"Skipping {experiment}/{computer}/{run.name}: "
                        "best.pt not found"
                    )
                    continue

                print(
                    f"\nEvaluating "
                    f"{experiment} / {computer} / {run.name}"
                )

                try:
                    model = YOLO(weights)

                    metrics = model.val(
                        data=DATA,
                        split="test",
                        imgsz=512,
                        batch=28,
                        device=0,
                        workers=8,
                        project=str(PROJECT),
                        name=f"{experiment}_{computer}_{run.name}",
                        exist_ok=True,
                        save_json=True,
                        plots=True,
                        verbose=True,
                    )

                except Exception as e:
                    print(
                        f"Failed evaluating "
                        f"{experiment}/{computer}/{run.name}"
                    )
                    print(e)
                    continue

                box = metrics.box

                results.append(
                    {
                        "experiment": experiment,
                        "computer": computer,
                        "run": run.name,
                        "mAP50": float(box.map50),
                        "mAP50_95": float(box.map),
                        "precision": float(box.mp),
                        "recall": float(box.mr),
                        "f1": float(box.f1.mean()),
                    }
                )

    # Save per-run results
    df = pd.DataFrame(results)

    df.to_csv(CSV_PATH, index=False)

    print(f"\nSaved: {CSV_PATH}")

    if df.empty:
        print("No evaluation results found.")
        return

    # Statistics per experiment (mean, std, min, max, n, bootstrap CI)
    summary = df.groupby("experiment").apply(summarize_group)

    summary_path = PROJECT / "evaluation_summary.csv"

    summary.to_csv(summary_path)

    print(f"Saved: {summary_path}")

    print("\nSummary:")
    print(summary)

    # Statistics per experiment and computer (mean, std, min, max, n, bootstrap CI)
    computer_summary = (
        df.groupby(["experiment", "computer"])
        .apply(summarize_group)
    )

    computer_summary_path = PROJECT / "evaluation_summary_by_computer.csv"

    computer_summary.to_csv(computer_summary_path)

    print(f"\nSaved: {computer_summary_path}")


if __name__ == "__main__":
    main()