Spaces:
Sleeping
Sleeping
File size: 6,623 Bytes
0506a57 | 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 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 | #!/usr/bin/env python
"""
Verify Aeon test results against expected ground truth.
This script reads the test results and compares them against the ground truth
values in test_samples.json to validate the Aeon model predictions.
Usage:
python verify_aeon_results.py \
--test-samples test_slides/test_samples.json \
--results-dir test_slides/results
"""
import argparse
import json
from pathlib import Path
import pandas as pd
from typing import Dict, List, Tuple
def load_test_samples(test_samples_file: Path) -> List[Dict]:
"""Load test samples from JSON file.
Args:
test_samples_file: Path to test_samples.json
Returns:
List of test sample dictionaries
"""
with open(test_samples_file) as f:
return json.load(f)
def load_aeon_results(slide_id: str, results_dir: Path) -> Tuple[str, float]:
"""Load Aeon prediction results for a slide.
Args:
slide_id: Slide identifier
results_dir: Directory containing results
Returns:
Tuple of (predicted_subtype, confidence)
"""
results_file = results_dir / slide_id / f"{slide_id}_aeon_results.csv"
if not results_file.exists():
raise FileNotFoundError(f"Results file not found: {results_file}")
df = pd.read_csv(results_file)
if df.empty:
raise ValueError(f"Empty results file: {results_file}")
# Get top prediction
top_prediction = df.iloc[0]
return top_prediction["Cancer Subtype"], top_prediction["Confidence"]
def verify_results(test_samples: List[Dict], results_dir: Path) -> Dict:
"""Verify all test results against ground truth.
Args:
test_samples: List of test sample dictionaries
results_dir: Directory containing results
Returns:
Dictionary with verification statistics
"""
total = len(test_samples)
passed = 0
failed = 0
results = []
print("=" * 80)
print("Aeon Model Verification Report")
print("=" * 80)
print()
for sample in test_samples:
slide_id = sample.get("slide_id") or sample.get("image_id")
ground_truth = sample.get("cancer_subtype") or sample.get("cancer_type")
site_type = sample["site_type"]
sex = sample["sex"]
tissue_site = sample["tissue_site"]
print(f"Slide: {slide_id}")
print(f" Ground Truth: {ground_truth}")
print(f" Site Type: {site_type}")
print(f" Sex: {sex}")
print(f" Tissue Site: {tissue_site}")
try:
predicted, confidence = load_aeon_results(slide_id, results_dir)
print(f" Predicted: {predicted}")
print(f" Confidence: {confidence:.4f} ({confidence * 100:.2f}%)")
# Check if prediction matches
if predicted == ground_truth:
print(" Status: ✓ PASS")
passed += 1
status = "PASS"
else:
print(f" Status: ✗ FAIL (expected {ground_truth}, got {predicted})")
failed += 1
status = "FAIL"
results.append({
"slide_id": slide_id,
"ground_truth": ground_truth,
"predicted": predicted,
"confidence": confidence,
"site_type": site_type,
"sex": sex,
"tissue_site": tissue_site,
"status": status
})
except Exception as e:
print(f" Status: ✗ ERROR - {e}")
failed += 1
results.append({
"slide_id": slide_id,
"ground_truth": ground_truth,
"predicted": None,
"confidence": None,
"site_type": site_type,
"sex": sex,
"tissue_site": tissue_site,
"status": "ERROR",
"error": str(e)
})
print()
# Print summary
print("=" * 80)
print("Summary")
print("=" * 80)
print(f"Total slides: {total}")
print(f"Passed: {passed} ({passed / total * 100:.1f}%)")
print(f"Failed: {failed} ({failed / total * 100:.1f}%)")
print()
if passed == total:
print("✓ All tests passed!")
else:
print(f"✗ {failed} test(s) failed")
# Calculate statistics for passed tests
if passed > 0:
confidences = [r["confidence"] for r in results if r["status"] == "PASS"]
avg_confidence = sum(confidences) / len(confidences)
min_confidence = min(confidences)
max_confidence = max(confidences)
print()
print("Confidence Statistics (for passed tests):")
print(f" Average: {avg_confidence:.4f} ({avg_confidence * 100:.2f}%)")
print(f" Minimum: {min_confidence:.4f} ({min_confidence * 100:.2f}%)")
print(f" Maximum: {max_confidence:.4f} ({max_confidence * 100:.2f}%)")
return {
"total": total,
"passed": passed,
"failed": failed,
"accuracy": passed / total if total > 0 else 0,
"results": results
}
def main():
parser = argparse.ArgumentParser(
description="Verify Aeon test results against ground truth"
)
parser.add_argument(
"--test-samples",
type=Path,
default=Path("test_slides/test_samples.json"),
help="Path to test_samples.json (default: test_slides/test_samples.json)"
)
parser.add_argument(
"--results-dir",
type=Path,
default=Path("test_slides/results"),
help="Directory containing results (default: test_slides/results)"
)
parser.add_argument(
"--output",
type=Path,
help="Optional path to save verification report as JSON"
)
args = parser.parse_args()
# Validate inputs
if not args.test_samples.exists():
raise FileNotFoundError(f"Test samples file not found: {args.test_samples}")
if not args.results_dir.exists():
raise FileNotFoundError(f"Results directory not found: {args.results_dir}")
# Load test samples
test_samples = load_test_samples(args.test_samples)
# Verify results
verification_report = verify_results(test_samples, args.results_dir)
# Save report if requested
if args.output:
with open(args.output, "w") as f:
json.dump(verification_report, f, indent=2)
print()
print(f"Verification report saved to: {args.output}")
# Exit with appropriate code
if verification_report["failed"] > 0:
exit(1)
else:
exit(0)
if __name__ == "__main__":
main()
|