binaryConfusionMatrix function

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

Generates a confusion matrix for binary classification. Returns TP, FP, FN, TN in order.

Implementation

List<int> binaryConfusionMatrix(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, fn = 0, tn = 0;

  for (int i = 0; i < yTrue.length; i++) {
    final trueLabel = yTrue[i];
    final predLabel = yPred[i];

    if (trueLabel == positiveLabel) {
      if (predLabel == positiveLabel) tp++;
      else fn++;
    } else {
      if (predLabel == positiveLabel) fp++;
      else tn++;
    }
  }

  return [tp, fp, fn, tn];
}