
After dipping my toe into machine learning(ML) in the form of building an MNIST handwritten digit classifier from scratch, without using any libraries other than the most excellent and honorable NumPy, I found myself hungry for more. While I don’t plan to continue building historical model architectures from scratch forever(because it takes positively forever), building an initial intuition and developing a deep understanding of ML principles will be critical for developing new architectures in the future, as troubleshooting and intuition are seminal guides for developing novel architectures, where there are no similar architectures to reference and copy from. Towards this end, I decided to develop a convolutional neural network architecture from scratch. Taking this approach will be unnecessarily long and difficult, but I have a reason: This project is to test if I can successfully build novel architectures, and give me a deep understanding of ML core principles. Simply creating a CNN from tutorials would not test my ability to figure things out for myself.
This blog post will cover the process I went through to go from a blank script to a fully functional CNN. It will be split into different parts covering motivation and overall architecture, core implementation, and several lessons and techniques I picked up along the way. This project will also include more best practices for writing clean and readable Python code, although I do not claim to be an expert in writing beautiful code yet.
At this point, before we get into the actual development, it’s worth noting that I will be developing this using a purely logical, intuition-based approach. I will try to avoid using formal math language when possible, and while much of the neural network and its training may rely on advanced math functions, such as Fast Fourier Transforms, these are almost exclusively used only to increase speed. These networks can be built and trained in simple Python code using for loops, but speed can be greatly increased by using math tricks and vectorized expressions to decrease the number of individual operations during training and inference.
Architecture:
Coming from building a 1D fully connected/dense neural network, there are a couple of fundamental additions to our understanding that we need to implement in order to build a CNN:
- 2D layers
- 2D layers
- Joining layers which go from 1D to 2D and vice versa
- Convolutional layers
- Convolutions
- The principle of depth
- Pooling
While all of these things are simple individually, we’ll soon find that implementing them all together in a neural network is several orders of magnitude more complex than a simple 1D dense network. For my first project, I created a simple network class which included a configurable number of dense hidden layers. This approach was simple and worked well for a 1D fully connected network, but is not the most flexible for more complex architectures. For our 2D convolutional network, I wanted to add several features which should make for a more modular, flexible, and powerful network:
- Monolithic architecture -> dynamically created networks using .yaml config files
- Identical layers -> unique blocks of different shapes and sizes
- ML functions defined at high level -> ML functions defined in each block class
These changes were driven in part because they allow us to have more complex interactions between dissimilar blocks: An effective convolutional network will need, at a minimum: Fully connected layers, convolutional blocks, and pooling blocks. The connections between these types of blocks depend on the block types. A fully connected block, for example, is connected and functions differently depending on whether it’s connected to another fully connected block, or a pooling or convolutional block.
So we need different types of layers/blocks, which possess unique qualities and functions, while also presenting a common interface for use with the model class and its training and inference functions. There are many ways to do this, but here’s how I went about it:
I created network and block classes, where each block class has some common attributes and functions that the higher-level network can blindly access:
Block Attributes:
- Activations: The neuron activations in each layer. This will always be a numpy ndarray, but the shape and number of dimensions can change.
- Z-values: The pre-activation function values for neurons in each layer. This will always be a numpy ndarray, but the shape and number of dimensions can change.
Block Methods:
- Forward: The forward function for each layer. This function will work differently for each layer, but can be called the same way, using the same arguments.
- Backprop: Similar to the forward function, this function will work differently for each layer, but can be called the same way, using the same arguments.
Blocks may also have many unique attributes which are used internally and may be called by higher functions in some cases, although not always. Because we may want to call these unique attributes in higher-level functions, we also need to have some way of knowing what type of block is at a given index in the neural network, so I added a simple tag to each block, identifying its type. This seems like an obvious step, but it’s important to include: it’s possible to build a network that works without it, but it leads to far more complexity and less flexibility.
Core Code:
Before we get into it, I’m simply going to go over code snippets here rather than going through each line of code, but the full code is always available on GitHub, although it may be an updated or more performant version, as there’s a bunch of things I plan to add/refine to this project.
Config files and handling:
In my first model, I just put everything in one file and had a(mostly) static architecture. For this Convolutional network, I wanted to use a more dynamic and flexible approach, both because useful convolutional networks often have unique shapes, and because it’s a good practice which will lead to more flexible code. To achieve this, I decided to use OmegaConf to import .yaml files as DictConfig classes which could be used throughout the model:
model.yaml
- Contains a complete model architecture based around blocks
- A block includes all the info needed to produce the architecture for that block, such as: Name, type, shape, flags, etc.
- Beyond common attributes such as name and type, some blocks have additional info such as stride and kernel shape for convolutional blocks.
hyper_params.yaml
- Contains all the info related to how any model should be trained, such as learning rate and batch size.
- Also contains info about the dataset, such as number of training examples, image size, and file paths.
These files are imported into a DictConfig, which is a structured config object that makes accessing nested information easier. All this combines to make loading and training a model a simple process:
mdl_cfg = OmegaConf.load("model.yaml")lrn_cfg = OmegaConf.load("hyper_params.yaml")model = NN.create_network(mdl_cfg)results = train(lrn_cfg, mdl_cfg, model)
This approach is very similar to config management frameworks such as hydra, but without the CLI argument functionality. It allows for simple and fast edits to architecture and training parameters, while leaving the core code loop fairly clean.
NN(Neural Network) class:
The neural network class is the core of the network structure and fairly simple. It is primarily just a list of blocks. It contains three major methods:
- create_network
- forward
- backprop
These methods are very simple, do what they say, and mostly just contain the conditional logic for handling how layers of different types are connected and, in the case of forward and backprop, calls to the functions of the same names in each block. Since the network is basically just a list, it’s very easy to loop through it and call a function on each block:
class NN: def __init__(self, config:DictConfig, blocks: list): self.config = config self.blocks = blocks def forward(self, input_ly): self.blocks[0].activations = input_ly self.blocks[0].z_values = input_ly for index in range(len(self.blocks)): #print("\nindex: ", index) if index == 0: self.blocks[0].activations = input_ly else: self.blocks[index].forward(self.blocks[index-1].activations)
In the future, I’m planning to rework the code so that the network class contains more functions as methods, but I was still coming to understand the way object-oriented programming works in Python when I initially wrote the code, so the code is more function-centered.
Block classes:
Where the network class is the architectural core of the model, the block classes are the functional core. Each block type may function differently, so on top of the code to create them dynamically at runtime, each block type also needs to contain the forward and backwards(backprop) methods. These unique-to-block-type methods are also where most of the complex linear algebra happens in the model; for example, the forward and backprop methods for the convolutional block are as follows:
def forward(self, input:np.ndarray): self.z_values = np.zeros(shape=(self.num_filters, *self.layer_shape), dtype=np.float32) self.activations = np.zeros(shape=(self.num_filters, *self.layer_shape), dtype=np.float32) if len(input.shape) == 2: input = np.expand_dims(input, axis=0) for m in range(self.filters.shape[1]): for h in range(self.filters.shape[0]): self.z_values[m,:,:] += convolve(input[h,:,:], self.filters[h,m,:,:], conv_mode="valid") self.z_values[m,:,:] += self.biases[m] self.activations = LeakyReLU(self.z_values) self.activations, self.z_values, clip_warns = clip_activations(self.activations, self.z_values) if clip_warns: logging.warning(f"activations clip warning: {clip_warns} at layer {self.index}")def backprop(self, prior_activations:np.ndarray=None, prior_z_vals:np.ndarray=None, del_l:np.ndarray=None, expected:np.ndarray=None): self.W_delta = np.zeros_like(self.filters, dtype=np.float32) self.B_delta = np.zeros_like(self.biases, dtype=np.float32) if len(prior_z_vals.shape) == 2: prior_z_vals = np.expand_dims(prior_z_vals, axis=0) if len(prior_activations.shape) == 2: prior_activations = np.expand_dims(prior_activations, axis=0) prior_z_prime = LeakyReLU_prime(prior_z_vals) neg1_error = np.zeros_like(prior_z_vals) self.B_delta = np.sum(del_l, axis=(1, 2)) for m in range(self.filters.shape[1]): for h in range(self.filters.shape[0]): kernel = self.filters[h, m] flipped_kernel = np.flip(kernel, axis=(0, 1)) back = scisig.correlate2d(del_l[m], flipped_kernel, mode="full") trimmed = back[1:-1, 1:-1] neg1_error[h] += trimmed self.W_delta[h,m,:,:] = scisig.convolve2d(prior_activations[h,:,:], del_l[m,:,:], mode="valid") del_l_neg1 = neg1_error * prior_z_prime return(del_l_neg1, self.W_delta, self.B_delta)
I’ll go over this code and the associated linear algebra in more detail later, but for now we can see that it’s going to be unique to each block type. Speaking of block types, where in my first 1D fully connected neural network we just had one type, we now have a gaggle of them:
- Input block
- FC(fully connected)
- FC_CONV block
- Conv(convolutional)
- Pooling
These are mostly what you would expect, with the exception of the FC_CONV block, which is just a fully connected block that is set up a little differently to be able to connect to each individual feature map in a convolutional layer, rather than a flat 2D layer.
Convolution function:
The convolution function is the core of what makes convolutional neural networks work so well for visual tasks. In broad terms, it determines each pixel/neuron in the next layer by looking at a local subset of pixels in the prior layer, multiplying them by a set of weights that’s the same size as the subset. This can be a bit confusing to talk through, but a visual can help:

This idea of convolutions means that for a given layer-layer interaction, we only need to have a small kernel(also called a filter) to feed values between the layers. This kernel will be some small size like 5×5 or 3×3. That means that the number of weights we need to deal with goes from the dimensions of the layers multiplied together to just the kernel dimensions multiplied with the number of kernels (depth). For our example of two 28×28 2D layers, that means the weights(W) for fully connected and convolutional types are:
Fully Connected:
Convolutional:
Where:
l1x, l1y are the previous layer dimensions.
l2x, l2y are the next layer dimensions.
kx, ky are the kernel dimensions, and n is the depth(number of unique kernels).
This really displays why CNNs are so much more effective over a dense(fully connected) network for vision tasks. The number of weights we need to do useful computations can be reduced by several orders of magnitude.
For computer vision, what we’re doing doesn’t quite fit the strict mathematical definitions of a convolution, but it’s close enough that we can still use convolution functions to do most of the work, with some tricks before/after to format the data. This is important, because being able to use mathematical convolution functions will reduce the computational load on the network by an order of magnitude. For an in-depth look at why, please see 3Blue1Brown‘s excellent video on convolutions. For our use case, we’re going to skip over much of the pure math and focus on some gotchas and good practices for implementing convolutions in our code:
Padding function:
The padding function just adds zeros or copied pixels to the edges of a layer, returning a layer with slightly larger dimensions. This function is good to have so that a convolution pass can go to the very edge of a layer if needed.
Pooling function:
We use pooling to reduce the x-y size of layers. Pooling essentially works by running some mathematical function over a layer and outputting the results to a new layer. The function used for our case is usually max pool: Where we’re only interested in the most extreme values(because they are most likely to be carrying useful information), so we keep the maximum value from each set of tiles and get rid of the rest.
Batch backprop function:
This function handles much of the heavy lifting for training the model. While each layer type has its own internal method for the forward pass and backpropagation, this function handles batching data, calling the forward pass and backprop methods, and tracking the mean change to the weights and biases.
Training function:
The training function simply calls batch backprop over a set number of epochs taken from a hyperparameter config file. While simple in theory, this function also has to track a number of housekeeping tasks, such as data handling, updating weights and biases, logging, importing and exporting weights and performance data, and starting and communicating with the monitoring server. I also built it to save the weights and performance data periodically while training is ongoing so a power outage can’t ruin a long training run. This also enables us to end training early and pause and restart training if needed.
Save performance class:
Saving model performance, not just the weights and biases, is easy to overlook but is essential in making debugging easier. Things like total loss, gradient max and mins, and changes to the weights are all useful tools for debugging the model, and saving them while the training was in progress saved me a lot of headache in the debugging stage.
Save weights class:
Save weights is pretty self-explanatory, with the small added feature that it acts as an independent class which contains the weights separately from the model trainer.
A server script to monitor training:
For new models where we’re not just using an off-the-shelf model with our data, I believe that visibility into the model is as important as performance. Writing code that enables quick debugging should be as much of a focus as writing the model itself. Without this visibility, it’s all too easy to spend weeks wondering where the problem in a model is, and spend whole training runs waiting for results that we could know were bad within the first epoch. One good way to avoid wasting that effort is through testing everything on a small scale, with simple implementation first. Another critical piece is to have the ability to watch training in real time and pause to debug or make changes. To make this possible, I created a web server that displays a live dashboard of the training progress, including loss, activations, dW, and dB. To make sure the server ran reliably and could update while the training loop was busy, I used Python’s threading library to run the server on a parallel thread, which accesses training run data through shared dictionaries:
shared_dict = { 'epoch': 0, 'loss': 0.0, 'log' : [], 'etc.': [], }import threadingthreading.Thread(target=server.start_dashboard_server, args=(shared_dict,), daemon=True).start()
Now we have a board to monitor training, and we can change what is displayed based on what we need. Here’s a sample output from the server:

Now, the only thing left to do is run and debug! I didn’t document as much as I should have in this step, but I worked through a couple of different bugs, including some typos in the code, which led to loss not being passed back correctly, exploding gradients, and an odd bug where improperly using a “valid” convolution rather than “full” resulted in a 1×1 being broadcast into a 9×9 filter, rather than a 9×9 into a 9×9 filter. Here’s a picture from training before the bug fix:

And after the fix:

This is a great example of why you should always check the scale on a graph! The buggy model is still clearly learning, and the shape of the graph looks good, but loss is still very high at the end of training. After the fix, the graph might look similar, but we can see immediately that loss is much lower, even after 5 epochs. Now that we’re confident the model is training as intended, we can do a full 50-epoch run and evaluate on our test dataset:

That’s a pretty perfect hockey stick, and a loss of less than .1 should be good. But let’s check a couple of examples, and then evaluate the model against the full test dataset to make sure we haven’t overtrained:



Image key: 4
Network’s guess: 4
[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
Image key: 9
Network’s guess: 9
[0. 0. 0. 0. 0. 0. 0. 0.0007 0. 0.9992]
Image key: 6
Network’s guess: 5
[0. 0.0003 0. 0. 0. 0.7346 0.265 0. 0. 0. ]
Here we can see that the model guesses correctly with a high degree of confidence most of the time, but when it guesses wrong, its confidence is generally lower, and in most cases, it’s hard to blame the model: That “6” barely looks like a number at all. Just to be sure, let’s check it against the full test dataset:
num_correct = 0for choice in range(len(test_images)): trained_model.forward(test_images[choice]) if np.argmax(trained_model.blocks[-1].activations) == test_labels[choice]: num_correct = num_correct + 1print(f" num samples:{len(test_images)}, num correct:{num_correct}")print(f"overall accuracy:{num_correct/len(test_images)}")
output: num samples:10000, num correct:9796 overall accuracy:0.9796
An overall accuracy of 97% is pretty good! I’ll do another post about lessons learned and things I would do differently in the future, but for now I’m more than satisfied with this project.

Leave a Reply