Neural-Networks-From-Scratch/lecture18_22/notes_18.ipynb

536 lines
23 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Previous Class Definitions"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"# imports\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import nnfs\n",
"from nnfs.datasets import spiral_data, vertical_data\n",
"nnfs.init()"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [],
"source": [
"class Layer_Dense:\n",
" def __init__(self, n_inputs, n_neurons):\n",
" # Initialize the weights and biases\n",
" self.weights = 0.01 * np.random.randn(n_inputs, n_neurons) # Normal distribution of weights\n",
" self.biases = np.zeros((1, n_neurons))\n",
"\n",
" def forward(self, inputs):\n",
" # Calculate the output values from inputs, weights, and biases\n",
" self.output = np.dot(inputs, self.weights) + self.biases # Weights are already transposed\n",
"\n",
"class Activation_ReLU:\n",
" def forward(self, inputs):\n",
" self.output = np.maximum(0, inputs)\n",
" \n",
"class Activation_Softmax:\n",
" def forward(self, inputs):\n",
" # Get the unnormalized probabilities\n",
" # Subtract max from the row to prevent larger numbers\n",
" exp_values = np.exp(inputs - np.max(inputs, axis=1, keepdims=True))\n",
"\n",
" # Normalize the probabilities with element wise division\n",
" probabilities = exp_values / np.sum(exp_values, axis=1,keepdims=True)\n",
" self.output = probabilities\n",
"\n",
"# Base class for Loss functions\n",
"class Loss:\n",
" '''Calculates the data and regularization losses given\n",
" model output and ground truth values'''\n",
" def calculate(self, output, y):\n",
" sample_losses = self.forward(output, y)\n",
" data_loss = np.average(sample_losses)\n",
" return data_loss\n",
"\n",
"class Loss_CategoricalCrossEntropy(Loss):\n",
" def forward(self, y_pred, y_true):\n",
" '''y_pred is the neural network output\n",
" y_true is the ideal output of the neural network'''\n",
" samples = len(y_pred)\n",
" # Bound the predicted values \n",
" y_pred_clipped = np.clip(y_pred, 1e-7, 1-1e-7)\n",
" \n",
" if len(y_true.shape) == 1: # Categorically labeled\n",
" correct_confidences = y_pred_clipped[range(samples), y_true]\n",
" elif len(y_true.shape) == 2: # One hot encoded\n",
" correct_confidences = np.sum(y_pred_clipped*y_true, axis=1)\n",
"\n",
" # Calculate the losses\n",
" negative_log_likelihoods = -np.log(correct_confidences)\n",
" return negative_log_likelihoods"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Previous Notes and Notation\n",
"The previous notation is clunky and long. From here forward, we will use the following notation for a layer with $n$ inputs and $i$ neurons. The neruon layer has is followed by an activation layer and then fed into a final value $y$ with a computed loss $l$. There can be $j$ batches of data.\n",
"\n",
"$\\vec{X_j} = \\begin{bmatrix} x_{1j} & x_{2j} & \\cdots & x_{nj} \\end{bmatrix}$ -> Row vector for the layer inputs for the $j$ batch of data.\n",
"\n",
"$\\overline{\\overline{W}} = \\begin{bmatrix} \\vec{w_{1}} \\\\ \\vec{w_{2}} \\\\ \\vdots \\\\ \\vec{w_{i}} \\end{bmatrix} = \\begin{bmatrix} w_{11} & w_{12} & \\cdots & w_{1n} \\\\ w_{21} & w_{22} & \\cdots & w_{2n} \\\\ \\vdots & \\vdots & \\ddots & \\vdots \\\\ w_{i1} & w_{i2} & \\cdots & w_{in}\\end{bmatrix}$ -> Matrix of weight values. Each row is a neuron's weights and each column is the weights for a given input.\n",
"\n",
"$\\vec{B} = \\begin{bmatrix} b_1 & b_2 & \\cdots & b_i \\end{bmatrix}$ -> Row vector for the neuron biases\n",
"\n",
"$\\vec{Z_j} = \\begin{bmatrix} z_{1j} & z_{2j} & \\cdots & z_{ij} \\end{bmatrix}$ -> Row vector for the neuron outputs for the $j$ batch of data.\n",
"\n",
"$\\vec{A_j} = \\begin{bmatrix} a_{1j} & a_{2j} & \\cdots & a_{ij} \\end{bmatrix}$ -> Row vector for the activation later outputs for the $j$ batch of data.\n",
"\n",
"$y_j$ -> Final layer output for the $j$ batch of data if the layer is the final layer (could be summation, probability, etc).\n",
"\n",
"$l_j$ -> Loss for the $j$ batch of data.\n",
"\n",
"The $j$ is often dropped because we typically only need to think with 1 set of input data.\n",
"\n",
"## Gradient Descent Using New Notation\n",
"We will look at the weight that the $i$ neuron applies for the $n$ input.\n",
"\n",
"$\\frac{\\delta l}{\\delta w_{in}} = \\frac{\\delta l}{\\delta y} \\frac{\\delta y}{\\delta a_i} \\frac{\\delta a_i}{\\delta z_i} \\frac{\\delta z_i}{\\delta w_{in}}$\n",
"\n",
"Similarly, for the bias of the $i$ neuron, there is\n",
"\n",
"$\\frac{\\delta l}{\\delta b_{i}} = \\frac{\\delta l}{\\delta y} \\frac{\\delta y}{\\delta a_i} \\frac{\\delta a_i}{\\delta z_i} \\frac{\\delta z_i}{\\delta b_{i}}$\n",
"\n",
"For the system we are using, where $l = (y-0)^2$ and the activation layer is ReLU, we have\n",
"\n",
"$\\frac{\\delta l}{\\delta y} = 2y$\n",
"\n",
"$\\frac{\\delta y}{\\delta a_i} = 1$\n",
"\n",
"$\\frac{\\delta a_i}{\\delta z_i} = 1$ if $z_i > 0$ else $0$\n",
"\n",
"$\\frac{\\delta z_i}{\\delta w_{in}} = x_n$\n",
"\n",
"$\\frac{\\delta z_i}{\\delta b_{i}} = 1$\n",
"\n",
"## Matrix Representation of Gradient Descent\n",
"We can simplify by seeing that $\\frac{\\delta l}{\\delta y} \\frac{\\delta y}{\\delta a_i} \\frac{\\delta a_i}{\\delta z_i} = \\frac{\\delta l}{\\delta z_i}$ is a common term.\n",
"\n",
"We take $\\frac{\\delta l}{\\delta z_i}$ and turn it into a 1 x $i$ vector that such that \n",
"\n",
"$\\frac{\\delta l}{\\delta \\vec{Z}} = \\begin{bmatrix} \\frac{\\delta l}{\\delta z_1} & \\frac{\\delta l}{\\delta z_2} & \\cdots & \\frac{\\delta l}{\\delta z_i} \\end{bmatrix}$\n",
"\n",
"We than can get that the gradient matrix for all weights is a $i$ x $n$ matrix given by \n",
"\n",
"$\\frac{\\delta l}{\\delta \\overline{\\overline{W}}} = \\begin{bmatrix} \\frac{\\delta l}{\\delta w_{11}} & \\frac{\\delta l}{\\delta w_{12}} & \\cdots & \\frac{\\delta l}{\\delta w_{1n}} \\\\ \\frac{\\delta l}{\\delta w_{21}} & w\\frac{\\delta l}{\\delta w_{22}} & \\cdots & \\frac{\\delta l}{\\delta w_{2n}} \\\\ \\vdots & \\vdots & \\ddots & \\vdots \\\\ \\frac{\\delta l}{\\delta w_{i1}} & \\frac{\\delta l}{\\delta w_{i2}} & \\cdots & \\frac{\\delta l}{\\delta w_{in}} \\end{bmatrix} = \\begin{bmatrix} \\frac{\\delta l}{\\delta z_1} \\\\ \\frac{\\delta l}{\\delta z_2} \\\\ \\vdots \\\\ \\frac{\\delta l}{\\delta z_n} \\end{bmatrix} \\begin{bmatrix} \\frac{\\delta z_1}{\\delta w_{i1}} & \\frac{\\delta z_1}{\\delta w_{i1}} & \\cdots & \\frac{\\delta z_1}{\\delta w_{in}} \\end{bmatrix} = \\begin{bmatrix} \\frac{\\delta l}{\\delta z_1} \\\\ \\frac{\\delta l}{\\delta z_2} \\\\ \\vdots \\\\ \\frac{\\delta l}{\\delta z_n} \\end{bmatrix} \\begin{bmatrix} x_1 & x_2 & \\cdots & x_n \\end{bmatrix}$\n",
"\n",
"Similarly, the gradient vector for the biases is given by\n",
"$\\frac{\\delta l}{\\delta \\vec{B}} = \\frac{\\delta l}{\\delta \\vec{Z}} \\frac{\\delta \\vec{Z}}{\\delta \\vec{B}} = \\vec{1} \\begin{bmatrix} \\frac{\\delta l}{\\delta z_1} & \\frac{\\delta l}{\\delta z_2} & \\cdots & \\frac{\\delta l}{\\delta z_i} \\end{bmatrix}$\n",
"\n",
"## Gradients of the Loss with Respect to Inputs\n",
"When chaining multiple layers together, we will need the partial derivatives of the loss with respect to the next layers input (ie, the output of the current layer). This involves extra summation because the output of 1 layer is fed into every neuron of the next layer, so the total loss must be found.\n",
"\n",
"The gradient of the loss with respect to the $n$ input fed into $i$ neurons is\n",
"\n",
"$\\frac{\\delta l}{\\delta x_n} = \\frac{\\delta l}{\\delta z_1} \\frac{\\delta z_1}{\\delta x_n} + \\frac{\\delta l}{\\delta z_2} \\frac{\\delta z_2}{\\delta x_n} + ... + \\frac{\\delta l}{\\delta z_i} \\frac{\\delta z_i}{\\delta x_n}$\n",
"\n",
"\n",
"Noting that $\\frac{\\delta z_i}{\\delta x_n} = w_{in}$ allows us to have\n",
"\n",
"$\\frac{\\delta l}{\\delta \\vec{X}} = \\begin{bmatrix} \\frac{\\delta l}{\\delta x_1} & \\frac{\\delta l}{\\delta x_2} & \\cdots & \\frac{\\delta l}{\\delta x_n} \\end{bmatrix} = \\begin{bmatrix} \\frac{\\delta l}{\\delta z_1} & \\frac{\\delta l}{\\delta z_2} & \\cdots & \\frac{\\delta l}{\\delta z_n} \\end{bmatrix} \\begin{bmatrix} w_{11} & w_{12} & \\cdots & w_{1n} \\\\ w_{21} & w_{22} & \\cdots & w_{2n} \\\\ \\vdots & \\vdots & \\ddots & \\vdots \\\\ w_{i1} & w_{i2} & \\cdots & w_{in} \\end{bmatrix}$\n",
"\n",
"## Note With Layer_Dense class\n",
"The Layer_Dense class has the weights stored in the transposed fashion for forward propagation. Therefore, the weight matrix must be transposed for the backpropagation."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Adding the Backward Propagation Method to Layer_Dense and ReLU Activation Classes"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [],
"source": [
"class Layer_Dense:\n",
" def __init__(self, n_inputs, n_neurons):\n",
" # Initialize the weights and biases\n",
" self.weights = 0.01 * np.random.randn(n_inputs, n_neurons) # Normal distribution of weights\n",
" self.biases = np.zeros((1, n_neurons))\n",
"\n",
" def forward(self, inputs):\n",
" # Calculate the output values from inputs, weights, and biases\n",
" self.inputs = inputs\n",
" self.output = np.dot(inputs, self.weights) + self.biases # Weights are already transposed\n",
" \n",
" def backward(self, dvalues):\n",
" '''Calculated the gradient of the loss with respect to the weights and biases of this layer.\n",
" dvalues is equiavelent to a transposed dl_dZ. It is the gradient \n",
" of the loss with respect to the outputs of this layer.'''\n",
" self.dweights = np.dot(self.inputs.T, dvalues)\n",
" self.dbiases = np.sum(dvalues, axis=0, keepdims=0)\n",
" self.dinputs = np.dot(dvalues, self.weights.T)\n",
"\n",
"class Activation_ReLU:\n",
" def forward(self, inputs):\n",
" self.inputs = inputs\n",
" self.output = np.maximum(0, inputs)\n",
" \n",
" def backward(self, dvalues):\n",
" '''Calculated the gradient of the loss with respect to this layer's activation function\n",
" dvalues is equiavelent to a transposed dl_dZ. It is the gradient \n",
" of the loss with respect to the outputs of this layer.'''\n",
" self.dinputs = dvalues.copy()\n",
" self.dinputs[self.inputs <= 0] = 0"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Adding the Backward Propagation Method to the Loss_CategoricalCrossEntropy Class"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [],
"source": [
"class Loss_CategoricalCrossEntropy(Loss):\n",
" def forward(self, y_pred, y_true):\n",
" '''y_pred is the neural network output\n",
" y_true is the ideal output of the neural network'''\n",
" samples = len(y_pred)\n",
" # Bound the predicted values \n",
" y_pred_clipped = np.clip(y_pred, 1e-7, 1-1e-7)\n",
" \n",
" if len(y_true.shape) == 1: # Categorically labeled\n",
" correct_confidences = y_pred_clipped[range(samples), y_true]\n",
" elif len(y_true.shape) == 2: # One hot encoded\n",
" correct_confidences = np.sum(y_pred_clipped*y_true, axis=1)\n",
"\n",
" # Calculate the losses\n",
" negative_log_likelihoods = -np.log(correct_confidences)\n",
" return negative_log_likelihoods\n",
" \n",
" def backward(self, dvalues, y_true):\n",
" samples = len(dvalues)\n",
"\n",
" # Number of lables in each sample\n",
" labels = len(dvalues[0])\n",
"\n",
" # if the labels are sparse, turn them into a one-hot vector\n",
" if len(y_true.shape) == 1:\n",
" y_true = np.eye(labels)[y_true]\n",
"\n",
" # Calculate the gradient then normalize\n",
" self.dinputs = -y_true / dvalues\n",
" self.dinputs = self.dinputs / samples"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Combined Softmax Activation and Cross Entropy Loss"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [],
"source": [
"class Activation_Softmax_Loss_CategoricalCrossentropy():\n",
" def __init__(self):\n",
" self.activation = Activation_Softmax()\n",
" self.loss = Loss_CategoricalCrossEntropy()\n",
"\n",
" def forward(self, inputs, y_true):\n",
" self.activation.forward(inputs)\n",
" self.output = self.activation.output\n",
" return self.loss.calculate(self.output, y_true)\n",
" \n",
" def backward(self, dvalues, y_true):\n",
" samples = len(dvalues)\n",
"\n",
" # if the samples are one-hot encoded, turn them into discrete values\n",
" if len(y_true.shape) == 2:\n",
" y_true = np.argmax(y_true, axis=1)\n",
" \n",
" # Copy so we can safely modify\n",
" self.dinputs = dvalues.copy()\n",
" \n",
" # Calculate and normalize gradient \n",
" self.dinputs[range(samples), y_true] -= 1\n",
" self.dinputs = self.dinputs / samples"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gradients: combined loss and activation:\n",
"[[-0.1 0.03333333 0.06666667]\n",
" [ 0.03333333 -0.16666667 0.13333333]\n",
" [ 0.00666667 -0.03333333 0.02666667]]\n"
]
}
],
"source": [
"softmax_outputs = np.array([[0.7, 0.1, 0.2],\n",
" [0.1, 0.5, 0.4],\n",
" [0.02, 0.9, 0.08]])\n",
"class_targets = np.array([0, 1, 1])\n",
"softmax_loss = Activation_Softmax_Loss_CategoricalCrossentropy()\n",
"softmax_loss.backward(softmax_outputs, class_targets)\n",
"dvalues1 = softmax_loss.dinputs\n",
"print('Gradients: combined loss and activation:')\n",
"print(dvalues1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Optimizer_SGD Class"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [],
"source": [
"class Optimizer_SGD():\n",
" def __init__(self, learning_rate=0.5):\n",
" self.learning_rate = learning_rate\n",
"\n",
" def update_params(self, layer):\n",
" layer.weights += -self.learning_rate * layer.dweights\n",
" layer.biases += -self.learning_rate * layer.dbiases"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Optimizer_SGD Class on Spiral Dataset"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"epoch: 0, acc: 0.350, loss: 1.099\n",
"epoch: 100, acc: 0.457, loss: 1.090\n",
"epoch: 200, acc: 0.460, loss: 1.058\n",
"epoch: 300, acc: 0.460, loss: 1.055\n",
"epoch: 400, acc: 0.463, loss: 1.053\n",
"epoch: 500, acc: 0.463, loss: 1.052\n",
"epoch: 600, acc: 0.463, loss: 1.052\n",
"epoch: 700, acc: 0.460, loss: 1.052\n",
"epoch: 800, acc: 0.463, loss: 1.051\n",
"epoch: 900, acc: 0.450, loss: 1.051\n",
"epoch: 1000, acc: 0.447, loss: 1.051\n",
"epoch: 1100, acc: 0.450, loss: 1.050\n",
"epoch: 1200, acc: 0.453, loss: 1.049\n",
"epoch: 1300, acc: 0.453, loss: 1.048\n",
"epoch: 1400, acc: 0.453, loss: 1.046\n",
"epoch: 1500, acc: 0.457, loss: 1.044\n",
"epoch: 1600, acc: 0.457, loss: 1.040\n",
"epoch: 1700, acc: 0.463, loss: 1.036\n",
"epoch: 1800, acc: 0.457, loss: 1.030\n",
"epoch: 1900, acc: 0.467, loss: 1.025\n",
"epoch: 2000, acc: 0.477, loss: 1.019\n",
"epoch: 2100, acc: 0.500, loss: 1.013\n",
"epoch: 2200, acc: 0.513, loss: 1.007\n",
"epoch: 2300, acc: 0.523, loss: 0.999\n",
"epoch: 2400, acc: 0.533, loss: 0.990\n",
"epoch: 2500, acc: 0.540, loss: 0.981\n",
"epoch: 2600, acc: 0.537, loss: 0.973\n",
"epoch: 2700, acc: 0.543, loss: 0.964\n",
"epoch: 2800, acc: 0.537, loss: 0.957\n",
"epoch: 2900, acc: 0.547, loss: 0.947\n",
"epoch: 3000, acc: 0.553, loss: 0.938\n",
"epoch: 3100, acc: 0.507, loss: 0.937\n",
"epoch: 3200, acc: 0.523, loss: 0.950\n",
"epoch: 3300, acc: 0.523, loss: 0.931\n",
"epoch: 3400, acc: 0.537, loss: 0.950\n",
"epoch: 3500, acc: 0.480, loss: 0.929\n",
"epoch: 3600, acc: 0.490, loss: 0.925\n",
"epoch: 3700, acc: 0.540, loss: 0.932\n",
"epoch: 3800, acc: 0.530, loss: 0.916\n",
"epoch: 3900, acc: 0.507, loss: 0.932\n",
"epoch: 4000, acc: 0.487, loss: 0.939\n",
"epoch: 4100, acc: 0.590, loss: 0.950\n",
"epoch: 4200, acc: 0.530, loss: 0.932\n",
"epoch: 4300, acc: 0.523, loss: 0.921\n",
"epoch: 4400, acc: 0.450, loss: 0.907\n",
"epoch: 4500, acc: 0.487, loss: 0.932\n",
"epoch: 4600, acc: 0.507, loss: 0.906\n",
"epoch: 4700, acc: 0.493, loss: 0.908\n",
"epoch: 4800, acc: 0.487, loss: 0.911\n",
"epoch: 4900, acc: 0.547, loss: 0.908\n",
"epoch: 5000, acc: 0.520, loss: 0.913\n",
"epoch: 5100, acc: 0.537, loss: 0.909\n",
"epoch: 5200, acc: 0.560, loss: 0.907\n",
"epoch: 5300, acc: 0.553, loss: 0.914\n",
"epoch: 5400, acc: 0.580, loss: 0.893\n",
"epoch: 5500, acc: 0.573, loss: 0.927\n",
"epoch: 5600, acc: 0.573, loss: 0.910\n",
"epoch: 5700, acc: 0.523, loss: 0.886\n",
"epoch: 5800, acc: 0.593, loss: 0.894\n",
"epoch: 5900, acc: 0.530, loss: 0.904\n",
"epoch: 6000, acc: 0.540, loss: 0.876\n",
"epoch: 6100, acc: 0.510, loss: 0.900\n",
"epoch: 6200, acc: 0.567, loss: 0.881\n",
"epoch: 6300, acc: 0.583, loss: 0.920\n",
"epoch: 6400, acc: 0.573, loss: 0.896\n",
"epoch: 6500, acc: 0.550, loss: 0.865\n",
"epoch: 6600, acc: 0.500, loss: 0.899\n",
"epoch: 6700, acc: 0.590, loss: 0.874\n",
"epoch: 6800, acc: 0.590, loss: 0.936\n",
"epoch: 6900, acc: 0.547, loss: 0.894\n",
"epoch: 7000, acc: 0.570, loss: 0.890\n",
"epoch: 7100, acc: 0.560, loss: 0.876\n",
"epoch: 7200, acc: 0.583, loss: 0.866\n",
"epoch: 7300, acc: 0.550, loss: 0.876\n",
"epoch: 7400, acc: 0.527, loss: 0.874\n",
"epoch: 7500, acc: 0.533, loss: 0.854\n",
"epoch: 7600, acc: 0.540, loss: 0.847\n",
"epoch: 7700, acc: 0.540, loss: 0.842\n",
"epoch: 7800, acc: 0.540, loss: 0.841\n",
"epoch: 7900, acc: 0.553, loss: 0.882\n",
"epoch: 8000, acc: 0.577, loss: 0.961\n",
"epoch: 8100, acc: 0.500, loss: 0.914\n",
"epoch: 8200, acc: 0.510, loss: 0.872\n",
"epoch: 8300, acc: 0.513, loss: 0.869\n",
"epoch: 8400, acc: 0.597, loss: 0.898\n",
"epoch: 8500, acc: 0.553, loss: 0.927\n",
"epoch: 8600, acc: 0.520, loss: 0.884\n",
"epoch: 8700, acc: 0.533, loss: 0.852\n",
"epoch: 8800, acc: 0.540, loss: 0.844\n",
"epoch: 8900, acc: 0.540, loss: 0.840\n",
"epoch: 9000, acc: 0.537, loss: 0.840\n",
"epoch: 9100, acc: 0.543, loss: 0.851\n",
"epoch: 9200, acc: 0.560, loss: 0.880\n",
"epoch: 9300, acc: 0.590, loss: 0.914\n",
"epoch: 9400, acc: 0.610, loss: 0.926\n",
"epoch: 9500, acc: 0.533, loss: 0.932\n",
"epoch: 9600, acc: 0.503, loss: 0.915\n",
"epoch: 9700, acc: 0.503, loss: 0.894\n",
"epoch: 9800, acc: 0.510, loss: 0.882\n",
"epoch: 9900, acc: 0.513, loss: 0.873\n",
"epoch: 10000, acc: 0.513, loss: 0.872\n"
]
}
],
"source": [
"# Create dataset\n",
"X, y = spiral_data(samples=100, classes=3)\n",
"\n",
"# Create Dense layer with 2 input features and 64 output values\n",
"dense1 = Layer_Dense(2, 64)\n",
"\n",
"# Create ReLU activation (to be used with Dense layer)\n",
"activation1 = Activation_ReLU()\n",
"\n",
"# Create second Dense layer with 64 input features (as we take output\n",
"# of previous layer here) and 3 output values (output values)\n",
"dense2 = Layer_Dense(64, 3)\n",
"\n",
"# Create Softmax classifier's combined loss and activation\n",
"loss_activation = Activation_Softmax_Loss_CategoricalCrossentropy()\n",
"\n",
"# Create optimizer\n",
"optimizer = Optimizer_SGD()\n",
"\n",
"# Train in loop\n",
"for epoch in range(10001):\n",
" # Perform a forward pass of our training data through this layer\n",
" dense1.forward(X)\n",
" \n",
" # Perform a forward pass through activation function\n",
" # takes the output of first dense layer here\n",
" activation1.forward(dense1.output)\n",
" \n",
" # Perform a forward pass through second Dense layer\n",
" # takes outputs of activation function of first layer as inputs\n",
" dense2.forward(activation1.output)\n",
" \n",
" # Perform a forward pass through the activation/loss function\n",
" # takes the output of second dense layer here and returns loss\n",
" loss = loss_activation.forward(dense2.output, y)\n",
" \n",
" # Calculate accuracy from output of activation2 and targets\n",
" # calculate values along first axis\n",
" predictions = np.argmax(loss_activation.output, axis=1)\n",
" if len(y.shape) == 2:\n",
" y = np.argmax(y, axis=1)\n",
" accuracy = np.mean(predictions == y)\n",
" \n",
" if not epoch % 100:\n",
" print(f'epoch: {epoch}, ' +\n",
" f'acc: {accuracy:.3f}, ' +\n",
" f'loss: {loss:.3f}')\n",
" \n",
" # Backward pass\n",
" loss_activation.backward(loss_activation.output, y)\n",
" dense2.backward(loss_activation.dinputs)\n",
" activation1.backward(dense2.dinputs)\n",
" dense1.backward(activation1.dinputs)\n",
" \n",
" # Update weights and biases\n",
" optimizer.update_params(dense1)\n",
" optimizer.update_params(dense2)\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"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.10.12"
}
},
"nbformat": 4,
"nbformat_minor": 2
}