Computes pixAcc and mIoU metric scores
| 8 | |
| 9 | |
| 10 | class SegmentationMetric(object): |
| 11 | """Computes pixAcc and mIoU metric scores |
| 12 | """ |
| 13 | |
| 14 | def __init__(self, nclass): |
| 15 | super(SegmentationMetric, self).__init__() |
| 16 | self.nclass = nclass |
| 17 | self.reset() |
| 18 | |
| 19 | def update(self, preds, labels): |
| 20 | """Updates the internal evaluation result. |
| 21 | |
| 22 | Parameters |
| 23 | ---------- |
| 24 | labels : 'NumpyArray' or list of `NumpyArray` |
| 25 | The labels of the data. |
| 26 | preds : 'NumpyArray' or list of `NumpyArray` |
| 27 | Predicted values. |
| 28 | """ |
| 29 | |
| 30 | def evaluate_worker(self, pred, label): |
| 31 | correct, labeled = batch_pix_accuracy(pred, label) |
| 32 | inter, union = batch_intersection_union(pred, label, self.nclass) |
| 33 | |
| 34 | self.total_correct += correct |
| 35 | self.total_label += labeled |
| 36 | if self.total_inter.device != inter.device: |
| 37 | self.total_inter = self.total_inter.to(inter.device) |
| 38 | self.total_union = self.total_union.to(union.device) |
| 39 | self.total_inter += inter |
| 40 | self.total_union += union |
| 41 | |
| 42 | if isinstance(preds, torch.Tensor): |
| 43 | evaluate_worker(self, preds, labels) |
| 44 | elif isinstance(preds, (list, tuple)): |
| 45 | for (pred, label) in zip(preds, labels): |
| 46 | evaluate_worker(self, pred, label) |
| 47 | |
| 48 | def get(self): |
| 49 | """Gets the current evaluation result. |
| 50 | |
| 51 | Returns |
| 52 | ------- |
| 53 | metrics : tuple of float |
| 54 | pixAcc and mIoU |
| 55 | """ |
| 56 | pixAcc = 1.0 * self.total_correct / (2.220446049250313e-16 + self.total_label) # remove np.spacing(1) |
| 57 | self.non_zero = self.total_union > 0 |
| 58 | self.non_zero_total_inter = self.total_inter[self.non_zero] |
| 59 | self.non_zero_total_union = self.total_union[self.non_zero] |
| 60 | |
| 61 | IoU = 1.0 * self.non_zero_total_inter / (2.220446049250313e-16 + self.non_zero_total_union) |
| 62 | mIoU = IoU.mean().item() |
| 63 | return pixAcc, mIoU |
| 64 | |
| 65 | def reset(self): |
| 66 | """Resets the internal evaluation result to initial state.""" |
| 67 | self.total_inter = torch.zeros(self.nclass) |