{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "6a937ab3",
   "metadata": {},
   "source": [
    "# Development of a Modular Python Library from Scratch for Automated ROI Segmentation in Thermal Images"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "547b1c8a",
   "metadata": {},
   "source": [
    "# Module 3: Artificial Neural Network (ANN)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c29cdf01",
   "metadata": {},
   "source": [
    "Author: Sofia Samaniego Lopez\n",
    "\n",
    "Institution: Universidad Autonoma de Baja California (UABC)\n",
    "\n",
    "Advisor: Dr. Gerardo Marx Chavez Campos"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fe3535d2",
   "metadata": {},
   "source": [
    "This notebook presents **Module 3** of the library's development: the implementation of an **Artificial Neural Network (ANN) from scratch**.\n",
    "\n",
    "With the objective of maintaining algorithmic transparency and bypassing commercial \"black-box\" frameworks, the entire network architecture (weight matrix initialization, feedforward propagation, and backpropagation via gradient descent) has been programmed using strictly linear algebra through **NumPy**. \n",
    "\n",
    "As a proof of concept and baseline evaluation, the model is trained and validated using the **MNIST** dataset. This demonstrates the pure mathematical algorithm's capability to classify complex patterns prior to scaling the framework for thermal image processing."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6ff6f020",
   "metadata": {},
   "source": [
    "## 1. Environment Setup & Initialization\n",
    "Importing core libraries for matrix operations and data visualization. A random seed is set to ensure reproducible weight initialization across experimental runs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "371dacfd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: numpy in c:\\Users\\sofia\\ANN-From-Scratch\\.venv\\Lib\\site-packages (2.5.0)\n",
      "Requirement already satisfied: matplotlib in c:\\Users\\sofia\\ANN-From-Scratch\\.venv\\Lib\\site-packages (3.11.0)\n",
      "Requirement already satisfied: contourpy>=1.0.1 in c:\\Users\\sofia\\ANN-From-Scratch\\.venv\\Lib\\site-packages (from matplotlib) (1.3.3)\n",
      "Requirement already satisfied: cycler>=0.10 in c:\\Users\\sofia\\ANN-From-Scratch\\.venv\\Lib\\site-packages (from matplotlib) (0.12.1)\n",
      "Requirement already satisfied: fonttools>=4.22.0 in c:\\Users\\sofia\\ANN-From-Scratch\\.venv\\Lib\\site-packages (from matplotlib) (4.63.0)\n",
      "Requirement already satisfied: kiwisolver>=1.3.1 in c:\\Users\\sofia\\ANN-From-Scratch\\.venv\\Lib\\site-packages (from matplotlib) (1.5.0)\n",
      "Requirement already satisfied: numpy>=1.25 in c:\\Users\\sofia\\ANN-From-Scratch\\.venv\\Lib\\site-packages (from matplotlib) (2.5.0)\n",
      "Requirement already satisfied: packaging>=20.0 in c:\\Users\\sofia\\ANN-From-Scratch\\.venv\\Lib\\site-packages (from matplotlib) (26.2)\n",
      "Requirement already satisfied: pillow>=9 in c:\\Users\\sofia\\ANN-From-Scratch\\.venv\\Lib\\site-packages (from matplotlib) (12.2.0)\n",
      "Requirement already satisfied: pyparsing>=3 in c:\\Users\\sofia\\ANN-From-Scratch\\.venv\\Lib\\site-packages (from matplotlib) (3.3.2)\n",
      "Requirement already satisfied: python-dateutil>=2.7 in c:\\Users\\sofia\\ANN-From-Scratch\\.venv\\Lib\\site-packages (from matplotlib) (2.9.0.post0)\n",
      "Requirement already satisfied: six>=1.5 in c:\\Users\\sofia\\ANN-From-Scratch\\.venv\\Lib\\site-packages (from python-dateutil>=2.7->matplotlib) (1.17.0)\n"
     ]
    }
   ],
   "source": [
    "!pip3 install numpy\n",
    "!pip3 install matplotlib\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "np.random.seed(12)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "64958384",
   "metadata": {},
   "source": [
    "## 2. Artificial Neural Network (ANN) Architecture"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8594921c",
   "metadata": {},
   "source": [
    "Neural Network's Basic Structure "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "d18ac1be",
   "metadata": {},
   "outputs": [],
   "source": [
    "class ann:\n",
    "    #init\n",
    "    def __init__():\n",
    "        pass\n",
    "\n",
    "    #feedfoward\n",
    "    def feedforward():\n",
    "        pass\n",
    "\n",
    "    #backpropagation\n",
    "    def backpropagation():\n",
    "        pass\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "83a68db8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'type'>\n"
     ]
    }
   ],
   "source": [
    "MyANN = ann\n",
    "print(type(MyANN))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d9680a2a",
   "metadata": {},
   "source": [
    "### 2.1 Initialization\n",
    "Defining the network structure (input, hidden, and output layers). Synaptic weight matrices ($W_{ih}$ and $W_{ho}$) are initialized using a normal distribution to break mathematical symmetry."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "7285c021",
   "metadata": {},
   "outputs": [],
   "source": [
    "class ann:\n",
    "    #init\n",
    "    def __init__(self, inputNodes: int, hiddenNodes: int, outputNodes: int):\n",
    "        # Nodes\n",
    "        inN = inputNodes # Private var or parameters\n",
    "        hN = hiddenNodes\n",
    "        oN = outputNodes\n",
    "        # Weights\n",
    "        np.random.seed(12) #seed for reproducibility\n",
    "        self.wih = np.random.randn(hN, inN) #weights for input to hidden layer\n",
    "        self.who = np.random.randn(oN, hN) #weights for hidden to output layer\n",
    "        pass\n",
    "\n",
    "    #feedfoward\n",
    "    def feedforward():\n",
    "        pass\n",
    "\n",
    "    #backpropagation\n",
    "    def backpropagation():\n",
    "        pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "b5b34c6e",
   "metadata": {},
   "outputs": [],
   "source": [
    "MyANN = ann(3, 3, 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "5c00cf15",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.47298583, -0.68142588,  0.2424395 ],\n",
       "       [-1.70073563,  0.75314283, -1.53472134],\n",
       "       [ 0.00512708, -0.12022767, -0.80698188]])"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "MyANN.wih"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "4b0f2e37",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 2.87181939, -0.59782292,  0.47245699],\n",
       "       [ 1.09595612, -1.2151688 ,  1.34235637],\n",
       "       [-0.12214979,  1.01251548, -0.91386915]])"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "MyANN.who"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f3e2ed15",
   "metadata": {},
   "source": [
    "### 2.2 Feedforward (Inference)\n",
    "So the next step is to create the network of nodes and links. The most important part of the network is the link weights. They’re used to calculate the signal being fed forward, the error as it’s propagated backwards, and it is the link weights themselves that are refined in an attempt to to improve the network.\n",
    "\n",
    "For the basic NN, the weight matrix consist of:\n",
    "\n",
    "- A matrix that links the input and hidden layers, $Wih$, of size hidden nodes by input nodes ($hn×in$)\n",
    "- and another matrix for the links between the hidden and output layers, $Who$, of size $on×hn$ (output nodes by hidden nodes)\n",
    "\n",
    "$$X_h=W_{ih}I$$\n",
    "$$O_h=\\sigma(X_h)$$\n",
    "\n",
    "\n",
    "Then, \n",
    "\n",
    "$$X_o=W_{ho}O_{h}$$\n",
    "$$O_o=\\sigma(X_o)$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "31b8c4dd",
   "metadata": {},
   "outputs": [],
   "source": [
    "class ann:\n",
    "    #init\n",
    "    def __init__(self, inputNodes: int, hiddenNodes: int, outputNodes: int):\n",
    "        # Nodes\n",
    "        inN = inputNodes # Private var or parameters\n",
    "        hN = hiddenNodes\n",
    "        oN = outputNodes\n",
    "        # Weights\n",
    "        np.random.seed(12) #seed for reproducibility\n",
    "        self.wih = np.random.randn(hN, inN) #weights for input to hidden layer\n",
    "        self.who = np.random.randn(oN, hN) #weights for hidden to output layer\n",
    "        pass\n",
    "\n",
    "    #feedfoward\n",
    "    def feedforward(self, Inputs):\n",
    "        # Forward pass to hidden layer\n",
    "        inputs = np.array(Inputs, ndmin=2).T\n",
    "        Xh = np.dot(self.wih, inputs)\n",
    "        af = lambda x: 1 / (1 + np.exp(-x))\n",
    "        Oh = af(Xh)\n",
    "        # Forward pass to output layer\n",
    "        Xo = self.who @ Oh\n",
    "        Oo = af(Xo)\n",
    "        return Oo\n",
    "\n",
    "    #backpropagation\n",
    "    def backpropagation():\n",
    "        pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "6d6b0b09",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0.80230104],\n",
       "       [0.65960645],\n",
       "       [0.48247944]])"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "MyANN = ann(3, 3, 3)\n",
    "MyANN.feedforward([0.1, 0.2, 0.3])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4dd6b848",
   "metadata": {},
   "source": [
    "### 2.3 Backpropagation (Training)\n",
    "The core learning algorithm. It calculates the prediction error, propagates it backward, and dynamically updates the weight matrices using gradient descent and the chain rule."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2fb1cf2c",
   "metadata": {},
   "source": [
    "\n",
    "The Gradient of Error\n",
    "$$ \\frac{\\partial E}{\\partial w_{ho}}= -e_o\\cdot \\sigma \\left(w_{ho} O_h\\right) \\left(1-\\sigma\\left (w_{ho} O_h\\right) \\right) O_h $$\n",
    "\n",
    "Thus,\n",
    "\n",
    "$$ \\frac{\\partial E}{\\partial w_{ho}}= -e_o\\cdot O_o \\left(1-O_o \\right) O_h $$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "ef1098b0",
   "metadata": {},
   "outputs": [],
   "source": [
    "class ann:\n",
    "    #init\n",
    "    def __init__(self, inputNodes: int, hiddenNodes: int, outputNodes: int):\n",
    "        # Nodes\n",
    "        inN = inputNodes # Private var or parameters\n",
    "        hN = hiddenNodes\n",
    "        oN = outputNodes\n",
    "        # Weights\n",
    "        np.random.seed(12) #seed for reproducibility\n",
    "        self.wih = np.random.randn(hN, inN) #weights for input to hidden layer\n",
    "        self.who = np.random.randn(oN, hN) #weights for hidden to output layer\n",
    "        pass\n",
    "\n",
    "    #feedfoward\n",
    "    def feedforward(self, Inputs):\n",
    "        # Oh\n",
    "        inputs = np.array(Inputs, ndmin=2).T\n",
    "        Xh = np.dot(self.wih, inputs)\n",
    "        af = lambda x: 1 / (1 + np.exp(-x))\n",
    "        Oh = af(Xh)\n",
    "        # Oo\n",
    "        Xo = self.who @ Oh\n",
    "        Oo = af(Xo)\n",
    "        return Oo\n",
    "\n",
    "    #backpropagation\n",
    "    def backpropagation(self, Inputs, Targets, Learning):\n",
    "        lr = Learning\n",
    "        inputs = np.array(Inputs, ndmin=2).T\n",
    "        targets = np.array(Targets, ndmin=2).T\n",
    "        \n",
    "        # 1. Internal feedforward\n",
    "        Xh = self.wih @ inputs\n",
    "        af = lambda x: 1 / (1 + np.exp(-x))\n",
    "        Oh = af(Xh)\n",
    "        \n",
    "        Xo = self.who @ Oh\n",
    "        Oo = af(Xo)\n",
    "        \n",
    "        # 2. Error calculation\n",
    "        Eo = targets - Oo\n",
    "        Eh = self.who.T @ Eo\n",
    "\n",
    "        # 3. Weight matrices update\n",
    "        self.who = self.who + (lr * Eo * Oo * (1-Oo) ) @ Oh.T\n",
    "        self.wih = self.wih + (lr * Eh * Oh * (1-Oh) ) @ inputs.T\n",
    "        pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "deacbee4",
   "metadata": {},
   "outputs": [],
   "source": [
    "MyANN = ann(3, 5, 3)\n",
    "MyANN.backpropagation([0.1, 0.2, 0.3], [0.01, 0.01, 0.99], 0.3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "40d8674c",
   "metadata": {},
   "source": [
    "## 3. MNIST Dataset Exploration\n",
    "Loading the training dataset. To verify the geometric structure, a raw 784-pixel flat array is extracted and reshaped into a 28x28 2D matrix for visual confirmation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "bb581e90",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<function TextIOWrapper.close()>"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Load training data\n",
    "file = open(\"mnist_train.csv\")\n",
    "list = file.readlines()\n",
    "file.close"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "ddb0a6fb",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 9144 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Visualize sample at index 120\n",
    "values = list[120].split(\",\")\n",
    "image = np.asarray(values[1:], dtype=int)\n",
    "plt.imshow(image.reshape(28,28), cmap='Grays')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "id": "23314858",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "49999"
      ]
     },
     "execution_count": 54,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "values [0]\n",
    "len(list)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b499d390",
   "metadata": {},
   "source": [
    "## 4. Model Training\n",
    "Setting up hyperparameters. During training, pixel intensities are normalized to a $[0.01, 1.0]$ range to prevent zero-gradient issues. Target labels are formatted using an adapted One-Hot Encoding."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "id": "c4dd5448",
   "metadata": {},
   "outputs": [],
   "source": [
    "# hyperparameters\n",
    "inputNodes = 784\n",
    "hiddenNodes = 100\n",
    "outNodes = 10\n",
    "learningRate = 0.1\n",
    "MyANN = ann(inputNodes, hiddenNodes, outNodes)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "id": "ae0ac96d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Iterative training loop\n",
    "epoch = 1\n",
    "for e in range (epoch):\n",
    "    for record in list: \n",
    "        values = record.split(\",\")\n",
    "       \n",
    "        # Input data normalization\n",
    "        data = np.asarray(values[1:], dtype=int)/255*0.99+0.01\n",
    "        index = np.asarray(values[0],dtype=int)\n",
    "       \n",
    "        # Target Vector construction\n",
    "        target = np.zeros(outNodes) + 0.01\n",
    "        target[index] = 0.99\n",
    "        \n",
    "        MyANN.backpropagation(data, target, learningRate)\n",
    "        pass\n",
    "    pass\n",
    "        "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c75cb916",
   "metadata": {},
   "source": [
    "## 5. Validation & Inference\n",
    "Evaluating model performance using unseen test data. A new sample is normalized and processed to extract the final prediction vector, which is then visually compared to the ground truth image."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "id": "a446646f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<function TextIOWrapper.close()>"
      ]
     },
     "execution_count": 57,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Load testing data\n",
    "file2 = open(\"mnist_test.csv\")\n",
    "list2 = file2.readlines()\n",
    "file2.close"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "id": "682673f4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1.12958417e-03],\n",
       "       [7.04806122e-03],\n",
       "       [1.33450332e-03],\n",
       "       [9.98132913e-01],\n",
       "       [1.21412650e-04],\n",
       "       [6.66539345e-03],\n",
       "       [2.96287176e-05],\n",
       "       [1.83308214e-03],\n",
       "       [8.11709452e-04],\n",
       "       [1.75208890e-04]])"
      ]
     },
     "execution_count": 58,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Inference on sample 500\n",
    "values = list2[500].split(\",\")\n",
    "data = np.asarray(values[1:], dtype=int)/255*0.99+0.01\n",
    "\n",
    "# Display probability vector for the 10 classes\n",
    "MyANN.feedforward(data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "id": "8d5fb4bd",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 9300 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Visual verification\n",
    "image = np.asarray(values[1:], dtype=int)\n",
    "plt.imshow(image.reshape(28,28), cmap='Grays')\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "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.14.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
