MetricEvaluator
The MetricEvaluator class provides a unified interface for computing all metrics with confidence intervals.
infer_ci.evaluator.MetricEvaluator
Unified evaluator for classification and regression metrics with confidence intervals.
This class provides a clean interface to compute various metrics with confidence intervals for both classification and regression tasks without needing to import individual metrics.
Available Metrics:
Classification: - accuracy - precision (PPV) - recall (TPR / Sensitivity) - specificity (TNR) - npv (Negative Predictive Value) - fpr (False Positive Rate) - f1 (F1 Score, Takahashi method) - precision_takahashi (Takahashi method) - recall_takahashi (Takahashi method) - auc (ROC AUC Score) Regression: - mae (Mean Absolute Error) - mse (Mean Squared Error) - rmse (Root Mean Squared Error) - r2 (Coefficient of Determination) - mape (Mean Absolute Percentage Error) - iou (Intersection over Union) - med_abs_err (Median Absolute Error) - mean_bia_dev (Mean Bias Deviation) - huber_loss (Huber Loss, pass delta=...) - exp_var_score (Explained Variance Score) - sym_mean_abs_per_error (Symmetric Mean Absolute Percentage Error) - rmse_log (Root Mean Squared Logarithmic Error) - adjusted_r2_score (Adjusted R², pass num_features=...)
Detection
- map (mAP@0.5:0.95 with CI)
- map50 (mAP@0.5 with CI)
- precision (Precision with CI)
- recall (Recall with CI)
Example:
evaluator = MetricEvaluator()
For regression
result = evaluator.evaluate( ... y_true=[1, 2, 3, 4, 5], ... y_pred=[1.1, 2.2, 2.8, 4.1, 4.9], ... task='regression', ... metric='mae', ... method='bootstrap_bca', ... plot=True ... ) ... # Specific metric function can also be called directly:
mae_val, ci = evaluator.mae( ... y_true=[1, 2, 3, 4, 5], ... y_pred=[1.1, 2.2, 2.8, 4.1, 4.9], ... confidence_level=0.95, ... method='jackknife' ... )For classification
result = evaluator.evaluate( ... y_true=[0, 1, 1, 0, 1], ... y_pred=[0, 1, 0, 0, 1], ... task='classification', ... metric='accuracy', ... method='wilson' ... )
Source code in src/infer_ci/evaluator.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 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 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 | |
evaluate(y_true=None, y_pred=None, task=None, metric=None, method='bootstrap_bca', confidence_level=0.95, compute_ci=True, plot=False, model=None, data=None, **kwargs)
Evaluate a metric with confidence intervals.
Parameters:
y_true : List[Union[int, float]], optional True labels/values (required for classification and regression tasks) y_pred : List[Union[int, float]], optional Predicted labels/values (required for classification and regression tasks) task : str or TaskType Task type ('classification', 'regression', or 'detection') metric : str Metric name (e.g., 'accuracy', 'mae', 'f1', 'map') method : str, optional Confidence interval method (default: 'bootstrap_bca') confidence_level : float, optional Confidence level (default: 0.95) compute_ci : bool, optional Whether to compute confidence intervals (default: True) plot : bool, optional Whether to create histogram plot for bootstrap methods (default: False) model : Any, optional Model object or path (required for detection tasks) data : str, optional Dataset configuration path (required for detection tasks) **kwargs : dict Additional arguments (e.g., n_resamples for bootstrap methods, n_iterations for detection tasks)
Returns:
Union[float, Tuple[float, Tuple[float, float]], Dict[str, Tuple[float, Tuple[float, float]]]] For classification/regression: If compute_ci=False: metric value If compute_ci=True: (metric_value, (lower_bound, upper_bound)) For detection: Dictionary with class names as keys and (mean_metric, (lower_CI, upper_CI)) as values
Example:
evaluator = MetricEvaluator()
Regression example
mae_val, ci = evaluator.evaluate( ... y_true=[1, 2, 3, 4, 5], ... y_pred=[1.1, 2.1, 2.9, 4.1, 4.9], ... task='regression', ... metric='mae', ... method='jackknife' ... ) print(f"MAE: {mae_val:.3f}, 95% CI: [{ci[0]:.3f}, {ci[1]:.3f}]")
Detection example
from ultralytics import YOLO model = YOLO('yolov8n.pt') results = model.predict(source='dataset/images') map_val, (lower, upper) = evaluator.evaluate( ... y_true='dataset', ... y_pred=results, ... task='detection', ... metric='map', ... method='bootstrap_percentile', ... n_resamples=1000 ... ) print(f"mAP@0.5:0.95: {map_val:.3f} [{lower:.3f}, {upper:.3f}]")
Source code in src/infer_ci/evaluator.py
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 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 | |
get_available_metrics(task)
Get list of available metrics for a given task type.
Parameters:
task : str or TaskType The task type ('classification' or 'regression')
Returns:
List[str]: List of available metric names
Source code in src/infer_ci/evaluator.py
get_available_methods(task)
Get list of available confidence interval methods for a given task type.
Parameters:
task : str or TaskType The task type ('classification' or 'regression')
Returns:
List[str]: List of available method names
Source code in src/infer_ci/evaluator.py
Overview
MetricEvaluator is the recommended way to compute metrics in infer-ci. It provides a consistent interface across all metric types (classification, regression, detection) and handles method selection automatically.
Basic Usage
from infer_ci import MetricEvaluator
import numpy as np
# Initialize evaluator
evaluator = MetricEvaluator()
# Binary classification example
y_true = np.array([0, 1, 1, 0, 1, 1, 0, 0, 1, 1])
y_pred = np.array([0, 1, 1, 0, 0, 1, 0, 0, 1, 1])
# Compute accuracy with Wilson interval
accuracy, ci = evaluator.evaluate(
y_true=y_true,
y_pred=y_pred,
task='classification',
metric='accuracy',
method='wilson'
)
print(f"Accuracy: {accuracy:.3f}")
print(f"95% CI: [{ci[0]:.3f}, {ci[1]:.3f}]")
Supported Tasks and Metrics
Classification Task
# Get all available classification metrics
metrics = evaluator.get_available_metrics('classification')
print(metrics)
# ['accuracy', 'precision', 'recall', 'f1', 'specificity', 'npv', 'fpr', 'auc', ...]
Available metrics:
- accuracy: Overall accuracy
- precision: Positive Predictive Value
- recall: True Positive Rate/Sensitivity
- f1: F1 Score (supports binary, macro, micro averaging)
- specificity: True Negative Rate
- npv: Negative Predictive Value
- fpr: False Positive Rate
- auc: ROC AUC Score
- precision_takahashi: Precision with Takahashi method
- recall_takahashi: Recall with Takahashi method
Regression Task
# Get all available regression metrics
metrics = evaluator.get_available_metrics('regression')
print(metrics)
# ['mae', 'mse', 'rmse', 'r2', 'mape', 'iou', 'med_abs_err', 'mean_bia_dev',
# 'huber_loss', 'exp_var_score', 'sym_mean_abs_per_error', 'rmse_log',
# 'adjusted_r2_score']
Available metrics:
- mae: Mean Absolute Error
- mse: Mean Squared Error
- rmse: Root Mean Squared Error
- r2: R² Score
- mape: Mean Absolute Percentage Error
- iou: Intersection over Union
- med_abs_err: Median Absolute Error
- mean_bia_dev: Mean Bias Deviation (mean of y_pred - y_true)
- huber_loss: Huber Loss (set the threshold with delta=..., default 1.0)
- exp_var_score: Explained Variance Score
- sym_mean_abs_per_error: Symmetric Mean Absolute Percentage Error (SMAPE)
- rmse_log: Root Mean Squared Logarithmic Error (RMSLE). Values must be greater than -1.
- adjusted_r2_score: Adjusted R². Needs the number of model features:
Detection Task
# Object detection example
from ultralytics import YOLO
model = YOLO('yolov8n.pt')
results = model.predict(source='images/', verbose=False)
map_value, ci = evaluator.evaluate(
y_true='dataset_path', # Path to dataset or ground truth
y_pred=results,
task='detection',
metric='map',
method='bootstrap_percentile',
n_resamples=1000
)
Available metrics:
- map: mean Average Precision @0.5:0.95
- map50: mean Average Precision @0.5
- precision: Detection precision
- recall: Detection recall
Available CI Methods
Check which methods are available for each task:
# Classification methods
methods = evaluator.get_available_methods('classification')
print(methods)
# ['wilson', 'normal', 'agresti_coull', 'beta', 'jeffreys', 'binom_test',
# 'bootstrap_bca', 'bootstrap_percentile', 'jackknife']
# Regression methods
methods = evaluator.get_available_methods('regression')
print(methods)
# ['bootstrap_bca', 'bootstrap_percentile', 'jackknife']
Advanced Usage
Comparing Different CI Methods
import numpy as np
y_true = np.array([0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1])
y_pred = np.array([0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1])
evaluator = MetricEvaluator()
# Compare different methods
methods = ['wilson', 'normal', 'agresti_coull', 'bootstrap_bca']
for method in methods:
acc, ci = evaluator.evaluate(
y_true=y_true,
y_pred=y_pred,
task='classification',
metric='accuracy',
method=method,
n_resamples=2000 # Only used by bootstrap
)
width = ci[1] - ci[0]
print(f"{method:20s}: {acc:.3f} [{ci[0]:.3f}, {ci[1]:.3f}] (width: {width:.3f})")
Output:
wilson : 0.800 [0.519, 0.938] (width: 0.419)
normal : 0.800 [0.596, 1.004] (width: 0.408)
agresti_coull : 0.800 [0.529, 0.933] (width: 0.404)
bootstrap_bca : 0.800 [0.533, 0.933] (width: 0.400)
Regression with Visualization
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
# Generate data
X, y = make_regression(n_samples=100, n_features=5, noise=10.0, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
# Train model
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
# Evaluate with visualization
evaluator = MetricEvaluator()
r2_value, ci = evaluator.evaluate(
y_true=y_test,
y_pred=y_pred,
task='regression',
metric='r2',
method='bootstrap_bca',
n_resamples=2000,
plot=True # Generate histogram of bootstrap samples
)
print(f"R² Score: {r2_value:.3f}")
print(f"95% CI: [{ci[0]:.3f}, {ci[1]:.3f}]")
Multi-class Classification with Macro/Micro Averaging
y_true = [0, 1, 2, 2, 2, 1, 1, 1, 0, 2, 2, 1, 0, 2, 2, 1, 2, 2, 1, 1]
y_pred = [0, 1, 0, 0, 2, 1, 1, 1, 0, 2, 2, 1, 0, 1, 2, 1, 2, 2, 1, 1]
evaluator = MetricEvaluator()
# Macro F1 (average across classes)
macro_f1, ci = evaluator.evaluate(
y_true=y_true,
y_pred=y_pred,
task='classification',
metric='f1',
method='takahashi', # Analytical method for multi-class
average='macro'
)
print(f"Macro F1: {macro_f1:.3f} [{ci[0]:.3f}, {ci[1]:.3f}]")
# Micro F1 (aggregate contributions of all classes)
micro_f1, ci = evaluator.evaluate(
y_true=y_true,
y_pred=y_pred,
task='classification',
metric='f1',
method='takahashi',
average='micro'
)
print(f"Micro F1: {micro_f1:.3f} [{ci[0]:.3f}, {ci[1]:.3f}]")
Parameters
evaluate() method
Parameters:
- y_true (array-like): Ground truth labels/values
- y_pred (array-like): Predicted labels/values
- task (str): Type of task - 'classification', 'regression', or 'detection'
- metric (str): Name of the metric to compute
- method (str, optional): CI calculation method (default: 'bootstrap_bca')
- confidence_interval (float, optional): Confidence level (default: 0.95)
- n_resamples (int, optional): Bootstrap resamples (default: 2000)
- random_state (int, optional): Random seed for reproducibility
- plot (bool, optional): Generate visualization (default: False)
- **kwargs: Additional metric-specific parameters
Returns:
- metric_value (float): The computed metric value
- ci (tuple): Confidence interval (lower_bound, upper_bound)
Method Selection Guide
When to use analytical methods (Classification)
- wilson: Recommended for most binary classification metrics (accuracy, precision, recall)
- normal: Simple but may give intervals outside [0,1] for small samples
- agresti_coull: Good alternative to Wilson
- beta/jeffreys: Conservative intervals, good for small samples
- binom_test: Exact method, computationally intensive
When to use bootstrap methods
- bootstrap_bca: Recommended default, corrects for bias and skewness
- bootstrap_percentile: Simpler alternative, good for symmetric distributions
- bootstrap_basic: Basic method, less accurate than BCA
When to use jackknife
- jackknife: Good for small samples, less computationally intensive than bootstrap
When to use Takahashi methods
- takahashi: Specifically for multi-class F1, precision, recall with macro/micro averaging
Error Handling
# Invalid task
try:
evaluator.evaluate(y_true, y_pred, task='invalid', metric='accuracy')
except ValueError as e:
print(e) # "Task must be one of: classification, regression, detection"
# Invalid metric for task
try:
evaluator.evaluate(y_true, y_pred, task='regression', metric='accuracy')
except ValueError as e:
print(e) # "Metric 'accuracy' not available for regression task"
# Invalid method
try:
evaluator.evaluate(y_true, y_pred, task='regression', metric='mae', method='wilson')
except ValueError as e:
print(e) # "Method 'wilson' not available for regression task"