{ "nbformat": 4, "nbformat_minor": 5, "metadata": { "colab": { "name": "The Infosiast \u2014 Machine Learning Evaluation: Accuracy Paradox, Confusion Matrix & Precision/Recall", "provenance": [], "gpuType": "T4" }, "accelerator": "GPU", "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.11.0" } }, "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# The Infosiast \u2014 Machine Learning Evaluation & Confusion Matrix Lab\n", "**Prepared by [Kshitij Gupta](https://www.linkedin.com/in/kshitij-gupta-855535134/) for [The Infosiast](https://theinfosiast.com/)**\n", "\n", "Accompanies: [What Is Machine Learning? How It Works, Everyday Examples, and Its Limits](https://theinfosiast.com/what-is-machine-learning/)\n", "\n", "Run this notebook to reproduce our imbalanced classification experiment and see why a naive classifier can score **95% accuracy** while catching **0% of actual fraud/urgent events**.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Step 1: The 95% Accuracy Paradox vs Precision & Recall\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n", "import numpy as np\n", "\n", "y_true = np.array([0]*950 + [1]*50)\n", "y_naive = np.zeros_like(y_true)\n", "y_tuned = np.array([0]*938 + [1]*12 + [0]*7 + [1]*43)\n", "\n", "for name, preds in [('Naive Majority Classifier', y_naive), ('Tuned Feature Classifier', y_tuned)]:\n", " tn, fp, fn, tp = confusion_matrix(y_true, preds).ravel()\n", " acc = accuracy_score(y_true, preds) * 100\n", " prec = precision_score(y_true, preds, zero_division=0) * 100\n", " rec = recall_score(y_true, preds, zero_division=0) * 100\n", " f1 = f1_score(y_true, preds, zero_division=0) * 100\n", " print(f'=== {name} ===')\n", " print(f' Confusion Matrix : TP={tp}, FP={fp}, TN={tn}, FN={fn}')\n", " print(f' Accuracy : {acc:.2f}%')\n", " print(f' Precision : {prec:.2f}%')\n", " print(f' Recall : {rec:.2f}%')\n", " print(f' F1 Score : {f1:.2f}%\\n')\n" ] } ] }