Lecture 23 and 24 exports
This commit is contained in:
parent
e190b86c70
commit
55795cc52f
@ -1,7 +1,7 @@
|
||||
# Purpose
|
||||
Following along with the playlist created by Vizuara on Youtube (https://www.youtube.com/playlist?list=PLPTV0NXA_ZSj6tNyn_UadmUeU3Q3oR-hu).
|
||||
|
||||
The primary objective is to gain a foundational understanding of simple neural networks including forward propagation, activation layers, backward propagation, and gradient descent.
|
||||
The primary objective is to gain a foundational understanding of simple neural networks including forward propagation, activation layers, backward propagation, gradient descent,learning rate decay, and momentum.
|
||||
|
||||
## Lecture Contents
|
||||
Lectures 1-2 use same handout.
|
||||
@ -18,8 +18,6 @@ Lectures 18-22 use same handout.
|
||||
|
||||
Lectures 23-24 use same handout.
|
||||
|
||||
Lectures 25-26 use same handout.
|
||||
|
||||
Lecture 27 uses same handout.
|
||||
Lectures 25-27 use same handout.
|
||||
|
||||
Lectures 28-31 use same handout.
|
||||
BIN
lecture23_24/notes_23.pdf
Normal file
BIN
lecture23_24/notes_23.pdf
Normal file
Binary file not shown.
402
lecture23_24/notes_23.py
Normal file
402
lecture23_24/notes_23.py
Normal file
@ -0,0 +1,402 @@
|
||||
# %% [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):
|
||||
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]
|
||||
# # 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]
|
||||
# # Learning Rate Decay
|
||||
# Start with a larger learning rate and gradually decrease it.
|
||||
#
|
||||
# $\alpha = \frac{\alpha_0}{1+decay*t}$
|
||||
|
||||
# %%
|
||||
class Optimizer_SGD():
|
||||
def __init__(self, learning_rate=0.5, decay=0.0):
|
||||
self.initial_rate = learning_rate
|
||||
self.current_learning_rate = self.initial_rate
|
||||
self.decay = decay
|
||||
self.iterations = 0
|
||||
|
||||
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):
|
||||
layer.weights += -self.current_learning_rate * layer.dweights
|
||||
layer.biases += -self.current_learning_rate * layer.dbiases
|
||||
|
||||
def post_update_params(self):
|
||||
# Update the self.iterations for use with decay
|
||||
self.iterations += 1
|
||||
|
||||
# %% [markdown]
|
||||
# # Testing the Learning Rate Decay
|
||||
|
||||
# %%
|
||||
# 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(learning_rate=1.0, decay=1e-3)
|
||||
|
||||
# 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.pre_update_params()
|
||||
optimizer.update_params(dense1)
|
||||
optimizer.update_params(dense2)
|
||||
optimizer.post_update_params()
|
||||
|
||||
|
||||
# %% [markdown]
|
||||
# # Momentum in Training Neural Networks
|
||||
# Using the past information on how changing the weights and biases changes the loss, we can use the large dimensional vectors to try and cancel out the overshoot.
|
||||
#
|
||||
# The new weight update = some factor * last weight update + learning rate * current gradient
|
||||
|
||||
# %%
|
||||
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]
|
||||
# # Testing the Gradient Optimizer with Momentum
|
||||
|
||||
# %%
|
||||
# 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(learning_rate=1.0, decay=1e-3, momentum=0.9)
|
||||
|
||||
# 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.pre_update_params()
|
||||
optimizer.update_params(dense1)
|
||||
optimizer.update_params(dense2)
|
||||
optimizer.post_update_params()
|
||||
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
4464
lecture25_27/handout_25.ipynb
Normal file
4464
lecture25_27/handout_25.ipynb
Normal file
File diff suppressed because one or more lines are too long
267
lecture25_27/notes_25.ipynb
Normal file
267
lecture25_27/notes_25.ipynb
Normal file
@ -0,0 +1,267 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Previous Class Definitions"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"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": null,
|
||||
"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\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\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\n",
|
||||
"\n",
|
||||
"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\n",
|
||||
"\n",
|
||||
"class Optimizer_SGD():\n",
|
||||
" def __init__(self, learning_rate=0.5, decay=0.0, momentum=0.0):\n",
|
||||
" self.initial_rate = learning_rate\n",
|
||||
" self.current_learning_rate = self.initial_rate\n",
|
||||
" self.decay = decay\n",
|
||||
" self.iterations = 0\n",
|
||||
" self.momentum = momentum\n",
|
||||
"\n",
|
||||
" def pre_update_params(self):\n",
|
||||
" # Update the current_learning_rate before updating params\n",
|
||||
" if self.decay:\n",
|
||||
" self.current_learning_rate = self.initial_rate / (1 + self.decay * self.iterations)\n",
|
||||
"\n",
|
||||
" def update_params(self, layer):\n",
|
||||
" if self.momentum:\n",
|
||||
" # For each layer, we need to use its last momentums\n",
|
||||
"\n",
|
||||
" # First check if the layer has a last momentum stored\n",
|
||||
" if not hasattr(layer, 'weight_momentums'):\n",
|
||||
" layer.weight_momentums = np.zeros_like(layer.weights)\n",
|
||||
" layer.bias_momentums = np.zeros_like(layer.biases)\n",
|
||||
" \n",
|
||||
" weight_updates = self.momentum * layer.weight_momentums - \\\n",
|
||||
" self.current_learning_rate * layer.dweights\n",
|
||||
" layer.weight_momentums = weight_updates\n",
|
||||
"\n",
|
||||
" bias_updates = self.momentum * layer.bias_momentums - \\\n",
|
||||
" self.current_learning_rate * layer.dbiases\n",
|
||||
" layer.bias_momentums = bias_updates\n",
|
||||
" \n",
|
||||
" # Not using momentum\n",
|
||||
" else:\n",
|
||||
" weight_updates = -self.current_learning_rate * layer.dweights\n",
|
||||
" bias_updates = -self.current_learning_rate * layer.dbiases\n",
|
||||
"\n",
|
||||
" layer.weights += weight_updates\n",
|
||||
" layer.biases += bias_updates\n",
|
||||
"\n",
|
||||
" def post_update_params(self):\n",
|
||||
" # Update the self.iterations for use with decay\n",
|
||||
" self.iterations += 1"
|
||||
]
|
||||
},
|
||||
{
|
||||
"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": [
|
||||
"# AdaGrad Optimizer"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
Loading…
Reference in New Issue
Block a user