-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathoptimize_threshold.py
More file actions
162 lines (124 loc) · 4.84 KB
/
optimize_threshold.py
File metadata and controls
162 lines (124 loc) · 4.84 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
import argparse
import os
import pandas as pd
import numpy as np
import pprint
import logging
from pathlib import Path
from tqdm.autonotebook import tqdm
from utils.inference import load_model_from_config, setup_inference
from utils.eval_utils import optimize_threshold
from utils.factory import ConfigCreator, ModelFactory
# Set default configurations
BATCH_SIZE = 8
DEVICE = 'cuda'
NMS_THRESH = 0.3
NUM_WORKERS = 8
OVERLAP = 0.3
VERBOSE = False
SPLIT = 'val'
BOX_FORMAT = 'cxcy'
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--batch_size", type=int, default=BATCH_SIZE, help="Batch size.")
parser.add_argument("--box_format", type=str, default=BOX_FORMAT, help='Box format (default: xyxy).')
parser.add_argument("--config_file", type=str, help="Existing config file.", required=True)
parser.add_argument("--dataset", type=str, help="Dataset filepath.", required=True)
parser.add_argument("--device", type=str, default=DEVICE, help="Device.")
parser.add_argument("--img_dir", type=str, help="Image directory.", required=True)
parser.add_argument("--nms_thresh", type=float, default=NMS_THRESH, help="Final NMS threshold.")
parser.add_argument("--num_workers", type=int, default=NUM_WORKERS, help="Number of processes.")
parser.add_argument("--overlap", type=float, default=OVERLAP, help="Overlap between patches.")
parser.add_argument("--overwrite", action="store_true", help="If true, existing results are overwritten.")
parser.add_argument("--split", type=str, default=SPLIT, help="Data split to evaluate.")
parser.add_argument("--wsi", action="store_true", help="Processes WSI")
return parser.parse_args()
def optimize(
batch_size: int,
box_format: str,
config_file: str,
dataset: str | pd.DataFrame,
device: str,
img_dir: str,
num_workers: int,
nms_thresh: float,
overlap: float,
overwrite: bool,
split: str,
wsi: bool,
logger: logging.Logger = None
):
# Check existing config_file
if not Path(config_file).exists():
raise FileNotFoundError(f"Could not find this config_file: {config_file}. Provide existing config_file.")
# Check dataset
if isinstance(dataset, str):
if not Path(dataset).exists():
raise FileNotFoundError(f"Could not find dataset: {dataset}")
dataset = pd.read_csv(dataset)
# Convert to xmin, ymin, xmax, ymax
if box_format == 'cxcy':
radius = 25
dataset = dataset.assign(xmin=dataset['x'] - radius)
dataset = dataset.assign(ymin=dataset['y'] - radius)
dataset = dataset.assign(xmax=dataset['x'] + radius)
dataset = dataset.assign(ymax=dataset['y'] + radius)
# Check image directory
img_dir = Path(img_dir)
if not img_dir.is_dir():
raise ValueError(f"This is not a directory: {str(img_dir)}")
# Load the model
model, config = load_model_from_config(config_file)
# Setup the inference
processor, patch_config = setup_inference(
model=model,
is_wsi=wsi,
batch_size=batch_size,
num_workers=num_workers,
nms_thresh=nms_thresh,
device=device,
patch_size=config.patch_size,
overlap=overlap,
overwrite=overwrite,
logger=logger
)
print('Loaded model configurations:')
pprint.pprint(config)
print()
# Filter dataset
optim_dataset = dataset.query("split == @split")
filenames = optim_dataset.filename.unique()
# Initialize predictions
preds = {}
# Run inference over all images
for file in tqdm(filenames, desc="Running inference"):
# Create image path
image_path = img_dir.joinpath(file)
# Process images individually
results = processor.process_single(image_path, patch_config)
# Collect predictions
preds[file] = results
# Filter only mitotic figures
filtered_dataset = optim_dataset.query('label == 1')
# Optimize detection threshold
best_thresh, best_f1, _, _ = optimize_threshold(
dataset=filtered_dataset,
preds=preds,
min_thresh=config.det_thresh
)
print(f'Best threshold: F1={best_f1:.4f}, Threshold={best_thresh:.2f}\n')
rounded_thresh = float(np.round(best_thresh, decimals=4))
# Updating model configs
config.update({'det_thresh': rounded_thresh})
print(f'Updated model configs with optimized threshold: {rounded_thresh}.')
config.save(config_file)
print(f'Updated config file at: {config_file}.')
def main(args):
# Convert args
optimize_kwargs = vars(args)
# Run optimize
optimize(**optimize_kwargs)
if __name__ == "__main__":
args = get_args()
main(args)
print('End of script.')