Repository navigation
Expand file tree
/
Copy pathevaluate.py
More file actions
174 lines (141 loc) · 6.07 KB
/
Copy pathevaluate.py
File metadata and controls
174 lines (141 loc) · 6.07 KB
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
from __future__ import annotations
import argparse
import logging
import os
from pathlib import Path
import cv2
import numpy as np
import tensorflow as tf
from sklearn.metrics import f1_score
from tensorflow.keras.models import load_model
import utils.tf_setup
from utils.config import TrainingConfig
from utils.data import list_images
from utils.model_io import resolve_model_path
from utils.tf_setup import configure_gpu, configure_logging, suppress_warnings
class F1Score(tf.keras.metrics.Metric):
def __init__(self, name: str = "val_f1_score", threshold: float = 0.5, **kwargs):
super().__init__(name=name, **kwargs)
self.threshold = threshold
self.tp = self.add_weight(name="tp", initializer="zeros")
self.fp = self.add_weight(name="fp", initializer="zeros")
self.fn = self.add_weight(name="fn", initializer="zeros")
def update_state(self, y_true, y_pred, sample_weight=None):
y_pred = tf.cast(y_pred > self.threshold, tf.float32)
y_true = tf.cast(y_true, tf.float32)
self.tp.assign_add(tf.reduce_sum(y_true * y_pred))
self.fp.assign_add(tf.reduce_sum((1 - y_true) * y_pred))
self.fn.assign_add(tf.reduce_sum(y_true * (1 - y_pred)))
def result(self):
precision = self.tp / (self.tp + self.fp + 1e-7)
recall = self.tp / (self.tp + self.fn + 1e-7)
return 2 * ((precision * recall) / (precision + recall + 1e-7))
def reset_state(self):
self.tp.assign(0)
self.fp.assign(0)
self.fn.assign(0)
def find_best_threshold(labels: list[int], scores: list[float]) -> tuple[float, float]:
best_f1 = 0.0
best_threshold = 0.5
for threshold in np.linspace(0, 1, num=100):
predicted = (np.array(scores) >= threshold).astype(int)
f1 = f1_score(labels, predicted, zero_division=0)
if f1 > best_f1:
best_f1 = float(f1)
best_threshold = float(threshold)
return best_threshold, best_f1
def parse_input_shape(model_path: str, config: TrainingConfig) -> tuple[int, int, int]:
filename = os.path.basename(model_path)
try:
shape_part = filename.split("_")[:4]
return tuple(map(int, shape_part[1:4]))
except (ValueError, IndexError):
logging.warning(
"Could not parse input shape from %s, using config input_shape",
filename,
)
return tuple(config.input_shape)
def evaluate(
model_path: str,
config: TrainingConfig,
threshold: float,
mode: str,
data_dir: str | None = None,
) -> None:
data_path = Path(data_dir or os.path.join(config.auto_split.output_dir, "test"))
if not data_path.is_dir():
raise FileNotFoundError(f"Test directory not found: {data_path}")
resolved_path = resolve_model_path(model_path)
input_shape = parse_input_shape(str(model_path), config)
logging.info("Loading model from %s", resolved_path)
model = load_model(resolved_path, compile=False)
model.compile(
optimizer="sgd",
loss="binary_crossentropy",
metrics=[F1Score(name="val_f1_score")],
)
ground_truth_labels: list[int] = []
predicted_probabilities: list[float] = []
count_images = 0
output_dirs: dict[int, str] = {}
if mode == "folder_split":
output_dirs = {0: os.path.join("out", "0"), 1: os.path.join("out", "1")}
for directory in output_dirs.values():
os.makedirs(directory, exist_ok=True)
for class_dir in sorted(path for path in data_path.iterdir() if path.is_dir()):
if mode == "standard":
output_dir = os.path.join("out", class_dir.name)
os.makedirs(output_dir, exist_ok=True)
logging.info("Evaluating class: %s", class_dir.name)
for image_path in list_images(class_dir):
image_bgr = cv2.imread(str(image_path))
if image_bgr is None:
logging.warning("Skipping unreadable image: %s", image_path)
continue
count_images += 1
image_resized = cv2.resize(image_bgr, (input_shape[1], input_shape[0]))
image_normalized = image_resized.astype("float32") / 255.0
image_input = np.expand_dims(image_normalized, axis=0)
prediction = float(model.predict(image_input, verbose=0)[0][0])
predicted_probabilities.append(prediction)
ground_truth_labels.append(int(class_dir.name))
output_filename = f"{prediction:.4f}_{image_path.name}"
if mode == "standard":
save_path = os.path.join(output_dir, output_filename)
else:
label_folder = 1 if prediction >= threshold else 0
save_path = os.path.join(output_dirs[label_folder], output_filename)
cv2.imwrite(save_path, image_bgr)
best_threshold, best_f1 = find_best_threshold(ground_truth_labels, predicted_probabilities)
logging.info("Images evaluated: %s", count_images)
logging.info("Best threshold: %.3f", best_threshold)
logging.info("Best F1-score: %.3f", best_f1)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Evaluate a trained binary classifier.")
parser.add_argument("-m", "--model", required=True, help="Path to the saved model")
parser.add_argument("-s", "--threshold", type=float, default=0.5, help="Classification threshold")
parser.add_argument(
"--mode",
choices=["standard", "folder_split"],
default="standard",
help="Output layout for annotated images",
)
parser.add_argument("--config", default="config.yaml", help="Path to config YAML")
parser.add_argument("--data-dir", default=None, help="Override test dataset directory")
return parser.parse_args()
def main() -> int:
args = parse_args()
configure_logging()
suppress_warnings()
configure_gpu()
config = TrainingConfig.from_yaml(args.config)
evaluate(
model_path=args.model,
config=config,
threshold=args.threshold,
mode=args.mode,
data_dir=args.data_dir,
)
return 0
if __name__ == "__main__":
raise SystemExit(main())