Skip to content

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
class 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'
    ... )
    """

    def __init__(self):
        """Initialize the MetricEvaluator with available metrics and methods."""

        # Classification metrics mapping
        self.classification_metrics = {
            'accuracy': accuracy_score,
            'precision': ppv_score,  # Positive Predictive Value
            'recall': tpr_score,     # True Positive Rate / Sensitivity
            'specificity': tnr_score, # True Negative Rate
            'npv': npv_score,        # Negative Predictive Value
            'fpr': fpr_score,        # False Positive Rate
            'f1': f1_score,          # F1 Score (Takahashi method)
            'precision_takahashi': precision_score,  # Takahashi precision
            'recall_takahashi': recall_score,        # Takahashi recall
            'auc': roc_auc_score     # ROC AUC Score
        }

        # Regression metrics mapping
        self.regression_metrics = {
            'mae': mae,           # Mean Absolute Error
            'mse': mse,           # Mean Squared Error
            'rmse': rmse,         # Root Mean Squared Error
            'r2': r2_score,       # Coefficient of Determination
            'mape': mape,         # Mean Absolute Percentage Error
            'iou': iou,           # Intersection over Union
            'med_abs_err': med_abs_err,                        # Median Absolute Error
            'mean_bia_dev': mean_bia_dev,                      # Mean Bias Deviation
            'huber_loss': huber_loss,                          # Huber Loss (pass delta=...)
            'exp_var_score': exp_var_score,                    # Explained Variance Score
            'sym_mean_abs_per_error': sym_mean_abs_per_error,  # Symmetric MAPE
            'rmse_log': rmse_log,                              # Root Mean Squared Log Error
            'adjusted_r2_score': adjusted_r2_score,            # Adjusted R² (pass num_features=...)
        }

        # Detection metrics mapping
        self.detection_metrics = {
            'map': map,               # mAP@0.5:0.95 with CI
            'map50': map50,           # mAP@0.5 with CI
            'precision': precision,   # Precision with CI
            'recall': recall          # Recall with CI
        }

        # Available methods for each task type
        self.classification_methods = proportion_conf_methods + ['bootstrap_bca', 'bootstrap_percentile', 'bootstrap_basic']
        self.regression_methods = regression_conf_methods
        # Detection uses bootstrap methods
        self.detection_methods = ['bootstrap_bca', 'bootstrap_percentile', 'bootstrap_basic']

        # Expose individual metric functions as instance methods
        # Classification metrics
        self.accuracy_score = accuracy_score
        self.ppv_score = ppv_score
        self.tpr_score = tpr_score
        self.tnr_score = tnr_score
        self.fpr_score = fpr_score
        self.npv_score = npv_score
        self.f1_score = f1_score
        self.precision_score = precision_score
        self.recall_score = recall_score
        self.roc_auc_score = roc_auc_score

        # Regression metrics
        self.mae = mae
        self.mse = mse
        self.rmse = rmse
        self.r2_score = r2_score
        self.mape = mape
        self.iou = iou

        # Detection metrics
        self.map = map
        self.map50 = map50
        self.precision = precision
        self.recall = recall

    def get_available_metrics(self, task: Union[str, TaskType]) -> List[str]:
        """
        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
        """
        task_str = task.value if isinstance(task, TaskType) else task.lower()

        if task_str == 'classification':
            return list(self.classification_metrics.keys())
        elif task_str == 'regression':
            return list(self.regression_metrics.keys())
        elif task_str == 'detection':
            return list(self.detection_metrics.keys())
        else:
            raise ValueError(f"Unknown task type: {task}. Use 'classification', 'regression', or 'detection'")

    def get_available_methods(self, task: Union[str, TaskType]) -> List[str]:
        """
        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
        """
        task_str = task.value if isinstance(task, TaskType) else task.lower()

        if task_str == 'classification':
            return self.classification_methods
        elif task_str == 'regression':
            return self.regression_methods
        elif task_str == 'detection':
            return self.detection_methods
        else:
            raise ValueError(f"Unknown task type: {task}. Use 'classification', 'regression', or 'detection'")

    def evaluate(self,
                 y_true: Optional[List[Union[int, float]]] = None,
                 y_pred: Optional[List[Union[int, float]]] = None,
                 task: Union[str, TaskType] = None,
                 metric: str = None,
                 method: str = 'bootstrap_bca',
                 confidence_level: float = 0.95,
                 compute_ci: bool = True,
                 plot: bool = False,
                 model: Optional[Any] = None,
                 data: Optional[str] = None,
                 **kwargs) -> Union[float, Tuple[float, Tuple[float, float]], Dict[str, Tuple[float, Tuple[float, float]]]]:
        """
        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}]")
        """

        # Validate and normalize task type
        task_str = task.value if isinstance(task, TaskType) else task.lower()
        if task_str not in ['classification', 'regression', 'detection']:
            raise ValueError(f"Unknown task type: {task}. Use 'classification', 'regression', or 'detection'")

        # Handle detection tasks separately (different interface)
        if task_str == 'detection':
            # Detection tasks require y_true (dataset path) and y_pred (Results objects)
            if y_true is None or y_pred is None:
                raise ValueError(
                    "Detection tasks require:\n"
                    "  - 'y_true': Path to validation dataset directory (e.g., 'val-dataset')\n"
                    "  - 'y_pred': List of ultralytics Results objects from model.predict()"
                )

            if metric not in self.detection_metrics:
                available = ', '.join(self.detection_metrics.keys())
                raise ValueError(f"Unknown detection metric: {metric}. Available: {available}")

            metric_func = self.detection_metrics[metric]

            # Call the detection metric function
            try:
                result = metric_func(
                    y_true=y_true,
                    y_pred=y_pred,
                    confidence_level=confidence_level,
                    method=method,
                    compute_ci=compute_ci,
                    plot=plot,
                    **kwargs
                )
                return result

            except Exception as e:
                raise RuntimeError(f"Error computing {metric}: {str(e)}")

        # Handle classification and regression tasks
        if y_true is None or y_pred is None:
            raise ValueError("Classification and regression tasks require 'y_true' and 'y_pred' parameters")

        # Get the appropriate metric function and validate
        if task_str == 'classification':
            if metric not in self.classification_metrics:
                available = ', '.join(self.classification_metrics.keys())
                raise ValueError(f"Unknown classification metric: {metric}. Available: {available}")
            metric_func = self.classification_metrics[metric]

            # Validate method for classification
            if method not in self.classification_methods:
                available = ', '.join(self.classification_methods)
                raise ValueError(f"Unknown classification method: {method}. Available: {available}")

        else:  # regression
            if metric not in self.regression_metrics:
                available = ', '.join(self.regression_metrics.keys())
                raise ValueError(f"Unknown regression metric: {metric}. Available: {available}")
            metric_func = self.regression_metrics[metric]

            if metric == 'adjusted_r2_score' and 'num_features' not in kwargs:
                raise ValueError("adjusted_r2_score needs num_features=<number of model features>")

            # Validate method for regression
            if method not in self.regression_methods:
                available = ', '.join(self.regression_methods)
                raise ValueError(f"Unknown regression method: {method}. Available: {available}")

        # Set default kwargs for different methods
        if method.startswith('bootstrap') and 'n_resamples' not in kwargs:
            kwargs['n_resamples'] = 9999

        # Call the metric function
        try:
            result = metric_func(
                y_true=y_true,
                y_pred=y_pred,
                confidence_level=confidence_level,
                method=method,
                compute_ci=compute_ci,
                plot=plot,
                **kwargs
            )
            return result

        except Exception as e:
            raise RuntimeError(f"Error computing {metric} with method {method}: {str(e)}")

    def evaluate_multiple(self,
                         y_true: List[Union[int, float]], 
                         y_pred: List[Union[int, float]], 
                         task: Union[str, TaskType],
                         metrics: List[str],
                         method: str = 'bootstrap_bca',
                         confidence_level: float = 0.95,
                         compute_ci: bool = True,
                         plot: bool = False,
                         **kwargs) -> Dict[str, Union[float, Tuple[float, Tuple[float, float]]]]:
        """
        Evaluate multiple metrics at once.

        Parameters:
        -----------
        y_true, y_pred, task, method, confidence_level, compute_ci, plot, **kwargs
            Same as evaluate() method
        metrics : List[str]
            List of metric names to evaluate

        Returns:
        --------
        Dict[str, Union[float, Tuple[float, Tuple[float, float]]]]
            Dictionary with metric names as keys and results as values

        Example:
        --------
        >>> evaluator = MetricEvaluator()
        >>> results = evaluator.evaluate_multiple(
        ...     y_true=[1, 2, 3, 4, 5],
        ...     y_pred=[1.1, 2.1, 2.9, 4.1, 4.9],
        ...     task='regression',
        ...     metrics=['mae', 'rmse', 'r2'],
        ...     method='jackknife'
        ... )
        >>> for metric, (value, ci) in results.items():
        ...     print(f"{metric}: {value:.3f} [{ci[0]:.3f}, {ci[1]:.3f}]")
        """
        results = {}
        for metric in metrics:
            results[metric] = self.evaluate(
                y_true=y_true,
                y_pred=y_pred,
                task=task,
                metric=metric,
                method=method,
                confidence_level=confidence_level,
                compute_ci=compute_ci,
                plot=plot,
                **kwargs
            )
        return results

    def info(self) -> Dict[str, Any]:
        """
        Get information about available tasks, metrics, and methods.

        Returns:
        --------
        Dict[str, Any]: Dictionary containing all available options
        """
        return {
            'tasks': ['classification', 'regression', 'detection'],
            'classification': {
                'metrics': list(self.classification_metrics.keys()),
                'methods': self.classification_methods
            },
            'regression': {
                'metrics': list(self.regression_metrics.keys()),
                'methods': self.regression_methods
            },
            'detection': {
                'metrics': list(self.detection_metrics.keys()),
                'methods': self.detection_methods
            }
        }

    def print_info(self):
        """Print formatted information about available options."""
        print("MetricEvaluator - Available Options")
        print("=" * 40)

        print("\n📊 CLASSIFICATION METRICS:")
        for metric in self.classification_metrics.keys():
            print(f"   - {metric}")

        print(f"\n🔧 Classification Methods: {len(self.classification_methods)}")
        for method in self.classification_methods:
            print(f"   - {method}")

        print("\n📈 REGRESSION METRICS:")
        for metric in self.regression_metrics.keys():
            print(f"   - {metric}")

        print(f"\n🔧 Regression Methods: {len(self.regression_methods)}")
        for method in self.regression_methods:
            print(f"   - {method}")

        print("\n🎯 DETECTION METRICS:")
        for metric in self.detection_metrics.keys():
            print(f"   - {metric}")

        print(f"\n🔧 Detection Methods: {len(self.detection_methods)}")
        for method in self.detection_methods:
            print(f"   - {method}")

        print(f"\nDefault method: bootstrap_bca")
        print(f"Default confidence level: 0.95")

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
def evaluate(self,
             y_true: Optional[List[Union[int, float]]] = None,
             y_pred: Optional[List[Union[int, float]]] = None,
             task: Union[str, TaskType] = None,
             metric: str = None,
             method: str = 'bootstrap_bca',
             confidence_level: float = 0.95,
             compute_ci: bool = True,
             plot: bool = False,
             model: Optional[Any] = None,
             data: Optional[str] = None,
             **kwargs) -> Union[float, Tuple[float, Tuple[float, float]], Dict[str, Tuple[float, Tuple[float, float]]]]:
    """
    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}]")
    """

    # Validate and normalize task type
    task_str = task.value if isinstance(task, TaskType) else task.lower()
    if task_str not in ['classification', 'regression', 'detection']:
        raise ValueError(f"Unknown task type: {task}. Use 'classification', 'regression', or 'detection'")

    # Handle detection tasks separately (different interface)
    if task_str == 'detection':
        # Detection tasks require y_true (dataset path) and y_pred (Results objects)
        if y_true is None or y_pred is None:
            raise ValueError(
                "Detection tasks require:\n"
                "  - 'y_true': Path to validation dataset directory (e.g., 'val-dataset')\n"
                "  - 'y_pred': List of ultralytics Results objects from model.predict()"
            )

        if metric not in self.detection_metrics:
            available = ', '.join(self.detection_metrics.keys())
            raise ValueError(f"Unknown detection metric: {metric}. Available: {available}")

        metric_func = self.detection_metrics[metric]

        # Call the detection metric function
        try:
            result = metric_func(
                y_true=y_true,
                y_pred=y_pred,
                confidence_level=confidence_level,
                method=method,
                compute_ci=compute_ci,
                plot=plot,
                **kwargs
            )
            return result

        except Exception as e:
            raise RuntimeError(f"Error computing {metric}: {str(e)}")

    # Handle classification and regression tasks
    if y_true is None or y_pred is None:
        raise ValueError("Classification and regression tasks require 'y_true' and 'y_pred' parameters")

    # Get the appropriate metric function and validate
    if task_str == 'classification':
        if metric not in self.classification_metrics:
            available = ', '.join(self.classification_metrics.keys())
            raise ValueError(f"Unknown classification metric: {metric}. Available: {available}")
        metric_func = self.classification_metrics[metric]

        # Validate method for classification
        if method not in self.classification_methods:
            available = ', '.join(self.classification_methods)
            raise ValueError(f"Unknown classification method: {method}. Available: {available}")

    else:  # regression
        if metric not in self.regression_metrics:
            available = ', '.join(self.regression_metrics.keys())
            raise ValueError(f"Unknown regression metric: {metric}. Available: {available}")
        metric_func = self.regression_metrics[metric]

        if metric == 'adjusted_r2_score' and 'num_features' not in kwargs:
            raise ValueError("adjusted_r2_score needs num_features=<number of model features>")

        # Validate method for regression
        if method not in self.regression_methods:
            available = ', '.join(self.regression_methods)
            raise ValueError(f"Unknown regression method: {method}. Available: {available}")

    # Set default kwargs for different methods
    if method.startswith('bootstrap') and 'n_resamples' not in kwargs:
        kwargs['n_resamples'] = 9999

    # Call the metric function
    try:
        result = metric_func(
            y_true=y_true,
            y_pred=y_pred,
            confidence_level=confidence_level,
            method=method,
            compute_ci=compute_ci,
            plot=plot,
            **kwargs
        )
        return result

    except Exception as e:
        raise RuntimeError(f"Error computing {metric} with method {method}: {str(e)}")

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
def get_available_metrics(self, task: Union[str, TaskType]) -> List[str]:
    """
    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
    """
    task_str = task.value if isinstance(task, TaskType) else task.lower()

    if task_str == 'classification':
        return list(self.classification_metrics.keys())
    elif task_str == 'regression':
        return list(self.regression_metrics.keys())
    elif task_str == 'detection':
        return list(self.detection_metrics.keys())
    else:
        raise ValueError(f"Unknown task type: {task}. Use 'classification', 'regression', or 'detection'")

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
def get_available_methods(self, task: Union[str, TaskType]) -> List[str]:
    """
    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
    """
    task_str = task.value if isinstance(task, TaskType) else task.lower()

    if task_str == 'classification':
        return self.classification_methods
    elif task_str == 'regression':
        return self.regression_methods
    elif task_str == 'detection':
        return self.detection_methods
    else:
        raise ValueError(f"Unknown task type: {task}. Use 'classification', 'regression', or 'detection'")

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:

evaluate_metric(y_true, y_pred, task='regression', metric='adjusted_r2_score',
                num_features=3)

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"

See Also