TypeScript: precision, recall, and F1 from a confusion matrix

A binary classifier makes four kinds of outcome. True positives (TP) are positives correctly found, false positives (FP) are negatives wrongly flagged, false negatives (FN) are positives that were missed, and true negatives (TN) are negatives correctly ignored. Together they form the confusion matrix.

TypeScript
interface Confusion {
  tp: number;
  fp: number;
  fn: number;
  tn: number;
}

function confusion(actual: number[], predicted: number[]): Confusion {
  const c: Confusion = { tp: 0, fp: 0, fn: 0, tn: 0 };
  for (let i = 0; i < actual.length; i++) {
    if (actual[i] === 1 && predicted[i] === 1) c.tp++;
    else if (actual[i] === 0 && predicted[i] === 1) c.fp++;
    else if (actual[i] === 1 && predicted[i] === 0) c.fn++;
    else c.tn++;
  }
  return c;
}

const actual = [1, 1, 1, 1, 0, 0, 0, 0, 0, 0];
const predicted = [1, 1, 1, 0, 1, 1, 0, 0, 0, 0];
const c = confusion(actual, predicted);

const precision = c.tp / (c.tp + c.fp);
const recall = c.tp / (c.tp + c.fn);
const f1 = (2 * precision * recall) / (precision + recall);
const accuracy = (c.tp + c.tn) / actual.length;

console.log("tp=" + c.tp + " fp=" + c.fp + " fn=" + c.fn + " tn=" + c.tn);
console.log("precision " + precision.toFixed(3) + ", recall " + recall.toFixed(3));
console.log("F1 " + f1.toFixed(3) + ", accuracy " + accuracy.toFixed(3));
Read the full lesson