torch_concepts.nn.modules.metrics.ConceptMetrics¶
- class ConceptMetrics(annotations: Annotations, fn_collection: GroupConfig, summary_metrics: bool = True, perconcept_metrics: bool | List[str] = False)[source]¶
Metrics manager for concept-based models with automatic type-aware routing.
This class organizes and manages metrics for different concept types (binary, categorical, continuous) with support for both summary metrics (aggregated across all concepts of a type) and per-concept metrics (individual tracking per concept).
The class automatically routes predictions to the appropriate metrics based on concept types defined in the annotations, handles different metric instantiation patterns, and maintains independent metric tracking across train/val/test splits.
- Parameters:
annotations (Annotations) – Concept annotations containing labels, types, and cardinalities. Should include axis 1 (concept axis) with metadata specifying concept types as ‘discrete’ or ‘continuous’.
fn_collection (GroupConfig) –
Metric configurations organized by concept type (‘binary’, ‘categorical’, ‘continuous’). Each metric can be specified in three ways:
Pre-instantiated metric: Pass an already instantiated metric object for full control over all parameters.
Example:
'accuracy': torchmetrics.classification.BinaryAccuracy(threshold=0.6)
Class with user kwargs: Pass a tuple of (MetricClass, kwargs_dict) to provide custom parameters while letting ConceptMetrics handle concept-specific parameters like num_classes automatically.
Example:
'accuracy': (torchmetrics.classification.MulticlassAccuracy, {'average': 'macro'})
Class only: Pass just the metric class and let ConceptMetrics handle all instantiation with appropriate concept-specific parameters.
Example:
'accuracy': torchmetrics.classification.MulticlassAccuracy
summary_metrics (bool, optional) – Whether to compute summary metrics that aggregate performance across all concepts of each type. Defaults to True.
perconcept_metrics (Union[bool, List[str]], optional) –
Controls per-concept metric tracking. Options:
False: No per-concept tracking (default)
True: Track all concepts individually
List[str]: Track only the specified concept names
- train_metrics¶
Metrics for training split
- Type:
MetricCollection
- val_metrics¶
Metrics for validation split
- Type:
MetricCollection
- test_metrics¶
Metrics for test split
- Type:
MetricCollection
- Raises:
NotImplementedError – If continuous concepts are found (not yet supported)
ValueError – If metric configuration doesn’t match concept types, or if user provides num_classes when it should be set automatically
Example
Basic usage with pre-instantiated metrics:
import torch import torchmetrics from torch_concepts import Annotations, AxisAnnotation from torch_concepts.nn.modules.metrics import ConceptMetrics from torch_concepts.nn.modules.utils import GroupConfig # Define concept structure annotations = Annotations({ 1: AxisAnnotation( labels=('round', 'smooth'), cardinalities=[1, 1], metadata={ 'round': {'type': 'discrete'}, 'smooth': {'type': 'discrete'} } ) }) # Create metrics with pre-instantiated objects metrics = ConceptMetrics( annotations=annotations, fn_collection=GroupConfig( binary={ 'accuracy': torchmetrics.classification.BinaryAccuracy(), 'f1': torchmetrics.classification.BinaryF1Score() } ), summary_metrics=True, perconcept_metrics=False ) # Simulate training batch predictions = torch.randn(32, 2) # endogenous predictions targets = torch.randint(0, 2, (32, 2)) # binary targets # Update metrics metrics.update(pred=predictions, target=targets, split='train') # Compute at epoch end results = metrics.compute('train') print(results) # {'train/SUMMARY-binary_accuracy': ..., 'train/SUMMARY-binary_f1': ...} # Reset for next epoch metrics.reset('train')
Using class + kwargs for flexible configuration:
# Mixed concept types with custom metric parameters annotations = Annotations({ 1: AxisAnnotation( labels=('binary1', 'binary2', 'category'), cardinalities=[1, 1, 5], metadata={ 'binary1': {'type': 'discrete'}, 'binary2': {'type': 'discrete'}, 'category': {'type': 'discrete'} } ) }) metrics = ConceptMetrics( annotations=annotations, fn_collection=GroupConfig( binary={ # Custom threshold 'accuracy': (torchmetrics.classification.BinaryAccuracy, {'threshold': 0.6}) }, categorical={ # Custom averaging, num_classes added automatically 'accuracy': (torchmetrics.classification.MulticlassAccuracy, {'average': 'macro'}) } ), summary_metrics=True, perconcept_metrics=True # Track all concepts individually ) # Predictions: 2 binary + 5 categorical = 7 dimensions predictions = torch.randn(16, 7) targets = torch.cat([ torch.randint(0, 2, (16, 2)), # binary torch.randint(0, 5, (16, 1)) # categorical ], dim=1) metrics.update(pred=predictions, target=targets, split='train') results = metrics.compute('train') # Results include both summary and per-concept metrics: # 'train/SUMMARY-binary_accuracy' # 'train/SUMMARY-categorical_accuracy' # 'train/binary1_accuracy' # 'train/binary2_accuracy' # 'train/category_accuracy'
Selective per-concept tracking:
# Track only specific concepts metrics = ConceptMetrics( annotations=annotations, fn_collection=GroupConfig( binary={'accuracy': torchmetrics.classification.BinaryAccuracy} ), summary_metrics=True, perconcept_metrics=['binary1'] # Only track binary1 individually )
Integration with PyTorch Lightning:
import pytorch_lightning as pl class ConceptModel(pl.LightningModule): def __init__(self, annotations): super().__init__() self.model = ... # your model self.metrics = ConceptMetrics( annotations=annotations, fn_collection=GroupConfig( binary={'accuracy': torchmetrics.classification.BinaryAccuracy} ), summary_metrics=True ) def training_step(self, batch, batch_idx): x, concepts = batch preds = self.model(x) # Update metrics self.metrics.update(pred=preds, target=concepts, split='train') return loss def on_train_epoch_end(self): # Compute and log metrics metrics_dict = self.metrics.compute('train') self.log_dict(metrics_dict) self.metrics.reset('train')
Note
Continuous concepts are not yet supported and will raise NotImplementedError
For categorical concepts, ConceptMetrics automatically handles padding to the maximum cardinality when computing summary metrics
User-provided ‘num_classes’ parameter for categorical metrics will raise an error as it’s set automatically based on concept cardinalities
Each split (train/val/test) maintains independent metric state
See also
torch_concepts.nn.modules.utils.GroupConfig: Configuration helpertorch_concepts.annotations.Annotations: Concept annotationsTorchMetrics Documentation: Available metrics and their parameters
- __init__(annotations: Annotations, fn_collection: GroupConfig, summary_metrics: bool = True, perconcept_metrics: bool | List[str] = False)[source]¶
Initialize internal Module state, shared by both nn.Module and ScriptModule.
Methods
__init__(annotations, fn_collection[, ...])Initialize internal Module state, shared by both nn.Module and ScriptModule.
add_module(name, module)Add a child module to the current module.
apply(fn)Apply
fnrecursively to every submodule (as returned by.children()) as well as self.bfloat16()Casts all floating point parameters and buffers to
bfloat16datatype.buffers([recurse])Return an iterator over module buffers.
children()Return an iterator over immediate children modules.
compile(*args, **kwargs)Compile this Module's forward using
torch.compile().compute([split])Compute final metric values from accumulated state for a split.
cpu()Move all model parameters and buffers to the CPU.
cuda([device])Move all model parameters and buffers to the GPU.
double()Casts all floating point parameters and buffers to
doubledatatype.eval()Set the module in evaluation mode.
extra_repr()Return the extra representation of the module.
float()Casts all floating point parameters and buffers to
floatdatatype.forward(*input)Define the computation performed at every call.
get(key[, default])Get a metric collection by key (dict-like interface).
get_buffer(target)Return the buffer given by
targetif it exists, otherwise throw an error.get_extra_state()Return any extra state to include in the module's state_dict.
get_parameter(target)Return the parameter given by
targetif it exists, otherwise throw an error.get_submodule(target)Return the submodule given by
targetif it exists, otherwise throw an error.half()Casts all floating point parameters and buffers to
halfdatatype.ipu([device])Move all model parameters and buffers to the IPU.
load_state_dict(state_dict[, strict, assign])Copy parameters and buffers from
state_dictinto this module and its descendants.modules()Return an iterator over all modules in the network.
mtia([device])Move all model parameters and buffers to the MTIA.
named_buffers([prefix, recurse, ...])Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
named_children()Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
named_modules([memo, prefix, remove_duplicate])Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
named_parameters([prefix, recurse, ...])Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
parameters([recurse])Return an iterator over module parameters.
register_backward_hook(hook)Register a backward hook on the module.
register_buffer(name, tensor[, persistent])Add a buffer to the module.
register_forward_hook(hook, *[, prepend, ...])Register a forward hook on the module.
register_forward_pre_hook(hook, *[, ...])Register a forward pre-hook on the module.
register_full_backward_hook(hook[, prepend])Register a backward hook on the module.
register_full_backward_pre_hook(hook[, prepend])Register a backward pre-hook on the module.
register_load_state_dict_post_hook(hook)Register a post-hook to be run after module's
load_state_dict()is called.register_load_state_dict_pre_hook(hook)Register a pre-hook to be run before module's
load_state_dict()is called.register_module(name, module)Alias for
add_module().register_parameter(name, param)Add a parameter to the module.
register_state_dict_post_hook(hook)Register a post-hook for the
state_dict()method.register_state_dict_pre_hook(hook)Register a pre-hook for the
state_dict()method.requires_grad_([requires_grad])Change if autograd should record operations on parameters in this module.
reset([split])Reset metric state for one or all splits.
set_extra_state(state)Set extra state contained in the loaded state_dict.
set_submodule(target, module[, strict])Set the submodule given by
targetif it exists, otherwise throw an error.share_memory()state_dict(*args[, destination, prefix, ...])Return a dictionary containing references to the whole state of the module.
to(*args, **kwargs)Move and/or cast the parameters and buffers.
to_empty(*, device[, recurse])Move the parameters and buffers to the specified device without copying storage.
train([mode])Set the module in training mode.
type(dst_type)Casts all parameters and buffers to
dst_type.update(preds, target[, split])Update metrics with predictions and targets for a given split.
xpu([device])Move all model parameters and buffers to the XPU.
zero_grad([set_to_none])Reset gradients of all model parameters.
Attributes
T_destinationcall_super_initdump_patches