|
| 1 | +# Copyright The PyTorch Lightning team. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +import warnings |
| 15 | +from typing import Any, Set |
| 16 | + |
| 17 | +import torch |
| 18 | +from torch import Tensor |
| 19 | + |
| 20 | +from torchmetrics.functional.detection.panoptic_quality import ( |
| 21 | + _get_category_id_to_continuous_id, |
| 22 | + _get_void_color, |
| 23 | + _panoptic_quality_compute, |
| 24 | + _panoptic_quality_update, |
| 25 | + _prepocess_image, |
| 26 | + _validate_categories, |
| 27 | + _validate_inputs, |
| 28 | +) |
| 29 | +from torchmetrics.metric import Metric |
| 30 | + |
| 31 | + |
| 32 | +class PanopticQuality(Metric): |
| 33 | + r"""Compute the `Panoptic Quality`_ for panoptic segmentations. |
| 34 | +
|
| 35 | + .. math:: |
| 36 | + PQ = \frac{IOU}{TP + 0.5 FP + 0.5 FN} |
| 37 | +
|
| 38 | + where IOU, TP, FP and FN are respectively the sum of the intersection over union for true positives, |
| 39 | + the number of true postitives, false positives and false negatives. This metric is inspired by the PQ |
| 40 | + implementati on of panopticapi, a standard implementation for the PQ metric for object detection. |
| 41 | +
|
| 42 | + .. note: |
| 43 | + Metric is currently experimental |
| 44 | +
|
| 45 | + Args: |
| 46 | + things: |
| 47 | + Set of ``category_id`` for countable things. |
| 48 | + stuffs: |
| 49 | + Set of ``category_id`` for uncountable stuffs. |
| 50 | + allow_unknown_preds_category: |
| 51 | + Bool indication if unknown categories in preds is allowed |
| 52 | +
|
| 53 | + Raises: |
| 54 | + ValueError: |
| 55 | + If ``things``, ``stuffs`` share the same ``category_id``. |
| 56 | +
|
| 57 | + Example: |
| 58 | + >>> from torch import tensor |
| 59 | + >>> preds = tensor([[[6, 0], [0, 0], [6, 0], [6, 0]], |
| 60 | + ... [[0, 0], [0, 0], [6, 0], [0, 1]], |
| 61 | + ... [[0, 0], [0, 0], [6, 0], [0, 1]], |
| 62 | + ... [[0, 0], [7, 0], [6, 0], [1, 0]], |
| 63 | + ... [[0, 0], [7, 0], [7, 0], [7, 0]]]) |
| 64 | + >>> target = tensor([[[6, 0], [0, 1], [6, 0], [0, 1]], |
| 65 | + ... [[0, 1], [0, 1], [6, 0], [0, 1]], |
| 66 | + ... [[0, 1], [0, 1], [6, 0], [1, 0]], |
| 67 | + ... [[0, 1], [7, 0], [1, 0], [1, 0]], |
| 68 | + ... [[0, 1], [7, 0], [7, 0], [7, 0]]]) |
| 69 | + >>> panoptic_quality = PanopticQuality(things = {0, 1}, stuffs = {6, 7}) |
| 70 | + >>> panoptic_quality(preds, target) |
| 71 | + tensor(0.5463, dtype=torch.float64) |
| 72 | + """ |
| 73 | + is_differentiable: bool = False |
| 74 | + higher_is_better: bool = True |
| 75 | + full_state_update: bool = False |
| 76 | + |
| 77 | + iou_sum: Tensor |
| 78 | + true_positives: Tensor |
| 79 | + false_positives: Tensor |
| 80 | + false_negatives: Tensor |
| 81 | + |
| 82 | + def __init__( |
| 83 | + self, |
| 84 | + things: Set[int], |
| 85 | + stuffs: Set[int], |
| 86 | + allow_unknown_preds_category: bool = False, |
| 87 | + **kwargs: Any, |
| 88 | + ): |
| 89 | + super().__init__(**kwargs) |
| 90 | + |
| 91 | + # todo: better testing for correctness of metric |
| 92 | + warnings.warn("This is experimental version and are actively working on its stability.") |
| 93 | + |
| 94 | + _validate_categories(things, stuffs) |
| 95 | + self.things = things |
| 96 | + self.stuffs = stuffs |
| 97 | + self.void_color = _get_void_color(things, stuffs) |
| 98 | + self.cat_id_to_continuous_id = _get_category_id_to_continuous_id(things, stuffs) |
| 99 | + self.allow_unknown_preds_category = allow_unknown_preds_category |
| 100 | + |
| 101 | + # per category intermediate metrics |
| 102 | + n_categories = len(things) + len(stuffs) |
| 103 | + self.add_state("iou_sum", default=torch.zeros(n_categories, dtype=torch.double), dist_reduce_fx="sum") |
| 104 | + self.add_state("true_positives", default=torch.zeros(n_categories, dtype=torch.int), dist_reduce_fx="sum") |
| 105 | + self.add_state("false_positives", default=torch.zeros(n_categories, dtype=torch.int), dist_reduce_fx="sum") |
| 106 | + self.add_state("false_negatives", default=torch.zeros(n_categories, dtype=torch.int), dist_reduce_fx="sum") |
| 107 | + |
| 108 | + def update(self, preds: Tensor, target: Tensor) -> None: |
| 109 | + r"""Update state with predictions and targets. |
| 110 | +
|
| 111 | + Args: |
| 112 | + preds: panoptic detection of shape ``[height, width, 2]`` containing |
| 113 | + the pair ``(category_id, instance_id)`` for each pixel of the image. |
| 114 | + If the ``category_id`` refer to a stuff, the instance_id is ignored. |
| 115 | +
|
| 116 | + target: ground truth of shape ``[height, width, 2]`` containing |
| 117 | + the pair ``(category_id, instance_id)`` for each pixel of the image. |
| 118 | + If the ``category_id`` refer to a stuff, the instance_id is ignored. |
| 119 | +
|
| 120 | + Raises: |
| 121 | + TypeError: |
| 122 | + If ``preds`` or ``target`` is not an ``torch.Tensor`` |
| 123 | + ValueError: |
| 124 | + If ``preds`` or ``target`` has different shape. |
| 125 | + ValueError: |
| 126 | + If ``preds`` is not a 3D tensor where the final dimension have size 2 |
| 127 | + """ |
| 128 | + _validate_inputs(preds, target) |
| 129 | + flatten_preds = _prepocess_image( |
| 130 | + self.things, self.stuffs, preds, self.void_color, self.allow_unknown_preds_category |
| 131 | + ) |
| 132 | + flatten_target = _prepocess_image(self.things, self.stuffs, target, self.void_color, True) |
| 133 | + iou_sum, true_positives, false_positives, false_negatives = _panoptic_quality_update( |
| 134 | + flatten_preds, flatten_target, self.cat_id_to_continuous_id, self.void_color |
| 135 | + ) |
| 136 | + self.iou_sum += iou_sum |
| 137 | + self.true_positives += true_positives |
| 138 | + self.false_positives += false_positives |
| 139 | + self.false_negatives += false_negatives |
| 140 | + |
| 141 | + def compute(self) -> Tensor: |
| 142 | + """Computes panoptic quality based on inputs passed in to ``update`` previously.""" |
| 143 | + return _panoptic_quality_compute(self.iou_sum, self.true_positives, self.false_positives, self.false_negatives) |
0 commit comments