# %% [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.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 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 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 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 class Optimizer_SGD(): def __init__(self, learning_rate=0.5, decay=0.0, momentum=0.0): self.initial_rate = learning_rate self.current_learning_rate = self.initial_rate self.decay = decay self.iterations = 0 self.momentum = momentum def pre_update_params(self): # Update the current_learning_rate before updating params if self.decay: self.current_learning_rate = self.initial_rate / (1 + self.decay * self.iterations) def update_params(self, layer): if self.momentum: # For each layer, we need to use its last momentums # First check if the layer has a last momentum stored if not hasattr(layer, 'weight_momentums'): layer.weight_momentums = np.zeros_like(layer.weights) layer.bias_momentums = np.zeros_like(layer.biases) weight_updates = self.momentum * layer.weight_momentums - \ self.current_learning_rate * layer.dweights layer.weight_momentums = weight_updates bias_updates = self.momentum * layer.bias_momentums - \ self.current_learning_rate * layer.dbiases layer.bias_momentums = bias_updates # Not using momentum else: weight_updates = -self.current_learning_rate * layer.dweights bias_updates = -self.current_learning_rate * layer.dbiases layer.weights += weight_updates layer.biases += bias_updates def post_update_params(self): # Update the self.iterations for use with decay self.iterations += 1 # %% [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] # # AdaGrad Optimizer # Different weights should have different learning rates. If one weight affects the loss much more strongly than the other, then consider using smaller learning rates with it. We can do this by maintaining a "cache" of the last gradients and normalizing based on this. # # A downside is that as the cache keeps accumulating, some neurons will have such a small learning rate that the neuron basically becomes fixed. # %% class Optimizer_Adagrad(): def __init__(self, learning_rate=0.5, decay=0.0, epsilon=1e-7): self.initial_learning_rate = learning_rate self.current_learning_rate = self.initial_learning_rate self.decay = decay self.iterations = 0 self.epsilon = epsilon def pre_update_params(self): if self.decay: self.current_learning_rate = self.initial_learning_rate / (1 + self.decay * self.iterations) def update_params(self, layer): if not hasattr(layer, 'weight_cache'): layer.weight_cache = np.zeros_like(layer.weights) layer.bias_cache = np.zeros_like(layer.biases) layer.weight_cache += layer.dweights**2 layer.bias_cache += layer.dbiases**2 layer.weights += -self.current_learning_rate * layer.dweights / (np.sqrt(layer.weight_cache) + self.epsilon) layer.biases += -self.current_learning_rate * layer.dbiases / (np.sqrt(layer.bias_cache) + self.epsilon) def post_update_params(self): self.iterations += 1 # %% [markdown] # ## Testing the AdagGrad Optimizer # %% # 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_Adagrad(learning_rate=1.0, decay=1e-4) # 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}, ' + f'lr: {optimizer.current_learning_rate}') # 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.pre_update_params() optimizer.update_params(dense1) optimizer.update_params(dense2) optimizer.post_update_params() # %% [markdown] # # RMSProp Optimizer # Root Meas Square Propagation optimizer. It is similar to AdaGrad in that you apply different learning rates to different weights. However, the way you change the learning rate focuses more on the most recent cache than the sum of all of the last gradients. # # Notably, RMSProp does not use momentum. While it does have information of the past gradient in the cache, it uses this to scale the learning rate, not to correct for overshooting. # %% class Optimizer_RMSProp(): def __init__(self, learning_rate=1e-3, decay=0.0, epsilon=1e-7, rho=0.9): self.initial_learning_rate = learning_rate self.current_learning_rate = self.initial_learning_rate self.decay = decay self.iterations = 0 self.epsilon = epsilon self.rho = rho def pre_update_params(self): if self.decay: self.current_learning_rate = self.initial_learning_rate / (1 + self.decay * self.iterations) def update_params(self, layer): if not hasattr(layer, 'weight_cache'): layer.weight_cache = np.zeros_like(layer.weights) layer.bias_cache = np.zeros_like(layer.biases) layer.weight_cache = self.rho * layer.weight_cache + (1 - self.rho) * layer.dweights**2 layer.bias_cache = self.rho * layer.bias_cache + (1 - self.rho) * layer.dbiases**2 layer.weights += -self.current_learning_rate * layer.dweights / (np.sqrt(layer.weight_cache) + self.epsilon) layer.biases += -self.current_learning_rate * layer.dbiases / (np.sqrt(layer.bias_cache) + self.epsilon) def post_update_params(self): self.iterations += 1 # %% [markdown] # ## Testing the RMSProp Optimizer # %% # 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_RMSProp(learning_rate=0.02, decay=1e-5, rho=0.999) # 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}, ' + f'lr: {optimizer.current_learning_rate}') # 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.pre_update_params() optimizer.update_params(dense1) optimizer.update_params(dense2) optimizer.post_update_params() # %% [markdown] # # Adam Optimizer # The Adam optimizer combines adaptive learning rate with momentum. # # $W_{i+1} = W_{i} - \frac{\alpha}{\sqrt{\frac{\text{cache}}{1- \beta_2^{i+1}}} + \epsilon} * \left(\beta_{1} * \frac{\text{Momentum}_i}{ 1- \beta_1^{i+1}} + \left(1 - \beta_2 \right) * \frac{\delta L}{\delta W}_i\right)$ # # From the equation, it is clear that the cache and momentum are "corrected" by dividing by some scalar that varies with the iteration value. This way, earlier iterations have larger corrected cache and momentum so local minima are harder to get stuck in. # %% import numpy as np # Adam optimizer class Optimizer_Adam(): def __init__(self, learning_rate=0.001, decay=0.0, epsilon=1e-7, beta_1=0.9, beta_2=0.999): self.initial_learning_rate = learning_rate self.current_learning_rate = learning_rate self.decay = decay self.iterations = 0 self.epsilon = epsilon self.beta_1 = beta_1 self.beta_2 = beta_2 def pre_update_params(self): if self.decay: self.current_learning_rate = self.initial_learning_rate * (1. / (1. + self.decay * self.iterations)) def update_params(self, layer): # If layer does not contain cache arrays, create them filled with zeros if not hasattr(layer, 'weight_cache'): layer.weight_momentums = np.zeros_like(layer.weights) layer.weight_cache = np.zeros_like(layer.weights) layer.bias_momentums = np.zeros_like(layer.biases) layer.bias_cache = np.zeros_like(layer.biases) # Update momentum with current gradients layer.weight_momentums = self.beta_1 * layer.weight_momentums + (1 - self.beta_1) * layer.dweights layer.bias_momentums = self.beta_1 * layer.bias_momentums + (1 - self.beta_1) * layer.dbiases # Get corrected momentum # use self.iteration + 1 because we start at iteration 0 weight_momentums_corrected = layer.weight_momentums / (1 - self.beta_1 ** (self.iterations + 1)) bias_momentums_corrected = layer.bias_momentums / (1 - self.beta_1 ** (self.iterations + 1)) # Update cache with squared current gradients layer.weight_cache = self.beta_2 * layer.weight_cache + (1 - self.beta_2) * layer.dweights**2 layer.bias_cache = self.beta_2 * layer.bias_cache + (1 - self.beta_2) * layer.dbiases**2 # Get corrected cache weight_cache_corrected = layer.weight_cache / (1 - self.beta_2 ** (self.iterations + 1)) bias_cache_corrected = layer.bias_cache / (1 - self.beta_2 ** (self.iterations + 1)) # Vanilla SGD parameter update + normalization with square rooted cache layer.weights += -self.current_learning_rate * weight_momentums_corrected / (np.sqrt(weight_cache_corrected) + self.epsilon) layer.biases += -self.current_learning_rate * bias_momentums_corrected / (np.sqrt(bias_cache_corrected) + self.epsilon) # Call once after any parameter updates def post_update_params(self): self.iterations += 1 # %% [markdown] # ## Testing the Adam Optimizer # %% # 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_Adam(learning_rate=0.02, decay=1e-5) # 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}, ' + f'lr: {optimizer.current_learning_rate}') # 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.pre_update_params() optimizer.update_params(dense1) optimizer.update_params(dense2) optimizer.post_update_params()