Repository: pytorch/ignite

Issue:
Adding Classification report utility function
## 🚀 Feature

I'd like to add the classification report utility to ignite. Similar to the same functionality in scikit-learn https://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html#sklearn.metrics.classification_report





Discussion:
@Moh-Yakoub thanks for a FR! May be helpful. I think this can be done as a helper method with attaching precision, recall, f1 and returning a dictionary with [MetricsLambda](https://pytorch.org/ignite/metrics.html#ignite.metrics.MetricsLambda).
Great, I will start doing that!

Resolving patch:
diff --git a/ignite/metrics/__init__.py b/ignite/metrics/__init__.py
--- a/ignite/metrics/__init__.py
+++ b/ignite/metrics/__init__.py
@@ -1,5 +1,6 @@
 from ignite.metrics.accumulation import Average, GeometricAverage, VariableAccumulation
 from ignite.metrics.accuracy import Accuracy
+from ignite.metrics.classification_report import ClassificationReport
 from ignite.metrics.confusion_matrix import ConfusionMatrix, DiceCoefficient, IoU, JaccardIndex, mIoU
 from ignite.metrics.epoch_metric import EpochMetric
 from ignite.metrics.fbeta import Fbeta
@@ -30,6 +31,7 @@
     "MeanPairwiseDistance",
     "MeanSquaredError",
     "ConfusionMatrix",
+    "ClassificationReport",
     "TopKCategoricalAccuracy",
     "Average",
     "DiceCoefficient",
diff --git a/ignite/metrics/classification_report.py b/ignite/metrics/classification_report.py
new file mode 100644
--- /dev/null
+++ b/ignite/metrics/classification_report.py
@@ -0,0 +1,107 @@
+import json
+from typing import Callable, Collection, Dict, List, Optional, Union
+
+import torch
+
+from ignite.metrics.fbeta import Fbeta
+from ignite.metrics.metric import Metric
+from ignite.metrics.metrics_lambda import MetricsLambda
+from ignite.metrics.precision import Precision
+from ignite.metrics.recall import Recall
+
+__all__ = ["ClassificationReport"]
+
+
+def ClassificationReport(
+    beta: int = 1,
+    output_dict: bool = False,
+    output_transform: Callable = lambda x: x,
+    device: Union[str, torch.device] = torch.device("cpu"),
+    is_multilabel: bool = False,
+    labels: Optional[List[str]] = None,
+) -> MetricsLambda:
+    r"""Build a text report showing the main classification metrics. The report resembles in functionality to
+    `scikit-learn classification_report
+    <https://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html#sklearn.metrics.classification_report>`_
+    The underlying implementation doesn't use the sklearn function.
+
+    Args:
+        beta: weight of precision in harmonic mean
+        output_dict: If True, return output as dict, otherwise return a str
+        output_transform: a callable that is used to transform the
+            :class:`~ignite.engine.engine.Engine`'s ``process_function``'s output into the
+            form expected by the metric. This can be useful if, for example, you have a multi-output model and
+            you want to compute the metric with respect to one of the outputs.
+        is_multilabel: If True, the tensors are assumed to be multilabel.
+        device: optional device specification for internal storage.
+        labels: Optional list of label indices to include in the report
+
+    .. code-block:: python
+
+
+        def process_function(engine, batch):
+            # ...
+            return y_pred, y
+
+        engine = Engine(process_function)
+        metric = ClassificationReport()
+        metric.attach(engine, "cr")
+        engine.run...
+        res = engine.state.metrics["cr"]
+        # result should be like
+        {
+          "0": {
+            "precision": 0.4891304347826087,
+            "recall": 0.5056179775280899,
+            "f1-score": 0.497237569060773
+          },
+          "1": {
+            "precision": 0.5157232704402516,
+            "recall": 0.4992389649923896,
+            "f1-score": 0.507347254447022
+          },
+          "macro avg": {
+            "precision": 0.5024268526114302,
+            "recall": 0.5024284712602398,
+            "f1-score": 0.5022924117538975
+          }
+        }
+    """
+
+    # setup all the underlying metrics
+    precision = Precision(average=False, is_multilabel=is_multilabel, output_transform=output_transform, device=device,)
+    recall = Recall(average=False, is_multilabel=is_multilabel, output_transform=output_transform, device=device,)
+    fbeta = Fbeta(beta, average=False, precision=precision, recall=recall)
+    averaged_precision = precision.mean()
+    averaged_recall = recall.mean()
+    averaged_fbeta = fbeta.mean()
+
+    def _wrapper(
+        recall_metric: Metric, precision_metric: Metric, f: Metric, a_recall: Metric, a_precision: Metric, a_f: Metric,
+    ) -> Union[Collection[str], Dict]:
+        p_tensor, r_tensor, f_tensor = precision_metric, recall_metric, f
+        if p_tensor.shape != r_tensor.shape:
+            raise ValueError(
+                "Internal error: Precision and Recall have mismatched shapes: "
+                f"{p_tensor.shape} vs {r_tensor.shape}. Please, open an issue "
+                "with a reference on this error. Thank you!"
+            )
+        dict_obj = {}
+        for idx, p_label in enumerate(p_tensor):
+            dict_obj[_get_label_for_class(idx)] = {
+                "precision": p_label.item(),
+                "recall": r_tensor[idx].item(),
+                "f{0}-score".format(beta): f_tensor[idx].item(),
+            }
+        dict_obj["macro avg"] = {
+            "precision": a_precision.item(),
+            "recall": a_recall.item(),
+            "f{0}-score".format(beta): a_f.item(),
+        }
+        return dict_obj if output_dict else json.dumps(dict_obj)
+
+    # helper method to get a label for a given class
+    def _get_label_for_class(idx: int) -> str:
+        return labels[idx] if labels else str(idx)
+
+    return MetricsLambda(_wrapper, recall, precision, fbeta, averaged_recall, averaged_precision, averaged_fbeta,)


Test patch:
diff --git a/tests/ignite/metrics/test_classification_report.py b/tests/ignite/metrics/test_classification_report.py
new file mode 100644
--- /dev/null
+++ b/tests/ignite/metrics/test_classification_report.py
@@ -0,0 +1,199 @@
+import json
+import os
+
+import pytest
+import torch
+
+import ignite.distributed as idist
+from ignite.engine import Engine
+from ignite.metrics.classification_report import ClassificationReport
+
+
+def _test_integration_multiclass(device, output_dict):
+
+    rank = idist.get_rank()
+    torch.manual_seed(12)
+
+    def _test(metric_device, n_classes, labels=None):
+
+        classification_report = ClassificationReport(device=metric_device, output_dict=output_dict, labels=labels)
+        n_iters = 80
+        s = 16
+        offset = n_iters * s
+        y_true = torch.randint(0, n_classes, size=(offset * idist.get_world_size(),)).to(device)
+        y_preds = torch.rand(offset * idist.get_world_size(), n_classes).to(device)
+
+        def update(engine, i):
+            return (
+                y_preds[i * s + rank * offset : (i + 1) * s + rank * offset, :],
+                y_true[i * s + rank * offset : (i + 1) * s + rank * offset],
+            )
+
+        engine = Engine(update)
+
+        classification_report.attach(engine, "cr")
+
+        data = list(range(n_iters))
+        engine.run(data=data)
+
+        assert "cr" in engine.state.metrics
+        res = engine.state.metrics["cr"]
+        res2 = classification_report.compute()
+        assert res == res2
+
+        assert isinstance(res, dict if output_dict else str)
+        if not output_dict:
+            res = json.loads(res)
+
+        from sklearn.metrics import classification_report as sklearn_classification_report
+
+        sklearn_result = sklearn_classification_report(
+            y_true.cpu().numpy(), torch.argmax(y_preds, dim=1).cpu().numpy(), output_dict=True
+        )
+
+        for i in range(n_classes):
+            label_i = labels[i] if labels else str(i)
+            assert pytest.approx(res[label_i]["precision"] == sklearn_result[str(i)]["precision"])
+            assert pytest.approx(res[label_i]["f1-score"] == sklearn_result[str(i)]["f1-score"])
+            assert pytest.approx(res[label_i]["recall"] == sklearn_result[str(i)]["recall"])
+        assert pytest.approx(res["macro avg"]["precision"] == sklearn_result["macro avg"]["precision"])
+        assert pytest.approx(res["macro avg"]["recall"] == sklearn_result["macro avg"]["recall"])
+        assert pytest.approx(res["macro avg"]["f1-score"] == sklearn_result["macro avg"]["f1-score"])
+
+    for _ in range(5):
+        # check multiple random inputs as random exact occurencies are rare
+        metric_devices = ["cpu"]
+        if device.type != "xla":
+            metric_devices.append(idist.device())
+        for metric_device in metric_devices:
+            _test(metric_device, 2, ["label0", "label1"])
+            _test(metric_device, 2)
+            _test(metric_device, 3, ["label0", "label1", "label2"])
+            _test(metric_device, 3)
+            _test(metric_device, 4, ["label0", "label1", "label2", "label3"])
+            _test(metric_device, 4)
+
+
+def _test_integration_multilabel(device, output_dict):
+
+    rank = idist.get_rank()
+    torch.manual_seed(12)
+
+    def _test(metric_device, n_epochs, labels=None):
+
+        classification_report = ClassificationReport(device=metric_device, output_dict=output_dict, is_multilabel=True)
+
+        n_iters = 10
+        s = 16
+        n_classes = 7
+
+        offset = n_iters * s
+        y_true = torch.randint(0, 2, size=(offset * idist.get_world_size(), n_classes, 6, 8)).to(device)
+        y_preds = torch.randint(0, 2, size=(offset * idist.get_world_size(), n_classes, 6, 8)).to(device)
+
+        def update(engine, i):
+            return (
+                y_preds[i * s + rank * offset : (i + 1) * s + rank * offset, ...],
+                y_true[i * s + rank * offset : (i + 1) * s + rank * offset, ...],
+            )
+
+        engine = Engine(update)
+
+        classification_report.attach(engine, "cr")
+
+        data = list(range(n_iters))
+        engine.run(data=data, max_epochs=n_epochs)
+
+        assert "cr" in engine.state.metrics
+        res = engine.state.metrics["cr"]
+        res2 = classification_report.compute()
+        assert res == res2
+
+        assert isinstance(res, dict if output_dict else str)
+        if not output_dict:
+            res = json.loads(res)
+
+        np_y_preds = to_numpy_multilabel(y_preds)
+        np_y_true = to_numpy_multilabel(y_true)
+
+        from sklearn.metrics import classification_report as sklearn_classification_report
+
+        sklearn_result = sklearn_classification_report(np_y_true, np_y_preds, output_dict=True)
+
+        for i in range(n_classes):
+            label_i = labels[i] if labels else str(i)
+            assert pytest.approx(res[label_i]["precision"] == sklearn_result[str(i)]["precision"])
+            assert pytest.approx(res[label_i]["f1-score"] == sklearn_result[str(i)]["f1-score"])
+            assert pytest.approx(res[label_i]["recall"] == sklearn_result[str(i)]["recall"])
+        assert pytest.approx(res["macro avg"]["precision"] == sklearn_result["macro avg"]["precision"])
+        assert pytest.approx(res["macro avg"]["recall"] == sklearn_result["macro avg"]["recall"])
+        assert pytest.approx(res["macro avg"]["f1-score"] == sklearn_result["macro avg"]["f1-score"])
+
+    for _ in range(3):
+        # check multiple random inputs as random exact occurencies are rare
+        metric_devices = ["cpu"]
+        if device.type != "xla":
+            metric_devices.append(idist.device())
+        for metric_device in metric_devices:
+            _test(metric_device, 1)
+            _test(metric_device, 2)
+            _test(metric_device, 1, ["0", "1", "2", "3", "4", "5", "6"])
+            _test(metric_device, 2, ["0", "1", "2", "3", "4", "5", "6"])
+
+
+@pytest.mark.multinode_distributed
+@pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support")
+@pytest.mark.skipif("GPU_MULTINODE_DISTRIB" not in os.environ, reason="Skip if not multi-node distributed")
+def test_multinode_distrib_gpu(distributed_context_multi_node_nccl):
+
+    device = torch.device(f"cuda:{distributed_context_multi_node_nccl['local_rank']}")
+    _test_integration_multiclass(device, True)
+    _test_integration_multiclass(device, False)
+    _test_integration_multilabel(device, True)
+    _test_integration_multilabel(device, False)
+
+
+@pytest.mark.multinode_distributed
+@pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support")
+@pytest.mark.skipif("MULTINODE_DISTRIB" not in os.environ, reason="Skip if not multi-node distributed")
+def test_multinode_distrib_cpu(distributed_context_multi_node_gloo):
+    device = torch.device("cpu")
+    _test_integration_multiclass(device, True)
+    _test_integration_multiclass(device, False)
+    _test_integration_multilabel(device, True)
+    _test_integration_multilabel(device, False)
+
+
+@pytest.mark.distributed
+@pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support")
+def test_distrib_cpu(local_rank, distributed_context_single_node_gloo):
+    device = torch.device("cpu")
+    _test_integration_multiclass(device, True)
+    _test_integration_multiclass(device, False)
+    _test_integration_multilabel(device, True)
+    _test_integration_multilabel(device, False)
+
+
+def _test_distrib_xla_nprocs(index):
+
+    device = idist.device()
+    _test_integration_multiclass(device, True)
+    _test_integration_multiclass(device, False)
+    _test_integration_multilabel(device, True)
+    _test_integration_multilabel(device, False)
+
+
+@pytest.mark.tpu
+@pytest.mark.skipif("NUM_TPU_WORKERS" not in os.environ, reason="Skip if no NUM_TPU_WORKERS in env vars")
+@pytest.mark.skipif(not idist.has_xla_support, reason="Skip if no PyTorch XLA package")
+def test_distrib_xla_nprocs(xmp_executor):
+    n = int(os.environ["NUM_TPU_WORKERS"])
+    xmp_executor(_test_distrib_xla_nprocs, args=(), nprocs=n)
+
+
+def to_numpy_multilabel(y):
+    # reshapes input array to (N x ..., C)
+    y = y.transpose(1, 0).cpu().numpy()
+    num_classes = y.shape[0]
+    y = y.reshape((num_classes, -1)).transpose(1, 0)
+    return y