[d869a2]: / Notebooks / 17_confusion_matrix_test.ipynb

Download this file

145 lines (144 with data), 2.8 kB

{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "y     = torch.Tensor([[1,0,0,1,0], [0,0,0,1,1]]).numpy()\n",
    "y_hat = torch.Tensor([[1,1,0,1,0], [1,1,0,0,1]]).numpy()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "np.float64(0.6)"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y_hat_binary = (y_hat > 0.5).astype(int)\n",
    "accuracy = np.mean(y_hat_binary == y)\n",
    "accuracy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import confusion_matrix"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([1., 0., 0., 1., 0., 0., 0., 0., 0., 0., 1., 1., 0., 0.])\n",
      "tensor([1., 1., 0., 1., 0., 0., 1., 1., 1., 0., 0., 1., 0., 0.])\n"
     ]
    }
   ],
   "source": [
    "y_true = torch.Tensor([[1,0,0,1,0,0,0], [0,0,0,1,1,0,0]]).flatten()\n",
    "y_pred = torch.Tensor([[1,1,0,1,0,0,1], [1,1,0,0,1,0,0]]).flatten()\n",
    "\n",
    "print(y_true)\n",
    "print(y_pred)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6 4 1 3\n"
     ]
    }
   ],
   "source": [
    "tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()\n",
    "print(tn, fp, fn, tp)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[6 4]\n",
      " [1 3]]\n",
      "tn fp\n",
      "fn tp\n"
     ]
    }
   ],
   "source": [
    "print(confusion_matrix(y_true, y_pred))\n",
    "print('tn fp\\nfn tp')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "master",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}