import numpy as np | |
from typing import List, Tuple | |
def compute_metrics(conf_matrix: np.ndarray) -> Tuple[List[float], float, List[float], float]: | |
""" | |
Calculates metrics IoU and F1 from confusion matrix | |
""" | |
num_classes = conf_matrix.shape[0] | |
ious, f1s = [], [] | |
for c in range(num_classes): | |
tp = conf_matrix[c, c] | |
fp = conf_matrix[:, c].sum() - tp | |
fn = conf_matrix[c, :].sum() - tp | |
union = tp + fp + fn | |
iou = tp / union if union else float('nan') | |
f1 = 2 * tp / (2 * tp + fp + fn) if (2*tp + fp + fn) else 0.0 | |
ious.append(iou) | |
f1s.append(f1) | |
miou = np.nanmean(ious) | |
mf1 = float(np.mean(f1s)) | |
return ious, miou, f1s, mf1 | |