In this post, let’s get right into the code!
Let’s start out by defining a basic neural network. There will be many more utility functions to write soon, but this will at least give us a basic idea of what things will look like. Our network will be comprised of layers, biases, and weights, and given that the biases and weights are there to modify the layers, we should be able to create them automatically:
def create_layer(layer_size, dtype=np.float32, **kwargs): layer = np.zeros(layer_size, dtype=dtype) return(layer)def create_layer_weights(prev_ly_size, curr_ly_size, init=True): if init: #ly_weights = np.random.rand(prev_ly_size, curr_ly_size) ly_weights = np.random.uniform(-1,1, size=(prev_ly_size, curr_ly_size)) else: ly_weights = np.zeros(shape=(prev_ly_size, curr_ly_size)) return(ly_weights)def create_biases(ly_size, init=True): if init: biases = np.random.rand(ly_size) else: biases = np.zeros(ly_size) return(biases)
We can now create a network, which is just an object containing lists of layers, biases, and weights. We’ll also store the z-values(the values of each neuron before being run through the activation function), because future us finds out they’re necessary to help do backpropagation :
class n_network: def __init__(self, layers, z_layers, biases, weights): self.layers = layers self.z_layers = z_layers self.biases = biases self.weights = weightsdef create_network(in_ly_size, out_ly_size, hidden_ly_num, hidden_ly_size): in_layer = create_layer(in_ly_size) hidden_lys = [] for index in range(hidden_ly_num): hidden_lys.append(create_layer(hidden_ly_size)) out_layer = create_layer(out_ly_size) network_lys = [in_layer, *hidden_lys, out_layer] z_layers = deep_copy_mat_list(network_lys, False) biases =[] for i in range(1, len(network_lys), 1): biases.append(create_biases(np.size(network_lys[i]), init=False)) weights = [] for i in range(1, len(network_lys), 1): weights.append( create_layer_weights(np.size(network_lys[i-1]), np.size(network_lys[i]), init=True)) network = n_network(network_lys, z_layers, biases, weights) return(network)
We also need to create a function to create deep copies of Python lists, as simply creating a copy this way:
z_layers = network_lys
will create a new list linked to the same objects, rather than copying the objects themselves, so we create a function:
def deep_copy_mat_list (list_to_copy, propigate_cell_vals=True): #creates a copy of a list containing numpy arrays of varible size, ethier as empty arrays or with the same values new_list = [] if propigate_cell_vals: for items in list_to_copy: new_list.append(items) else: for items in list_to_copy: new_list.append(np.zeros_like(items)) return(new_list)
Now, to test if the network will run, we can add our forward and activation functions. For this project, we’re going to use a sigmoid function. We’ll also add its derivative (sigmoid_prime), which we’ll need for backprop later:
def forward(input_vals:np.ndarray, net:n_network): #first layer input_vals = np.array(input_vals) net.layers[0] = input_vals for index in range(1, len(net.layers), 1): net.z_layers[index] = np.dot(net.layers[(index-1)], net.weights[index-1]) + net.biases[index-1] net.layers[index] = sigmond(net.z_layers[index]) #activation function return(net)def sigmond(input): #a more easily vectorizable sigmond function return( 1/(1+np.exp(-input)))def sigmond_prime(input): return(sigmond(input) * (1-sigmond(input)))
With this done, we can test a forward pass, using random weights and a mostly empty input layer. This should just output random gibberish, but it’s a good check to see that the network is functional:
net = create_network(28*28, 10, 2, 5)input_ly = np.zeros((28,28))input_ly[3,4] = 1input_ly = input_ly.flatten()out = forward(input_ly, net)print(np.max(out.layers[-1]))
Now that we have a basic idea of our neural network, we can get into the bulk of the work. To start out, before we get into any of the ML, we need to get our dataset imported and make sure we can handle and inspect training data. The MNIST digit dataset can be downloaded here and is split into images, labels, training, and test, formatted in .idx1-ubyte or .idx3-ubyte. If the files have a .gz format as well, they will need to be unzipped before use. A quick peek into these files once they’re unzipped shows that they’re in a binary format, which is common for large ML datasets. So to read and manipulate the data, we’ll write a few functions:
import matplotlib.pyplot as pltimport numpy as npimages_path = "MNIST/train-images.idx3-ubyte"labels_path = "MNIST/train-labels.idx1-ubyte"batch_size = 2dataset_size = 60000image_size = 28**2image_dim = int(np.sqrt(image_size))def label_to_output(int) -> np.ndarray: #for a single label outlayer = np.zeros(shape=(10), dtype=np.float32) outlayer[int] = 1 return(outlayer)def label_vec_to_output(inputs: np.ndarray) -> np.ndarray: #for a batch of labels # Create an identity matrix of size 10 and index into it return np.eye(10, dtype=np.int8)[inputs]def create_batch(image_file, label_file): #this takes the raw file objects and reads an appropriately sized batch in numpy arrays image_buffer = image_file.read(image_size * batch_size) input_batch = np.frombuffer(image_buffer, dtype=np.uint8).astype(np.float32) input_batch = input_batch.reshape(batch_size, image_size) label_buffer = label_file.read(batch_size) label_batch = np.frombuffer(label_buffer, dtype=np.uint8).astype(np.int64) Label_batch = label_vec_to_output(label_batch) return(input_batch, Label_batch)def view_batch_sample(batch_size, image_batch, label_batch): image_batch = image_batch.reshape(batch_size, image_dim, image_dim, 1) for index in range(batch_size): image = np.asarray(image_batch[index]).squeeze() plt.imshow(image) plt.show() print(f"image label: {np.argmax(label_batch[index])}")
Now let’s test our functions:
f = open(images_path, 'rb')f.read(16)l = open(labels_path,'rb')l.read(8)im_btc, lb_btc = create_batch(f, l)view_batch_sample(batch_size, im_btc, lb_btc)
Notice the functions for creating a batch do not load the files themselves. Since we will be creating many batches in a single training loop, we will only load the files into memory once in the high-level training loop. This is good practice to avoid wasting resources reloading the same files. We should see an output like this from our test code:

image label: 5

image label: 0
We should also add a loss function, maybe a couple other functions, and a config object. For this example, we’ll use the @dataclass decorator. This seems verbose but will make passing code parameters to functions much simpler. For simplicity purposes, I’ve removed references to cfg in the functions and objects shown up to this point, but they are included in the full working code on GitHub:
from dataclasses import dataclassdataclassclass Config: input_layer_size: int output_layer_size: int hidden_layer_num : int hidden_layer_size : int dataset_size : int learning_rate :float batch_size : int epochs : intdef loss(network_output_ly, expected_ly): #loss = mean of all output neurons - the expected, squared loss_vec = ((network_output_ly - expected_ly)**2) / 2 loss_sclr = np.sum((network_output_ly - expected_ly)**2) return(loss_sclr, loss_vec)
Now, finally, we can get to the core of our learning code. We’ll split this into three separate functions, with the core math happening in the backprop function:
def backprop_single(net: n_network, expected_out_ly): #does backprop for a single training example, duhh first = True expected_out_ly = np.array(expected_out_ly) w_delta = deep_copy_mat_list(net.weights, propigate_cell_vals=False) b_delta = deep_copy_mat_list(net.biases, propigate_cell_vals=False) a_error = deep_copy_mat_list(net.layers, propigate_cell_vals=False) for l in range(len(net.layers)-1, 0, -1): w = l - 1 if first: #first(last) layer first = False a_delta_dir = expected_out_ly - net.layers[l] a_error[l] = a_delta_dir * sigmond_prime(net.z_layers[l]) a_error[l-1] = np.dot(net.weights[w], a_error[l]) * sigmond_prime(net.z_layers[l-1]) w_delta[w] = np.outer(net.layers[l-1], a_error[l]) b_delta[w] = a_error[l] else: a_error[l] = np.dot(net.weights[w+1], a_error[l+1]) * sigmond_prime(net.z_layers[l]) w_delta[w] = np.outer(net.layers[l-1], a_error[l]) b_delta[w] = a_error[l] return(w_delta, b_delta)
This code bears explaining, as it’s the core of what makes our neural network able to learn, and therefore deserving of being called AI/ML. The code loops backwards through our network, because we can only directly measure error in the final(output) layer. We start by subtracting what the network predicted from our expected outputs(which will be a one-hot matrix containing the image label); this gives us a point on the error surface:
a_delta_dir = expected_out_ly - net.layers[l]
Note that this actually gives us the negative of our error; we do this because we want to reduce error. We could also do this by multiplying by -1 later when we want to apply changes, but doing it now means we don’t have to remember it later. Next, we’ll take the derivative of our activation function at that point; this will provide our error gradient. Note that to take the derivative properly, we actually use the pre-activation values for each neuron(the z values). This makes sense because we want to know how our layer changes with respect to its changes in its input values:
a_error[l] = a_delta_dir * sigmond_prime(net.z_layers[l])
We can now directly change the activations of our layer by biasing them with the negative error, and we can change the weights by multiplying the negative error by the activations of the prior layer. Applying either one of these changes would greatly reduce error for this training image, but would probably not help the network as a whole, as the gradient is not constant, and it will change for different training examples and as we manipulate weights and biases. Instead, we’ll simply save the suggested changes to the weights and biases of this layer and multiply them by the learning rate (a small number such as 0.01), and average them over a batch before applying them to the network. This is also just finding suggested changes to the final layer so far:
w_delta[w] = np.outer(net.layers[l-1], a_error[l])
b_delta[w] = a_error[l]
Since these are fully connected layers, each weight is directly connected to exactly 1 neuron in the prior layer and 1 neuron in the current layer, so we can find how to change them to reduce error by multiplying each weight by its corresponding activation in the prior layer and the negative error of the corresponding neuron in the current layer. This ends up being easily represented as the outer product. For a network of 1-D layers, it can even easily be visualized by a table:
| negative error in current layer neurons | |||||
| 0.24 | -0.12 | 0.9 | |||
| input neuron activations | 0.1 | 0.024 | -0.012 | 0.09 | |
| 0.5 | 0.12 | -0.06 | 0.45 | ||
| 0.78 | 0.1872 | -0.0936 | 0.702 | ||
| suggested changes to each weight ^ | |||||
For simple fully connected networks, this is a wonderful way to build intuition for how we use error to train neural networks. In many more complicated examples, finding an intuition becomes far harder to visualize, but the core of changing weights to reduce error by understanding how different neurons interact through weights… will remain largely the same.
Speaking of more complicated, we now need to backpropagate our error to prior layers. We do this one layer at a time, by finding how the error in each output neuron is formed by the weights and activations of the neurons in the prior layer:
a_error[l-1] = np.dot(net.weights[w], a_error[l]) * sigmond_prime(net.z_layers[l-1])
We’ve used the derivative of the activation function before to know how our layer changes with respect to its changes in its input values, so the only new part here is the dot product. The dot product here is transforming the error in the current layer, through the weights, into the prior layer. This can be a little counterintuitive at first, but it’s really just a way of summing the influence of the error in each output neuron to a given neuron in the prior layer, through the weights which connect each neuron.
Whew! Now that we’ve gone through all that for one layer, and backpropagated our measure of negative error to the next layer back, we can just repeat over the rest of the layers in the network, stopping one layer before the input layer, as we can’t influence it, and there are 1 fewer layers of weights than neurons, as the weights only exist between neuron layers.
for l in range(len(net.layers)-1, 0, -1):
if not last_layer:
w = l - 1
a_error[l] = np.dot(net.weights[w+1], a_error[l+1]) * sigmond_prime(net.z_layers[l])
w_delta[w] = np.outer(net.layers[l-1], a_error[l])
b_delta[w] = a_error[l]
Looking at the whole function again:
def backprop_single(net: n_network, expected_out_ly): #does backprop for a single training example, duhh first = True expected_out_ly = np.array(expected_out_ly) w_delta = deep_copy_mat_list(net.weights, propigate_cell_vals=False) b_delta = deep_copy_mat_list(net.biases, propigate_cell_vals=False) a_error = deep_copy_mat_list(net.layers, propigate_cell_vals=False) for l in range(len(net.layers)-1, 0, -1): w = l - 1 if first: #first(last) layer first = False a_delta_dir = expected_out_ly - net.layers[l] a_error[l] = a_delta_dir * sigmond_prime(net.z_layers[l]) a_error[l-1] = np.dot(net.weights[w], a_error[l]) * sigmond_prime(net.z_layers[l-1]) w_delta[w] = np.outer(net.layers[l-1], a_error[l]) b_delta[w] = a_error[l] else: a_error[l] = np.dot(net.weights[w+1], a_error[l+1]) * sigmond_prime(net.z_layers[l]) w_delta[w] = np.outer(net.layers[l-1], a_error[l]) b_delta[w] = a_error[l] return(w_delta, b_delta)
It finally returns weight change suggestions and bias change suggestions. We’ll now use a batching function to repeat this process and average the change suggestions over a batch of training examples:
def batch_learning(input_batch:np.ndarray, desired_output_batch:np.ndarray, net:n_network, cfg:Config):
#This runs the network across every training example in a single batch and averages the results, returning a decent step and the loss across the batch
cfg.batch_size
w_del_batch = []
b_del_batch = []
batch_loss = np.ndarray((cfg.batch_size,))
for layers in net.weights:
w_del_batch.append(np.zeros((cfg.batch_size,) + layers.shape, dtype=np.float32) )
for layers in net.biases:
b_del_batch.append(np.zeros((cfg.batch_size,) + layers.shape, dtype=np.float32) )
for batch in range(cfg.batch_size):
net = forward(input_batch[batch], net)
w_del_batch_tmp, b_del_batch_tmp = backprop_single(net, desired_output_batch[batch])
for layer_num in range(cfg.hidden_layer_num +1):
w_del_batch[layer_num][batch,:,:] = w_del_batch_tmp[layer_num]
b_del_batch[layer_num][batch,:] = b_del_batch_tmp[layer_num]
loss_sclr, loss_vec = loss(net.layers[-1], desired_output_batch[batch])
batch_loss[batch] = loss_sclr
batch_loss = np.mean(batch_loss)
w_delta_mean = deep_copy_mat_list(net.weights, False)
b_delta_mean = deep_copy_mat_list(net.biases, False)
for layer_num in range(cfg.hidden_layer_num +1):
w_delta_mean[layer_num] = np.mean(w_del_batch[layer_num], axis=0) * cfg.learning_rate #learning rate is here!
b_delta_mean[layer_num] = np.mean(b_del_batch[layer_num], axis=0) * cfg.learning_rate
descent_step = w_delta_mean, b_delta_mean
return(descent_step, batch_loss)
We also take the chance to apply the learning rate here. This reduces the step size we take down the gradient to a size within which we hope the direction will still be mostly correct. After finding the suggested changes(descent step), we can pass it up to our highest level training function, which trains over the whole dataset for a number of epochs:
def train(images_pth, labels_pth, cfg:Config):
#the core training loop that trains through epochs.
# requires an images path, labels path(ideally located in the same directory as this code), and cfg containing hyperparameters
#plotting stuff
x_data, y_data = [],[]
from IPython.display import clear_output
net = create_network(cfg.input_layer_size, cfg.output_layer_size, cfg.hidden_layer_num, cfg.hidden_layer_size)
for epoch in range(cfg.epochs):
print("epoch ", int(epoch), "out of ", int(cfg.epochs))
f = open(images_pth, 'rb')
f.read(16)
l = open(labels_pth,'rb')
l.read(8)
for index in range(0, cfg.dataset_size, cfg.batch_size):
input_ly, label_ly = create_batch(cfg, f, l)
(W_delta, B_delta), loss = batch_learning(input_ly, label_ly, net,cfg)
for layer_num in range(cfg.hidden_layer_num +1):
net.weights[layer_num] = net.weights[layer_num] + W_delta[layer_num]
net.biases[layer_num] = net.biases[layer_num] + B_delta[layer_num]
#plotting stuff
x_data.append(epoch)
y_data.append(loss)
clear_output(wait=True) # Clear previous plot
plt.figure(figsize=(6, 4))
plt.plot(x_data, y_data, 'bo-')
plt.title("Epoch vs Loss")
plt.xlabel("Epoch")
plt.ylabel("Loss at epoch end")
plt.grid(True)
plt.show()
return(net, (x_data, y_data))
While this loop looks sizable, most of it is just for tracking training progress and file handling. The core learning just moves over batches and epochs, adding the suggested changes calculated earlier in our batch learning function:
(W_delta, B_delta), loss = batch_learning(input_ly, label_ly, net,cfg)for layer_num in range(cfg.hidden_layer_num +1): net.weights[layer_num] = net.weights[layer_num] + W_delta[layer_num] net.biases[layer_num] = net.biases[layer_num] + B_delta[layer_num]
And that’s it! We now just need to create a config set and call the training function. Before we do that, we’ll also write some functions to save training performance and our network weights and biases. I won’t go over this code in depth since it’s nothing special:
def save_weights_biases(net:n_network):#save the weights and biases import pickle from datetime import datetime timestamp = datetime.now().strftime("%m%d%Y_%H%M%S") file_name = f"weights/nn_training_{timestamp}.pkl" with open(file_name, "wb") as f: pickle.dump(net, f) return(timestamp, file_name)def save_performance(x_epoch, y_loss, cfg:Config, timestamp): #save hyperparams and preformance data to a csv import csv #["run ID", "timestamp", "number of hidden layers", "hidden layer size", "LR", "Epochs", "Batch size"] from datetime import datetime #timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") run_id = f"{cfg.hidden_layer_num}{cfg.hidden_layer_size}{cfg.learning_rate}{cfg.epochs}{cfg.batch_size}" data = [run_id, timestamp, cfg.hidden_layer_num, cfg.hidden_layer_size, cfg.learning_rate, cfg.epochs, cfg.batch_size] results_name = 'results.csv' with open(results_name, mode='a', newline='') as file: writer = csv.writer(file) writer.writerow(data) plot_f_name = f"results/{run_id}_{timestamp}_plots.csv" print(type(y_loss)) plots = [[x_epoch],[y_loss]] with open(plot_f_name, mode='w', newline='') as file: writer = csv.writer(file) for index, value in enumerate(x_epoch): writer.writerow([int(x_epoch[index]), (y_loss[index])]) return(run_id, results_name,plot_f_name)
Now to create a config set and call the training function:
image_size = 28**2batch_size = 100dataset_size = 60000hidden_layers = 3hidden_layer_size = 17learning_rate = 0.05epochs = 100images_path = "MNIST/train-images.idx3-ubyte"labels_path = "MNIST/train-labels.idx1-ubyte"cfg = Config(input_layer_size=image_size, output_layer_size=10, hidden_layer_num= hidden_layers, hidden_layer_size = hidden_layer_size, learning_rate=learning_rate, dataset_size=dataset_size, batch_size=batch_size, epochs=epochs )net, (x_epoch, y_loss) = train(images_path, labels_path, cfg=cfg)timestamp, f_name = save_weights_biases(net)run_id, results_f_name, plot_f_name = save_performance(x_epoch,y_loss, cfg=cfg, timestamp=timestamp)
Now that we’ve done all the code, we can go ahead and train the model; we should see an output something like this:

We can see that after 100 epochs, our loss is around 0.1, which means the model will correctly guess most of the time, which is pretty good! Side note: A loss of 0.1 is not necessarily 90%, because loss is not exactly accuracy, but it’s still quite a good result. The model is clearly learning and performs significantly better than a random guess, which means we’ve successfully made a machine learning model that works! It could be better, and we will need to check against a test dataset to ensure the model hasn’t just memorized the training dataset, but overall we can call the project a success. Now we can move on to more useful models like convolutional neural networks and transformers.
Leave a Reply