# %% [markdown] # # Previous Class Definitions # %% # imports import matplotlib.pyplot as plt import numpy as np import nnfs from nnfs.datasets import spiral_data, vertical_data nnfs.init() # %% class Layer_Dense: def __init__(self, n_inputs, n_neurons): # Initialize the weights and biases self.weights = 0.01 * np.random.randn(n_inputs, n_neurons) # Normal distribution of weights self.biases = np.zeros((1, n_neurons)) def forward(self, inputs): # Calculate the output values from inputs, weights, and biases self.output = np.dot(inputs, self.weights) + self.biases # Weights are already transposed class Activation_ReLU: def forward(self, inputs): self.output = np.maximum(0, inputs) class Activation_Softmax: def forward(self, inputs): # Get the unnormalized probabilities # Subtract max from the row to prevent larger numbers exp_values = np.exp(inputs - np.max(inputs, axis=1, keepdims=True)) # Normalize the probabilities with element wise division probabilities = exp_values / np.sum(exp_values, axis=1,keepdims=True) self.output = probabilities # Base class for Loss functions class Loss: '''Calculates the data and regularization losses given model output and ground truth values''' def calculate(self, output, y): sample_losses = self.forward(output, y) data_loss = np.average(sample_losses) return data_loss class Loss_CategoricalCrossEntropy(Loss): def forward(self, y_pred, y_true): '''y_pred is the neural network output y_true is the ideal output of the neural network''' samples = len(y_pred) # Bound the predicted values y_pred_clipped = np.clip(y_pred, 1e-7, 1-1e-7) if len(y_true.shape) == 1: # Categorically labeled correct_confidences = y_pred_clipped[range(samples), y_true] elif len(y_true.shape) == 2: # One hot encoded correct_confidences = np.sum(y_pred_clipped*y_true, axis=1) # Calculate the losses negative_log_likelihoods = -np.log(correct_confidences) return negative_log_likelihoods # %% [markdown] # # Previous Notes and Notation # 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. # # $\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. # # $\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. # # $\vec{B} = \begin{bmatrix} b_1 & b_2 & \cdots & b_i \end{bmatrix}$ -> Row vector for the neuron biases # # $\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. # # $\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. # # $y_j$ -> Final layer output for the $j$ batch of data if the layer is the final layer (could be summation, probability, etc). # # $l_j$ -> Loss for the $j$ batch of data. # # The $j$ is often dropped because we typically only need to think with 1 set of input data. # # ## Gradient Descent Using New Notation # We will look at the weight that the $i$ neuron applies for the $n$ input. # # $\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}}$ # # Similarly, for the bias of the $i$ neuron, there is # # $\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}}$ # # For the system we are using, where $l = (y-0)^2$ and the activation layer is ReLU, we have # # $\frac{\delta l}{\delta y} = 2y$ # # $\frac{\delta y}{\delta a_i} = 1$ # # $\frac{\delta a_i}{\delta z_i} = 1$ if $z_i > 0$ else $0$ # # $\frac{\delta z_i}{\delta w_{in}} = x_n$ # # $\frac{\delta z_i}{\delta b_{i}} = 1$ # # ## Matrix Representation of Gradient Descent # 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. # # We take $\frac{\delta l}{\delta z_i}$ and turn it into a 1 x $i$ vector that such that # # $\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}$ # # We than can get that the gradient matrix for all weights is a $i$ x $n$ matrix given by # # $\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}$ # # Similarly, the gradient vector for the biases is given by # $\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}$ # # ## Gradients of the Loss with Respect to Inputs # 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. # # The gradient of the loss with respect to the $n$ input fed into $i$ neurons is # # $\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}$ # # # Noting that $\frac{\delta z_i}{\delta x_n} = w_{in}$ allows us to have # # $\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}$ # # ## Note With Layer_Dense class # 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. # %% [markdown] # # Adding the Backward Propagation Method to Layer_Dense and ReLU Activation Classes # %% class Layer_Dense: def __init__(self, n_inputs, n_neurons): # Initialize the weights and biases self.weights = 0.01 * np.random.randn(n_inputs, n_neurons) # Normal distribution of weights self.biases = np.zeros((1, n_neurons)) def forward(self, inputs): # Calculate the output values from inputs, weights, and biases self.inputs = inputs self.output = np.dot(inputs, self.weights) + self.biases # Weights are already transposed def backward(self, dvalues): '''Calculated the gradient of the loss with respect to the weights and biases of this layer. dvalues is equiavelent to a transposed dl_dZ. It is the gradient of the loss with respect to the outputs of this layer.''' self.dweights = np.dot(self.inputs.T, dvalues) self.dbiases = np.sum(dvalues, axis=0, keepdims=0) self.dinputs = np.dot(dvalues, self.weights.T) class Activation_ReLU: def forward(self, inputs): self.inputs = inputs self.output = np.maximum(0, inputs) def backward(self, dvalues): '''Calculated the gradient of the loss with respect to this layer's activation function dvalues is equiavelent to a transposed dl_dZ. It is the gradient of the loss with respect to the outputs of this layer.''' self.dinputs = dvalues.copy() self.dinputs[self.inputs <= 0] = 0 # %% [markdown] # # Adding the Backward Propagation Method to the Loss_CategoricalCrossEntropy Class # %% class Loss_CategoricalCrossEntropy(Loss): def forward(self, y_pred, y_true): '''y_pred is the neural network output y_true is the ideal output of the neural network''' samples = len(y_pred) # Bound the predicted values y_pred_clipped = np.clip(y_pred, 1e-7, 1-1e-7) if len(y_true.shape) == 1: # Categorically labeled correct_confidences = y_pred_clipped[range(samples), y_true] elif len(y_true.shape) == 2: # One hot encoded correct_confidences = np.sum(y_pred_clipped*y_true, axis=1) # Calculate the losses negative_log_likelihoods = -np.log(correct_confidences) return negative_log_likelihoods def backward(self, dvalues, y_true): samples = len(dvalues) # Number of lables in each sample labels = len(dvalues[0]) # if the labels are sparse, turn them into a one-hot vector if len(y_true.shape) == 1: y_true = np.eye(labels)[y_true] # Calculate the gradient then normalize self.dinputs = -y_true / dvalues self.dinputs = self.dinputs / samples # %% [markdown] # # Combined Softmax Activation and Cross Entropy Loss # %% class Activation_Softmax_Loss_CategoricalCrossentropy(): def __init__(self): self.activation = Activation_Softmax() self.loss = Loss_CategoricalCrossEntropy() def forward(self, inputs, y_true): self.activation.forward(inputs) self.output = self.activation.output return self.loss.calculate(self.output, y_true) def backward(self, dvalues, y_true): samples = len(dvalues) # if the samples are one-hot encoded, turn them into discrete values if len(y_true.shape) == 2: y_true = np.argmax(y_true, axis=1) # Copy so we can safely modify self.dinputs = dvalues.copy() # Calculate and normalize gradient self.dinputs[range(samples), y_true] -= 1 self.dinputs = self.dinputs / samples # %% softmax_outputs = np.array([[0.7, 0.1, 0.2], [0.1, 0.5, 0.4], [0.02, 0.9, 0.08]]) class_targets = np.array([0, 1, 1]) softmax_loss = Activation_Softmax_Loss_CategoricalCrossentropy() softmax_loss.backward(softmax_outputs, class_targets) dvalues1 = softmax_loss.dinputs print('Gradients: combined loss and activation:') print(dvalues1) # %% [markdown] # # Optimizer_SGD Class # %% class Optimizer_SGD(): def __init__(self, learning_rate=0.5): self.learning_rate = learning_rate def update_params(self, layer): layer.weights += -self.learning_rate * layer.dweights layer.biases += -self.learning_rate * layer.dbiases # %% [markdown] # ## Optimizer_SGD Class on Spiral Dataset # %% # Create dataset X, y = spiral_data(samples=100, classes=3) # Create Dense layer with 2 input features and 64 output values dense1 = Layer_Dense(2, 64) # Create ReLU activation (to be used with Dense layer) activation1 = Activation_ReLU() # Create second Dense layer with 64 input features (as we take output # of previous layer here) and 3 output values (output values) dense2 = Layer_Dense(64, 3) # Create Softmax classifier's combined loss and activation loss_activation = Activation_Softmax_Loss_CategoricalCrossentropy() # Create optimizer optimizer = Optimizer_SGD() # Train in loop for epoch in range(10001): # Perform a forward pass of our training data through this layer dense1.forward(X) # Perform a forward pass through activation function # takes the output of first dense layer here activation1.forward(dense1.output) # Perform a forward pass through second Dense layer # takes outputs of activation function of first layer as inputs dense2.forward(activation1.output) # Perform a forward pass through the activation/loss function # takes the output of second dense layer here and returns loss loss = loss_activation.forward(dense2.output, y) # Calculate accuracy from output of activation2 and targets # calculate values along first axis predictions = np.argmax(loss_activation.output, axis=1) if len(y.shape) == 2: y = np.argmax(y, axis=1) accuracy = np.mean(predictions == y) if not epoch % 100: print(f'epoch: {epoch}, ' + f'acc: {accuracy:.3f}, ' + f'loss: {loss:.3f}') # Backward pass loss_activation.backward(loss_activation.output, y) dense2.backward(loss_activation.dinputs) activation1.backward(dense2.dinputs) dense1.backward(activation1.dinputs) # Update weights and biases optimizer.update_params(dense1) optimizer.update_params(dense2)