kirad.ordinal_thresholding¶
kirad.ordinal_thresholding
¶
Tune ordinal thresholds that turn continuous scores into severity classes.
Stage: thresholds/metrics. After each validation epoch base_models tunes six threshold sets (accuracy, absolute_error, macro_recall, macro_precision, macro_f1 by DP; coral from the CORAL biases), stores them as buffers in the checkpoint and reuses them on test.
OrdinalThresholding
¶
Bases: Module
Base module: K-1 sorted thresholds (buffer) that map scores to K ordinal classes.
Basic 1d thresholding logic.
Source code in kirad/ordinal_thresholding.py
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 | |
num_classes = num_classes
instance-attribute
¶
thresholds
instance-attribute
¶
__init__(num_classes)
¶
Create num_classes - 1 zero thresholds as a buffer (saved in the checkpoint).
Init thresholding module with the specified number of classes (one more than the number of thresholds).
Source code in kirad/ordinal_thresholding.py
21 22 23 24 25 26 27 28 | |
is_valid()
¶
Check whether the thresholds are monotone non-decreasing.
Source code in kirad/ordinal_thresholding.py
30 31 32 | |
forward(scores)
¶
Class index per score = number of thresholds strictly below it (searchsorted).
Find which thresholds each score lies between. Note: a score equal to a threshold falls in the lower class.
Source code in kirad/ordinal_thresholding.py
34 35 36 37 38 39 40 | |
tune_thresholds(*, scores, labels, available_thresholds=None)
¶
Tune thresholds on validation scores/labels; no-op here, overridden by subclasses.
Adapt the thresholds to the given data.
This is essentially an abstract method, but for testing purposes it's helpful to be able to instantiate the class with a no-op version.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores
|
a vector of `float` scores for each example in the validation set
|
|
required |
labels
|
a vector of `int` labels having the same shape as `scores` containing the corresponding labels
|
|
required |
available_thresholds
|
a vector of `float` score values over which to optimize choice of thresholds;
|
|
None
|
Returns:
| Type | Description |
|---|---|
scalar `float` mean cost on the validation set using optimal thresholds
|
|
Source code in kirad/ordinal_thresholding.py
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 | |
CORALThresholding
¶
Bases: OrdinalThresholding
Thresholds = -CORAL bias at the chosen cutoff indices (learned on train, no tuning).
Thresholding using the biases learned on the TRAINING set from the CORAL loss.
Source code in kirad/ordinal_thresholding.py
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 | |
biases = coral_loss.biases
instance-attribute
¶
threshold_indices = torch.tensor(threshold_indices)
instance-attribute
¶
__init__(coral_loss, threshold_indices)
¶
Keep a reference to the CORAL biases and the cutoff indices to read.
Init module taking thresholds at specified indices from a given CORALLoss instance
Source code in kirad/ordinal_thresholding.py
76 77 78 79 80 81 82 83 | |
tune_thresholds(*, scores, labels, available_thresholds=None)
¶
Copy -biases[threshold_indices] from the CORAL loss; scores and labels are ignored.
Ignore the data, pull the specified biases from the CORAL loss, and multiply by -1 to get thresholds.
Source code in kirad/ordinal_thresholding.py
85 86 87 88 89 90 91 92 93 94 95 96 97 98 | |
OptimalOrdinalThresholdingViaDynamicProgramming
¶
Bases: OrdinalThresholding, ABC
Base for DP threshold tuning: pick K-1 thresholds from candidates to optimize a metric.
Super-class for general dynamic programming implementations of ordinal threshold tuning.
Subclasses implement different ways of computing the mean cost and corresponding DP step.
Source code in kirad/ordinal_thresholding.py
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 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 | |
direction
instance-attribute
¶
__init__(num_classes)
¶
Check that the subclass set direction to "min" or "max".
Source code in kirad/ordinal_thresholding.py
112 113 114 115 116 117 118 | |
mean_cost(*, labels, preds)
abstractmethod
¶
Compute the mean cost of assigning label(s) preds when the ground truth is labels.
Source code in kirad/ordinal_thresholding.py
120 121 122 123 124 | |
best_constant_output_classifier(labels)
¶
Best metric of a constant-class predictor and that class (baseline_const_* in logs).
Find the optimal mean cost of a constant-output classifier for given labels and the associated constant.
Source code in kirad/ordinal_thresholding.py
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 | |
dp_step(c_idx, *, scores, labels, available_thresholds, prev_cost=None)
abstractmethod
¶
One DP step: best cost of classes <= c_idx for each candidate upper threshold of c_idx.
Given optimal cost prev_cost of classes < c_idx, optimize cost of c_idx as a function of threshold.
Arguments
c_idx : current class index
scores, labels, available_thresholds : see `tune_thresholds`
prev_cost (optional float tensor) : optimal cost of classes < `c_idx` as a function of upper threshold
for class `c_idx - 1`; ignored if `c_idx == 0`
Returns:
| Type | Description |
|---|---|
cost: `cost[i]` is for choosing upper threshold of class `c_idx` equal to `available_thresholds[i]`
|
indices : to achieve |
Source code in kirad/ordinal_thresholding.py
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 | |
tune_thresholds(*, scores, labels, available_thresholds=None)
¶
Set thresholds by DP over midpoints of unique scores (+/-inf); return the best metric.
Set self.thresholds to optimize mean cost of given scores and labels.
Arguments
scores (1d float tensor) : scores of examples on tuning dataset
labels (1d int tensor) : labels in {0, ..., self.num_classes - 1} of same shape as scores
available_thresholds (optional 1d float tensor) : thresholds which will be considered when tuning.
+/-inf will be added automatically to ensure all examples are classified. If omitted, will
insert thresholds between each element of sorted(unique(scores)).
Returns:
| Type | Description |
|---|---|
float tensor : optimal mean cost achieved on the provided dataset at the tuned `self.thresholds`
|
|
Source code in kirad/ordinal_thresholding.py
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 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 | |
OptimalCostPerSampleOrdinalThresholding
¶
Bases: OptimalOrdinalThresholdingViaDynamicProgramming, ABC
DP tuning for metrics that are a mean of per-sample costs (accuracy, MAE, macro recall).
Optimal 1d thresholding based on tuning thresholds to optimize the mean of a sample-wise cost function.
Source code in kirad/ordinal_thresholding.py
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 | |
cost(*, labels, preds)
abstractmethod
¶
Per-sample cost of predicting preds for labels (subclasses define the metric).
Compute the sample-wise cost of assigning label(s) preds when the ground truth is labels.
Source code in kirad/ordinal_thresholding.py
279 280 281 282 283 | |
mean_cost(*, labels, preds)
¶
Compute the mean cost of assigning label(s) preds when the ground truth is labels.
Source code in kirad/ordinal_thresholding.py
285 286 287 288 289 | |
dp_step(c_idx, *, scores, labels, available_thresholds, prev_cost=None)
¶
O(n) DP step: histogram per-sample costs over candidates, cumsum, running max.
O(len(scores)) implementation for per-sample cost. Note: torch.histogram runs on CPU (no CUDA kernel); tensors are moved back and forth.
Source code in kirad/ordinal_thresholding.py
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 | |
MaxAccuracyOrdinalThresholding
¶
Bases: OptimalCostPerSampleOrdinalThresholding
Threshold to maximize accuracy.
Source code in kirad/ordinal_thresholding.py
331 332 333 334 335 336 337 338 | |
direction = 'max'
class-attribute
instance-attribute
¶
cost(*, labels, preds)
¶
1.0 where pred == label, else 0.0.
Source code in kirad/ordinal_thresholding.py
336 337 338 | |
MaxMacroRecallOrdinalThresholding
¶
Bases: OptimalCostPerSampleOrdinalThresholding
Threshold to maximize macro-averaged recall.
Source code in kirad/ordinal_thresholding.py
341 342 343 344 345 346 347 348 349 350 351 352 | |
direction = 'max'
class-attribute
instance-attribute
¶
cost(*, labels, preds)
¶
Correct = N / (K * count[label]), so the mean equals macro-averaged recall.
Source code in kirad/ordinal_thresholding.py
346 347 348 349 350 351 352 | |
MinAbsoluteErrorOrdinalThresholding
¶
Bases: OptimalCostPerSampleOrdinalThresholding
Threshold to minimize mean absolute error.
Source code in kirad/ordinal_thresholding.py
355 356 357 358 359 360 361 362 | |
direction = 'min'
class-attribute
instance-attribute
¶
cost(*, labels, preds)
¶
|pred - label| in class units.
Source code in kirad/ordinal_thresholding.py
360 361 362 | |
ClassWeightedOptimalCostPerSampleOrdinalThresholding
¶
Bases: OptimalCostPerSampleOrdinalThresholding
Wrap a per-sample cost so each class weighs equally; not used by base_models.
Compute cost weighted equally over classes instead of equally over samples.
This class takes another instance of OptimalCostPerSampleOrdinalThresholding which computes its cost independently for each sample and reweights the cost based on label frequencies.
Note: this class depends on an implementation detail of its superclass:
namely calling self.cost with the full tuning or eval set of labels,
rather than a single label. This is required to do the re-weighting properly.
Source code in kirad/ordinal_thresholding.py
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 | |
direction = unweighted_instance.direction
instance-attribute
¶
unweighted_instance = unweighted_instance
instance-attribute
¶
__init__(unweighted_instance)
¶
Copy direction and num_classes from the wrapped instance.
Source code in kirad/ordinal_thresholding.py
382 383 384 385 386 | |
cost(*, labels, preds)
¶
Wrapped cost times N / (K * count[label]); raises if any class is missing.
Source code in kirad/ordinal_thresholding.py
388 389 390 391 392 393 394 395 396 397 398 399 400 | |
OptimalCostPerClassOrdinalThresholding
¶
Bases: OptimalOrdinalThresholdingViaDynamicProgramming, ABC
DP tuning for per-class metrics (macro precision, macro F1) via a T x T cost matrix.
General DP case for when the linear algorithm for per-sample costs is not applicable.
Complexity depends on the implementation of cost_matrix.
Source code in kirad/ordinal_thresholding.py
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 | |
cost_matrix(c_idx, *, scores, labels, available_thresholds, start, end)
abstractmethod
¶
Cost matrix [T, T]: metric of class c_idx if scores in [thr[i], thr[j]) get c_idx.
Each output[i, j] = cost for when scores in range available_thresholds[i:j] are assigned label c_idx.
Source code in kirad/ordinal_thresholding.py
414 415 416 417 418 419 420 421 422 423 424 425 426 427 | |
mean_cost(*, labels, preds)
¶
Macro metric of fixed preds, reusing cost_matrix with thresholds c +/- 0.5.
Compute the mean cost of assigning label(s) preds when the ground truth is labels.
Source code in kirad/ordinal_thresholding.py
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 | |
dp_step(c_idx, *, scores, labels, available_thresholds, prev_cost=None)
¶
O(T^2) DP step: add prev_cost to each lower-threshold row and max over it.
T = number of candidate thresholds. Cost is divided by K, giving a macro average.
Source code in kirad/ordinal_thresholding.py
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 | |
MaxMacroPrecisionOrdinalThresholding
¶
Bases: OptimalCostPerClassOrdinalThresholding
Threshold to maximize macro-averaged precision.
Source code in kirad/ordinal_thresholding.py
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 | |
direction = 'max'
class-attribute
instance-attribute
¶
cost_matrix(c_idx, scores, labels, available_thresholds, start, end)
¶
Precision of class c_idx for each (lower, upper) threshold pair; empty range = 0.
Source code in kirad/ordinal_thresholding.py
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 | |
MaxMacroF1OrdinalThresholding
¶
Bases: OptimalCostPerClassOrdinalThresholding
Threshold to maximize macro-averaged F1 score.
Source code in kirad/ordinal_thresholding.py
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 | |
direction = 'max'
class-attribute
instance-attribute
¶
cost_matrix(c_idx, scores, labels, available_thresholds, start, end)
¶
F1 of class c_idx = 2TP / (TP+FP + TP+FN) for each (lower, upper) threshold pair.
Source code in kirad/ordinal_thresholding.py
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 | |
cumsum_with_0(t)
¶
Cumulative sum along dim 0 with a leading 0 (length n + 1).
Source code in kirad/ordinal_thresholding.py
266 267 268 | |