precision function

double precision(
  1. List<int> yTrue,
  2. List<int> yPred, {
  3. int positiveLabel = 1,
})

Precision metric for binary classification (positive = 1).

Implementation

double precision(List<int> yTrue, List<int> yPred, {int positiveLabel = 1}) {
  if (yTrue.length != yPred.length) {
    throw ArgumentError('Lengths of true and predicted labels must match.');
  }

  int tp = 0, fp = 0;

  for (int i = 0; i < yTrue.length; i++) {
    if (yPred[i] == positiveLabel) {
      if (yTrue[i] == positiveLabel) tp++;
      else fp++;
    }
  }

  final denominator = tp + fp;
  return denominator == 0 ? 0.0 : tp / denominator;
}