← All projects

Programming & Computational Methods

Convolutional Neural Network from Scratch

I built a convolutional neural network from scratch that can tell whether a galaxy is elliptical or cigar-shaped.

Year
2025
Context
Data science course assignment, University of Geneva
Assignment by
Yannick Eyholzer
Built with
Python, NumPy

Context

This was a project for a data science class, where we could choose from several projects. I picked this one for two reasons.

First, I wanted to understand convolution. 3Blue1Brown's video on convolution was what first got me interested in it.

Second, I was fascinated by neural networks and how they are now used almost everywhere, and I wanted a real grasp of how they work. Sebastian Lague's video helped me understand neural networks, but it didn't cover convolutional ones. Building one myself seemed like the best way to learn.

It was considered the most demanding project of the class, but since it brought together two things I was already curious about, it felt worth taking on.

The question

Is this galaxy round or elongated? From a small 31 × 31 pixel image, the network has to decide which of the two shapes it is looking at.

A small, round, fuzzy galaxy at the centre of a dark pixelated image.
Elliptical
An elongated, diagonal galaxy in a dark pixelated image.
Cigar-shaped

How it works

The image passes through two convolution layers. The first picks up small local patterns. The second combines them into a single number: how likely the galaxy is to be cigar-shaped.

What I built

Everything is written from scratch in Python and NumPy, without machine-learning libraries:

Backpropagation

The part that took me the longest to understand was backpropagation: not just the steps, but why each one is needed. I worked through the derivation by hand. To send the error back through a layer, you convolve it with the same kernel rotated by 180°.

δl−1 = δpl ∗ rot180(Kl)

Inside the trained network

Before the galaxies, I checked that everything worked on a simpler task: turning each image into its negative. Then I trained networks with one, two and three layers to classify the galaxies, and looked at what they had learned.

A 3 by 3 grid of coloured squares showing the learned first-layer weights.
The first layer learned diagonal features.
A 31 by 31 heatmap, mostly uniform, with a structured pattern near the centre.
The second layer focuses on the centre of the image and captures the overall shape of the galaxy.
A small, compact galaxy labelled true label 0, meaning elliptical.
A miss: an elliptical galaxy predicted as cigar-shaped. The network struggles most with very small galaxies and with images that are genuinely ambiguous.

What I learned

Next time, I would spend more time on the math first and plan the whole structure on paper before writing any code.

Related projects