Metrics¶
Metric configuration and management for training.
MetricConfig¶
Configuration for a single metric.
API Reference¶
autotimm.MetricConfig
dataclass
¶
Configuration for a single metric.
All parameters are required - no defaults are provided to ensure explicit configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique identifier for this metric (used in logging). |
required |
backend
|
str
|
Metric backend type. One of |
required |
metric_class
|
str
|
The metric class name (for torchmetrics/custom). |
required |
params
|
dict[str, Any]
|
Parameters passed to the metric constructor/function. |
required |
stages
|
list[str]
|
List of stages where this metric applies: |
required |
log_on_step
|
bool
|
Whether to log on each step. |
False
|
log_on_epoch
|
bool
|
Whether to log on epoch end. |
True
|
prog_bar
|
bool
|
Whether to show in progress bar. |
False
|
Example
config = MetricConfig( ... name="accuracy", ... backend="torchmetrics", ... metric_class="Accuracy", ... params={"task": "multiclass"}, ... stages=["train", "val", "test"], ... prog_bar=True, ... )
Source code in src/autotimm/core/metrics.py
Usage Examples¶
Basic Accuracy¶
from autotimm import MetricConfig
accuracy = MetricConfig(
name="accuracy",
backend="torchmetrics",
metric_class="Accuracy",
params={"task": "multiclass"},
stages=["train", "val", "test"],
prog_bar=True,
)
F1 Score¶
f1 = MetricConfig(
name="f1",
backend="torchmetrics",
metric_class="F1Score",
params={"task": "multiclass", "average": "macro"},
stages=["val", "test"],
)
Top-K Accuracy¶
top5 = MetricConfig(
name="top5_accuracy",
backend="torchmetrics",
metric_class="Accuracy",
params={"task": "multiclass", "top_k": 5},
stages=["val", "test"],
)
Custom Metric¶
custom = MetricConfig(
name="custom",
backend="custom",
metric_class="mypackage.metrics.CustomMetric",
params={"threshold": 0.5},
stages=["val"],
)
Parameters¶
| Parameter | Type | Default | Description |
|---|---|---|---|
name |
str |
Required | Unique identifier |
backend |
str |
Required | "torchmetrics" or "custom" |
metric_class |
str |
Required | Class name or full path |
params |
dict |
Required | Constructor parameters |
stages |
list[str] |
Required | ["train", "val", "test"] |
log_on_step |
bool |
False |
Log each step |
log_on_epoch |
bool |
True |
Log each epoch |
prog_bar |
bool |
False |
Show in progress bar |
MetricManager¶
Manages multiple metrics across training stages.
API Reference¶
autotimm.MetricManager ¶
Manages multiple metrics for training/validation/testing.
This class creates and manages metric instances from explicit configurations. No default values are provided - all configuration must be specified.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
configs
|
list[MetricConfig]
|
List of |
required |
num_classes
|
int
|
Number of classes (required for classification metrics). |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
train_metrics |
Dict of metrics for training stage. |
|
val_metrics |
Dict of metrics for validation stage. |
|
test_metrics |
Dict of metrics for test stage. |
Example
manager = MetricManager( ... configs=[ ... MetricConfig( ... name="accuracy", ... backend="torchmetrics", ... metric_class="Accuracy", ... params={"task": "multiclass"}, ... stages=["train", "val", "test"], ... prog_bar=True, ... ), ... MetricConfig( ... name="f1", ... backend="torchmetrics", ... metric_class="F1Score", ... params={"task": "multiclass", "average": "macro"}, ... stages=["val"], ... ), ... ], ... num_classes=10, ... ) train_metrics = manager.get_train_metrics()
Source code in src/autotimm/core/metrics.py
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | |
configs
property
¶
Return the configurations used to create the metrics.
__init__ ¶
Source code in src/autotimm/core/metrics.py
get_train_metrics ¶
Return ModuleDict of train metrics for Lightning module.
get_val_metrics ¶
Return ModuleDict of validation metrics for Lightning module.
get_test_metrics ¶
Return ModuleDict of test metrics for Lightning module.
get_metric_config ¶
Get the config for a specific metric.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stage
|
str
|
One of "train", "val", "test". |
required |
name
|
str
|
The metric name. |
required |
Returns:
| Type | Description |
|---|---|
MetricConfig | None
|
The MetricConfig if found, None otherwise. |
Source code in src/autotimm/core/metrics.py
get_metric_by_name ¶
Get a metric instance by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The metric name to search for. |
required |
stage
|
str | None
|
Optional stage to search in ("train", "val", "test"). If None, searches in order: val, train, test. |
None
|
Returns:
| Type | Description |
|---|---|
Module | None
|
The first matching metric instance, or None if not found. |
Source code in src/autotimm/core/metrics.py
get_config_by_name ¶
Get a metric config by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The metric name to search for. |
required |
Returns:
| Type | Description |
|---|---|
MetricConfig | None
|
The matching MetricConfig, or None if not found. |
Source code in src/autotimm/core/metrics.py
Usage Examples¶
Basic Usage¶
from autotimm import MetricConfig, MetricManager
def main():
metric_configs = [
MetricConfig(
name="accuracy",
backend="torchmetrics",
metric_class="Accuracy",
params={"task": "multiclass"},
stages=["train", "val", "test"],
),
MetricConfig(
name="f1",
backend="torchmetrics",
metric_class="F1Score",
params={"task": "multiclass", "average": "macro"},
stages=["val", "test"],
),
]
manager = MetricManager(configs=metric_configs, num_classes=10)
print(f"Number of metrics: {len(manager)}")
print(f"Number of classes: {manager.num_classes}")
if __name__ == "__main__":
main()
Access Stage Metrics¶
def main():
# ... create manager ...
train_metrics = manager.get_train_metrics() # ModuleDict
val_metrics = manager.get_val_metrics()
test_metrics = manager.get_test_metrics()
# Use in training loop
for name, metric in train_metrics.items():
metric.update(preds, targets)
value = metric.compute()
if __name__ == "__main__":
main()
Get Metric Config¶
def main():
# ... create manager ...
config = manager.get_metric_config("val", "accuracy")
print(config.prog_bar) # True
if __name__ == "__main__":
main()
Access Metrics by Name¶
def main():
# ... create manager ...
# Get metric instance by name
accuracy_metric = manager.get_metric_by_name("accuracy")
accuracy_metric = manager.get_metric_by_name("accuracy", stage="val")
# Get config by name
config = manager.get_config_by_name("accuracy")
print(config.stages) # ["train", "val", "test"]
if __name__ == "__main__":
main()
Iterate Over Configs¶
def main():
# ... create manager ...
# Iterate over all configs
for config in manager:
print(f"{config.name}: {config.stages}")
# Access by index
first_config = manager[0]
print(f"First metric: {first_config.name}")
# Length
print(f"Number of metrics: {len(manager)}")
if __name__ == "__main__":
main()
Parameters¶
| Parameter | Type | Description |
|---|---|---|
configs |
list[MetricConfig] |
List of metric configs |
num_classes |
int |
Number of classes |
Methods¶
| Method | Returns | Description |
|---|---|---|
get_train_metrics() |
ModuleDict |
Train stage metrics |
get_val_metrics() |
ModuleDict |
Validation stage metrics |
get_test_metrics() |
ModuleDict |
Test stage metrics |
get_metric_config(stage, name) |
MetricConfig \| None |
Get config by stage/name |
get_metric_by_name(name, stage) |
Module \| None |
Get metric instance by name |
get_config_by_name(name) |
MetricConfig \| None |
Get config by name |
len(manager) |
int |
Number of metric configs |
iter(manager) |
Iterator | Iterate over configs |
manager[i] |
MetricConfig |
Get config by index |
LoggingConfig¶
Configuration for enhanced logging during training.
API Reference¶
autotimm.LoggingConfig
dataclass
¶
Configuration for enhanced logging during training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
log_learning_rate
|
bool
|
Whether to log the current learning rate. |
required |
log_gradient_norm
|
bool
|
Whether to log gradient norms. |
required |
log_weight_norm
|
bool
|
Whether to log weight norms. |
False
|
log_confusion_matrix
|
bool
|
Whether to log confusion matrix at epoch end. |
False
|
log_predictions
|
bool
|
Whether to log sample predictions/images. |
False
|
predictions_per_epoch
|
int
|
Number of sample predictions to log per epoch. |
8
|
verbosity
|
int
|
Logging verbosity level (0=minimal, 1=normal, 2=verbose). |
1
|
Example
config = LoggingConfig( ... log_learning_rate=True, ... log_gradient_norm=True, ... log_confusion_matrix=True, ... )
Source code in src/autotimm/core/metrics.py
Usage Examples¶
Basic Logging¶
from autotimm import LoggingConfig
config = LoggingConfig(
log_learning_rate=True,
log_gradient_norm=True,
)
Full Logging¶
config = LoggingConfig(
log_learning_rate=True,
log_gradient_norm=True,
log_weight_norm=True,
log_confusion_matrix=True,
log_predictions=False,
predictions_per_epoch=8,
verbosity=2,
)
Parameters¶
| Parameter | Type | Default | Description |
|---|---|---|---|
log_learning_rate |
bool |
Required | Log LR each step |
log_gradient_norm |
bool |
Required | Log gradient norms |
log_weight_norm |
bool |
False |
Log weight norms |
log_confusion_matrix |
bool |
False |
Log confusion matrix |
log_predictions |
bool |
False |
Log sample predictions |
predictions_per_epoch |
int |
8 |
Predictions to log |
verbosity |
int |
1 |
0=minimal, 1=normal, 2=verbose |
Logged Values¶
| Metric | Key | Condition |
|---|---|---|
| Learning rate | train/lr |
log_learning_rate=True |
| Gradient norm | train/grad_norm |
log_gradient_norm=True |
| Weight norm | train/weight_norm |
log_weight_norm=True |
| Confusion matrix | val/confusion_matrix |
log_confusion_matrix=True |
Common Torchmetrics¶
Classification¶
| Metric Class | Common Params |
|---|---|
Accuracy |
task="multiclass", top_k=1 |
F1Score |
task="multiclass", average="macro" |
Precision |
task="multiclass", average="macro" |
Recall |
task="multiclass", average="macro" |
AUROC |
task="multiclass" |
ConfusionMatrix |
task="multiclass" |
Binary Classification¶
| Metric Class | Common Params |
|---|---|
Accuracy |
task="binary" |
F1Score |
task="binary" |
AUROC |
task="binary" |
Precision |
task="binary" |
Recall |
task="binary" |
Multi-Label Classification¶
Use torchmetrics.classification.Multilabel* metrics with ImageClassifier(multi_label=True).
These are resolved automatically from the torchmetrics.classification submodule.
| Metric Class | Common Params |
|---|---|
MultilabelAccuracy |
num_labels=N |
MultilabelF1Score |
num_labels=N, average="macro" |
MultilabelPrecision |
num_labels=N, average="macro" |
MultilabelRecall |
num_labels=N, average="macro" |
MultilabelAUROC |
num_labels=N |
MultilabelHammingDistance |
num_labels=N |
MetricConfig(
name="accuracy",
backend="torchmetrics",
metric_class="MultilabelAccuracy",
params={"num_labels": 4},
stages=["train", "val"],
prog_bar=True,
)
Note: num_classes and num_labels are auto-injected by MetricManager from the model's num_classes value. Auto-injected parameters that a metric doesn't accept are automatically filtered out.
Average Options¶
| Value | Description |
|---|---|
"micro" |
Global average |
"macro" |
Unweighted class average |
"weighted" |
Weighted by class support |
"none" |
Per-class values |
Full Example¶
from autotimm import (
AutoTrainer,
ImageClassifier,
ImageDataModule,
LoggerConfig,
LoggingConfig,
MetricConfig,
MetricManager,
)
def main():
# Define metrics
metric_configs = [
MetricConfig(
name="accuracy",
backend="torchmetrics",
metric_class="Accuracy",
params={"task": "multiclass"},
stages=["train", "val", "test"],
prog_bar=True,
),
MetricConfig(
name="top5_accuracy",
backend="torchmetrics",
metric_class="Accuracy",
params={"task": "multiclass", "top_k": 5},
stages=["val", "test"],
),
MetricConfig(
name="f1",
backend="torchmetrics",
metric_class="F1Score",
params={"task": "multiclass", "average": "macro"},
stages=["val", "test"],
prog_bar=True,
),
MetricConfig(
name="precision",
backend="torchmetrics",
metric_class="Precision",
params={"task": "multiclass", "average": "macro"},
stages=["test"],
),
MetricConfig(
name="recall",
backend="torchmetrics",
metric_class="Recall",
params={"task": "multiclass", "average": "macro"},
stages=["test"],
),
]
# Create MetricManager
metric_manager = MetricManager(configs=metric_configs, num_classes=10)
# Data
data = ImageDataModule(
data_dir="./data",
dataset_name="CIFAR10",
image_size=224,
batch_size=64,
)
# Create model
model = ImageClassifier(
backbone="resnet50",
num_classes=10,
metrics=metric_manager,
logging_config=LoggingConfig(
log_learning_rate=True,
log_gradient_norm=True,
log_confusion_matrix=True,
),
)
# Trainer
trainer = AutoTrainer(
max_epochs=10,
logger=[LoggerConfig(backend="tensorboard", params={"save_dir": "logs"})],
)
trainer.fit(model, datamodule=data)
trainer.test(model, datamodule=data)
if __name__ == "__main__":
main()