---
title: Classwise Wrapper
description: Wrapper metric for altering the output of classification metrics.
canonical: 'https://lightning.ai/docs/torchmetrics/stable/wrappers/classwise_wrapper'
---
# Classwise Wrapper {#classwise-wrapper}

## Module Interface {#module-interface}

### `class torchmetrics.wrappers.ClasswiseWrapper(metric, labels=None, prefix=None, postfix=None)` {#torchmetrics.wrappers.ClasswiseWrapper}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/wrappers/classwise.py#L32-L244)

Wrapper metric for altering the output of classification metrics.

This metric works together with classification metrics that returns multiple values (one value per class) such that label information can be automatically included in the output.

Parameters:

*   **metric** ([`Metric`](/docs/torchmetrics/1.9.0/api-reference/metric.md#torchmetrics.Metric "torchmetrics.metric.Metric")) – base metric that should be wrapped. It is assumed that the metric outputs a single tensor that is split along the first dimension.
    
*   **labels** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`list`](https://docs.python.org/3/builtins/stdtypes.html#list "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")\]\]) – list of strings indicating the different classes.
    
*   **prefix** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")\]) – string that is prepended to the metric names.
    
*   **postfix** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")\]) – string that is appended to the metric names.
    

Example::

Basic example where the output of a metric is unwrapped into a dictionary with the class index as keys:

```python
>>> from torch import randint, randn
>>> from torchmetrics.wrappers import ClasswiseWrapper
>>> from torchmetrics.classification import MulticlassAccuracy
>>> metric = ClasswiseWrapper(MulticlassAccuracy(num_classes=3, average=None))
>>> preds = randn(10, 3).softmax(dim=-1)
>>> target = randint(3, (10,))
>>> metric(preds, target)  
{'multiclassaccuracy_0': tensor(0.5000),
 'multiclassaccuracy_1': tensor(0.7500),
 'multiclassaccuracy_2': tensor(0.)}
```

Example::

Using custom name via prefix and postfix:

```python
>>> from torch import randint, randn
>>> from torchmetrics.wrappers import ClasswiseWrapper
>>> from torchmetrics.classification import MulticlassAccuracy
>>> metric_pre = ClasswiseWrapper(MulticlassAccuracy(num_classes=3, average=None), prefix="acc-")
>>> metric_post = ClasswiseWrapper(MulticlassAccuracy(num_classes=3, average=None), postfix="-acc")
>>> preds = randn(10, 3).softmax(dim=-1)
>>> target = randint(3, (10,))
>>> metric_pre(preds, target)  
{'acc-0': tensor(0.3333), 'acc-1': tensor(0.6667), 'acc-2': tensor(0.)}
>>> metric_post(preds, target)  
{'0-acc': tensor(0.3333), '1-acc': tensor(0.6667), '2-acc': tensor(0.)}
```

Example::

Providing labels as a list of strings:

```python
>>> from torch import randint, randn
>>> from torchmetrics.wrappers import ClasswiseWrapper
>>> from torchmetrics.classification import MulticlassAccuracy
>>> metric = ClasswiseWrapper(
...    MulticlassAccuracy(num_classes=3, average=None),
...    labels=["horse", "fish", "dog"]
... )
>>> preds = randn(10, 3).softmax(dim=-1)
>>> target = randint(3, (10,))
>>> metric(preds, target)  
{'multiclassaccuracy_horse': tensor(0.),
 'multiclassaccuracy_fish': tensor(0.3333),
 'multiclassaccuracy_dog': tensor(0.4000)}
```

Example::

Classwise can also be used in combination with [`MetricCollection`](/docs/torchmetrics/1.9.0/user-guide/overview.md#torchmetrics.MetricCollection "torchmetrics.MetricCollection"). In this case, everything will be flattened into a single dictionary:

```python
>>> from torch import randint, randn
>>> from torchmetrics import MetricCollection
>>> from torchmetrics.wrappers import ClasswiseWrapper
>>> from torchmetrics.classification import MulticlassAccuracy, MulticlassRecall
>>> labels = ["horse", "fish", "dog"]
>>> metric = MetricCollection(
...     {'multiclassaccuracy': ClasswiseWrapper(MulticlassAccuracy(num_classes=3, average=None), labels),
...     'multiclassrecall': ClasswiseWrapper(MulticlassRecall(num_classes=3, average=None), labels)}
... )
>>> preds = randn(10, 3).softmax(dim=-1)
>>> target = randint(3, (10,))
>>> metric(preds, target)  
{'multiclassaccuracy_horse': tensor(0.6667),
 'multiclassaccuracy_fish': tensor(0.3333),
 'multiclassaccuracy_dog': tensor(0.5000),
 'multiclassrecall_horse': tensor(0.6667),
 'multiclassrecall_fish': tensor(0.3333),
 'multiclassrecall_dog': tensor(0.5000)}
```

#### `compute()` {#torchmetrics.wrappers.ClasswiseWrapper.compute}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/wrappers/classwise.py#L175-L177)

Compute metric.

Return type:

[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")\]

#### `forward(*args, **kwargs)` {#torchmetrics.wrappers.ClasswiseWrapper.forward}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/wrappers/classwise.py#L167-L169)

Calculate on batch and accumulate to global state.

Return type:

[`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")

#### `plot(val=None, ax=None)` {#torchmetrics.wrappers.ClasswiseWrapper.plot}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/wrappers/classwise.py#L183-L225)

Plot a single or multiple values from the metric.

Parameters:

*   **val** (`Union`\[[`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)"), [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence "(in Python v3.15)")\[[`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")\], [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – Either a single result from calling metric.forward or metric.compute or a list of these results. If no value is provided, will automatically call metric.compute and plot that result.
    
*   **ax** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Axes`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.html#matplotlib.axes.Axes "(in Matplotlib v3.11.2)")\]) – An matplotlib axis object. If provided will add plot to that axis
    

Return type:

[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple "(in Python v3.15)")\[[`Figure`](https://matplotlib.org/stable/api/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure "(in Matplotlib v3.11.2)"), `Union`\[[`Axes`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.html#matplotlib.axes.Axes "(in Matplotlib v3.11.2)"), [`ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray "(in NumPy v2.5)")\]\]

Returns:

Figure and Axes object

Raises:

[**ModuleNotFoundError**](https://docs.python.org/3/builtins/exceptions.html#ModuleNotFoundError "(in Python v3.15)") – If matplotlib is not installed

```python
>>> # Example plotting a single value
>>> import torch
>>> from torchmetrics.wrappers import ClasswiseWrapper
>>> from torchmetrics.classification import MulticlassAccuracy
>>> metric = ClasswiseWrapper(MulticlassAccuracy(num_classes=3, average=None))
>>> metric.update(torch.randint(3, (20,)), torch.randint(3, (20,)))
>>> fig_, ax_ = metric.plot()
```

[![../../\_images/classwise\_wrapper-1.png](/docs/torchmetrics/1.9.0/static/_images/classwise_wrapper-1.png)](/docs/torchmetrics/1.9.0/static/_images/classwise_wrapper-1.png)

```python
>>> # Example plotting multiple values
>>> import torch
>>> from torchmetrics.wrappers import ClasswiseWrapper
>>> from torchmetrics.classification import MulticlassAccuracy
>>> metric = ClasswiseWrapper(MulticlassAccuracy(num_classes=3, average=None))
>>> values = [ ]
>>> for _ in range(3):
...     values.append(metric(torch.randint(3, (20,)), torch.randint(3, (20,))))
>>> fig_, ax_ = metric.plot(values)
```

[![../../\_images/classwise\_wrapper-2.png](/docs/torchmetrics/1.9.0/static/_images/classwise_wrapper-2.png)](/docs/torchmetrics/1.9.0/static/_images/classwise_wrapper-2.png)

#### `reset()` {#torchmetrics.wrappers.ClasswiseWrapper.reset}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/wrappers/classwise.py#L179-L181)

Reset metric.

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `update(*args, **kwargs)` {#torchmetrics.wrappers.ClasswiseWrapper.update}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/wrappers/classwise.py#L171-L173)

Update state.

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `property higher_is_better: Optional[bool]` {#torchmetrics.wrappers.ClasswiseWrapper.higher_is_better}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/torchmetrics/wrappers.py)

Return if the metric is higher the better.

---

**Navigation**

- Parent: [Wrappers](/docs/torchmetrics/1.9.0/wrappers.md)
