ConfusionMatrix#
-
class
ignite.metrics.confusion_matrix.
ConfusionMatrix
(num_classes, average=None, output_transform=<function ConfusionMatrix.<lambda>>, device=device(type='cpu'))[source]# Calculates confusion matrix for multi-class data.
update
must receive output of the form(y_pred, y)
or{'y_pred': y_pred, 'y': y}
.y_pred must contain logits and has the following shape (batch_size, num_classes, …). If you are doing binary classification, see Note for an example on how to get this.
y should have the following shape (batch_size, …) and contains ground-truth class indices with or without the background class. During the computation, argmax of y_pred is taken to determine predicted classes.
- Parameters
num_classes (int) – Number of classes, should be > 1. See notes for more details.
average (Optional[str]) – confusion matrix values averaging schema: None, “samples”, “recall”, “precision”. Default is None. If average=”samples” then confusion matrix values are normalized by the number of seen samples. If average=”recall” then confusion matrix values are normalized such that diagonal values represent class recalls. If average=”precision” then confusion matrix values are normalized such that diagonal values represent class precisions.
output_transform (Callable) – a callable that is used to transform the
Engine
’sprocess_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.device (Union[str, torch.device]) – specifies which device updates are accumulated on. Setting the metric’s device to be the same as your
update
arguments ensures theupdate
method is non-blocking. By default, CPU.
Note
In case of the targets y in (batch_size, …) format, target indices between 0 and num_classes only contribute to the confusion matrix and others are neglected. For example, if num_classes=20 and target index equal 255 is encountered, then it is filtered out.
If you are doing binary classification with a single output unit, you may have to transform your network output, so that you have one value for each class. E.g. you can transform your network output into a one-hot vector with:
def binary_one_hot_output_transform(output): y_pred, y = output y_pred = torch.sigmoid(y_pred).round().long() y_pred = ignite.utils.to_onehot(y_pred, 2) y = y.long() return y_pred, y metrics = { "confusion_matrix": ConfusionMatrix(2, output_transform=binary_one_hot_output_transform), } evaluator = create_supervised_evaluator( model, metrics=metrics, output_transform=lambda x, y, y_pred: (y_pred, y) )
Methods
Attaches current metric to provided engine.
Helper method to compute metric’s value and put into the engine.
Computes the metric based on it’s accumulated state.
Detaches current metric from the engine and no metric’s computation is done during the run.
Checks if current metric is attached to provided engine.
Helper method to update metric’s computation.
Normalize given matrix with given average.
Resets the metric to it’s initial state.
Helper method to start data gathering for metric’s computation.
Updates the metric’s state using the passed batch output.
-
attach
(engine, name, usage=<ignite.metrics.metric.EpochWise object>)# Attaches current metric to provided engine. On the end of engine’s run, engine.state.metrics dictionary will contain computed metric’s value under provided name.
- Parameters
engine (ignite.engine.engine.Engine) – the engine to which the metric must be attached
name (str) – the name of the metric to attach
usage (Union[str, ignite.metrics.metric.MetricUsage]) – the usage of the metric. Valid string values should be
ignite.metrics.metric.EpochWise.usage_name
(default) orignite.metrics.metric.BatchWise.usage_name
.
- Return type
Example:
metric = ... metric.attach(engine, "mymetric") assert "mymetric" in engine.run(data).metrics assert metric.is_attached(engine)
Example with usage:
metric = ... metric.attach(engine, "mymetric", usage=BatchWise.usage_name) assert "mymetric" in engine.run(data).metrics assert metric.is_attached(engine, usage=BatchWise.usage_name)
-
completed
(engine, name)# Helper method to compute metric’s value and put into the engine. It is automatically attached to the engine with
attach()
. If metrics’ value is torch tensor, it is explicitly sent to CPU device.- Parameters
engine (ignite.engine.engine.Engine) – the engine to which the metric must be attached
name (str) – the name of the metric used as key in dict engine.state.metrics
- Return type
Changed in version 0.4.3: Added dict in metrics results.
Changed in version 0.4.5: metric’s value is put on CPU if torch tensor.
-
compute
()[source]# Computes the metric based on it’s accumulated state.
By default, this is called at the end of each epoch.
- Returns
- the actual quantity of interest. However, if a
Mapping
is returned, it will be (shallow) flattened into engine.state.metrics whencompleted()
is called. - Return type
Any
- Raises
NotComputableError – raised when the metric cannot be computed.
-
detach
(engine, usage=<ignite.metrics.metric.EpochWise object>)# Detaches current metric from the engine and no metric’s computation is done during the run. This method in conjunction with
attach()
can be useful if several metrics need to be computed with different periods. For example, one metric is computed every training epoch and another metric (e.g. more expensive one) is done every n-th training epoch.- Parameters
engine (ignite.engine.engine.Engine) – the engine from which the metric must be detached
usage (Union[str, ignite.metrics.metric.MetricUsage]) – the usage of the metric. Valid string values should be ‘epoch_wise’ (default) or ‘batch_wise’.
- Return type
Example:
metric = ... engine = ... metric.detach(engine) assert "mymetric" not in engine.run(data).metrics assert not metric.is_attached(engine)
Example with usage:
metric = ... engine = ... metric.detach(engine, usage="batch_wise") assert "mymetric" not in engine.run(data).metrics assert not metric.is_attached(engine, usage="batch_wise")
-
is_attached
(engine, usage=<ignite.metrics.metric.EpochWise object>)# Checks if current metric is attached to provided engine. If attached, metric’s computed value is written to engine.state.metrics dictionary.
- Parameters
engine (ignite.engine.engine.Engine) – the engine checked from which the metric should be attached
usage (Union[str, ignite.metrics.metric.MetricUsage]) – the usage of the metric. Valid string values should be ‘epoch_wise’ (default) or ‘batch_wise’.
- Return type
-
iteration_completed
(engine)# Helper method to update metric’s computation. It is automatically attached to the engine with
attach()
.Note
engine.state.output
is used to compute metric values. The majority of implemented metrics accepts the following formats forengine.state.output
:(y_pred, y)
or{'y_pred': y_pred, 'y': y}
.y_pred
andy
can be torch tensors or list of tensors/numbers if applicable.- Parameters
engine (ignite.engine.engine.Engine) – the engine to which the metric must be attached
- Return type
Changed in version 0.4.5:
y_pred
andy
can be torch tensors or list of tensors/numbers
-
static
normalize
(matrix, average)[source]# Normalize given matrix with given average.
- Parameters
matrix (torch.Tensor) –
average (str) –
- Return type
-
reset
()[source]# Resets the metric to it’s initial state.
By default, this is called at the start of each epoch.
- Return type
-
started
(engine)# Helper method to start data gathering for metric’s computation. It is automatically attached to the engine with
attach()
.- Parameters
engine (ignite.engine.engine.Engine) – the engine to which the metric must be attached
- Return type
-
update
(output)[source]# Updates the metric’s state using the passed batch output.
By default, this is called once for each batch.
- Parameters
output (Sequence[torch.Tensor]) – the is the output from the engine’s process function.
- Return type