Skip to main content

A lightweight educational neural network library

Project description

QuackNet

A pure Python deep learning library built entirely from scratch, designed for educational insight and hands-on experimentation with neural networks and CNNs without using TensorFlow or PyTorch.

QuackNet is a Python-based library for building and training neural networks and convolutional networks entirely from scratch. It offers foundational implementations of key components such as forward propagation, backpropagation and optimisation algorithms, without relying on machine learning frameworks like TensorFlow or PyTorch.

Latest release: PyPI version Docs License: MIT

Table of Contents

Installation

QuackNet is simple to install via PyPI.

Install via PyPI

pip install QuackNet

Quick Start

from quacknet.main import Network

n = Network(lossFunc="Cross Entropy", learningRate=0.01, optimisationFunc="SGD")
n.addLayer(5, "ReLU")
n.addLayer(3, "SoftMax")
n.createWeightsAndBiases()

inputData = [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]]
labels = [[1], [0]]

accuracy, averageLoss = n.train(inputData, labels, epochs=5)

For more detailed examples, see Advanced Usage or Examples

Benchmark

Performance Comparison: QuackNet vs PyTorch & TensorFlow

The library was benchmarked on the MNIST dataset against PyTorch and TensorFlow using identical architectures and hyperparameters to ensure fair comparison.

  • Neural Network Model Architecture: 784 (input) → 128 → 64 → 10 (output)
  • Activation Function: Leaky ReLU for input and hidden layers, and SoftMax for output layer
  • Optimiser: Gradient Descent with Batches
  • Batch Size: 64
  • Learning rate: 0.01
  • Epochs 10

Below is the graph showing the training accuracy and loss over 10 epochs, for the three ML frameworks.

Training Accuracy & Loss for the 3 frameworks

Framework Accuracy Loss
QuackNet 96.26% 0.127
PyTorch 93.58% 0.223
TensorFlow 94.88% 0.175

Note: Due to differences in weight initialisation, dataset shuffling, and internal batch handling, QuackNet occasionally performs slightly better in this specific benchmark. Results may vary across runs.

code:

  • The code for the QuackNet benchmark can be found here
  • The code for the PyTorch benchmark can be found here
  • The code for the TensorFlow benchmark can be found here

QuackNet benchmark on MNIST

The code for this benchmark can be found is the same as the one used to benchmark against PyTorch and TensorFlow.

Below is the graph showing the training accuracy and loss over 10 epochs, across 5 runs:

QuackNet Training Accuracy & Loss over 10 Epochs for 5 runs

Why this Library?

QuackNet was created to deepen my understanding of how neural networks work internally. Unlike high-level frameworks, it shows the mechanisms of forward and backward propagation, gradient computation, and weight gradients. Offering a highly educational and customisable platform for learning and experimentation.

Learning Outcomes

Building QuackNet from scratch enabled mastery of:

Core Concepts: 1. Backpropagation - Derived and implemented gradient calculations for dense and convolutional layers 2. Optimiser Internals - Coded Stochastic Gradient Descent and Adam 3. CNN Operations - Implemented kernels, padding, strides, and pooling 4. Data Handling - Used vectorisation (NumPy) to make code more performant - Designed preprocessing (normalisation -> augmentation -> batching)

CS Skills: 1. Testing Rigor - Unit test coverage >80% - Unit test are used to ensure reliability of components 2. API Design - Created easy interface (e.g., Network.addLayer()) for educational use 3. Documentation - Used pdoc to create automated documentation - Private functions are marked with a '_' at the start - All functions have docstrings showing their args/params

Key Features

1. Custom Implementation:

  • Implemented from scratch layers, activation functions and loss functions.
  • No reliance on external libraries for machine learning (except for numpy)

2. Core Functionality:

  • Support for common activation functions (e.g. Leaky ReLU, Sigmoid, SoftMax)
  • Multiple loss functions with derivatives (e.g. MSE, MAE, Cross Entropy)
  • Optimisers: Gradient Descent, Stochastic Gradient Descent (SGD), and Adam.
  • Supports batching for efficient training.

3. Layer Support:

  • Fully Connected Layer (Dense)
  • Convolutional
  • Pooling (Max and Average)
  • Global Average Pooling
  • Activation Layers

4. Additional Features:

  • Save and load model weights and biases.
  • Evaluation metrics such as accuracy and loss.
  • Visualisation tools for training progress.
  • Demo projects like MNIST and HAM10000 classification.

Highlights

  • Custom Architectures: Define and train neural networks with fully customisable architectures
  • Optimisation Algorithms: Includes Gradient Descent, Stochastic Gradient Descent and Adam optimiser for efficient training
  • Loss and Activation Functions: Prebuilt support for common loss and activation functions with the option to make your own
  • Layer Support:
    • Fully Connected (Dense)
    • Convolutional
    • Pooling (Max and Average)
    • Global Average Pooling
    • Activation layer
  • Evaluation Tools: Includes metrics for model evaluation such as accuracy and loss
  • Save and Load: Save weights and biases for reuse for further training
  • Demo Projects: Includes example implementations such as MNIST digit classification

Advanced Usage

Here is an example of how to create and train a simple neural network using the library:

from quacknet.main import Network

# Define a neural network architecture
n = Network(
    lossFunc = "Cross Entropy",
    learningRate = 0.01,
    optimisationFunc = "SGD", # Stochastic Gradient Descent
)
n.addLayer(3) # Input layer
n.addLayer(2, "ReLU") # Hidden layer
n.addLayer(1, "SoftMax") # Output layer
n.createWeightsAndBiases()

# Train the network
accuracy, averageLoss = n.train(mnist_images, mnist_labels, epochs = 10)

# Evaluate
print(f"Accuracy: {accuracy}%")
print(f"Average loss: {averageLoss}")

Note: This example assumes input and labels are preprocessed as NumPy arrays. You can use this script to download and save MNIST images using torchvision.

Examples

Roadmap

  • Forward propagation Implemented the feed forward pass for neural network layers
  • Activation functions Added support for Leaky ReLU, Sigmoid, SoftMax, and others
  • Loss functions Implemented MSE, MAE, and Cross Entropy loss with their derivatives
  • Backpropagation Completed backpropagation for gradient calculation and parameter updates
  • Optimisers Added support for batching, stochastic gradient descent and gradient descent
  • Convolutional Neural Network Implemented kernels, pooling and dense layers for Convolutional Neural Network
  • Visualisation tools
    Added support for visualising training, such as loss and accuracy graphs
  • Benchmark against PyTorch/TensorFlow Benchmark against popular machine learning frameworks on MNIST dataset
  • Add Adam optimiser
    Implement the Adam optimiser to improve training performance and convergence
  • Data augmentation Add data augmentation such as flipping, rotation and cropping
  • Input Data augmentation: Add pixel normalisation of pixels and one-hot encoded label
  • Skin Lesion detector
    Use the neural network library to create a model for detecting skin lesions using HAM10000 for skin lesion images
  • Additional activation functions
    Implement advanced activation functions (eg. GELU and Swish)

Unit Tests

QuackNet includes unit tests that ensures the reliability of QuackNet's neural and convolutional components. They help to confirm that all layers and training processes behave as expected after every major update to ensure structural stability of all components. The tests are organised into two directories:

These tests cover:

  • Forward and backward propagation for both neural networks and convolutional neural networks.
  • CNN specific layers: Dense, Convolutional, Pooling
  • Activation functions and loss functions, including their derivatives
  • Optimisation algorithms: SGD, GD, Adam

To run the tests:

pytest

To check test coverage:

coverage run -m pytest
coverage report -m

Related Projects

Skin Lesion Detector

A convolutional neural network (CNN) skin lesion classification model built with QuackNet, trained using the HAM10000 dataset. This model achieved 60.2% accuracy on a balanced validation set of skin lesion images.

You can explore the full project here: Skin Lesion Detector Repository

This project demonstrates how QuackNet can be applied to real-world image classification tasks.

Project Architecture

Neural Network Class

  • Purpose Handles fully connected layers for standard neural network
  • Key Components:
    • Layers: Dense Layer
    • Functions: Forward propagation, backpropagation
    • Optimisers: SGD, GD, GD using batching

Convolutional Neural Network Class

  • Purpose Specialised for image data processing using convolutional layers
  • Key Components:
    • Layers: Convolutional, pooling, dense and activation layers
    • Functions: Forward propagation, backpropagation, flattening, global average pooling
    • Optimisers: Adam optimiser, SGD, GD, GD using batching

License

This project is licensed under the MIT License - see the LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

quacknet-1.0.tar.gz (22.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

quacknet-1.0-py3-none-any.whl (29.2 kB view details)

Uploaded Python 3

File details

Details for the file quacknet-1.0.tar.gz.

File metadata

  • Download URL: quacknet-1.0.tar.gz
  • Upload date:
  • Size: 22.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.1

File hashes

Hashes for quacknet-1.0.tar.gz
Algorithm Hash digest
SHA256 91434164c348596d8c9b5a69ee17b81f3fd15ee3ff8e7f59c1c2a6a3ad0670ad
MD5 c5bdc01605d4dbfacdadc3ae04f97829
BLAKE2b-256 c7d77f3b4b1d85394aa7e61b667de349c6bb3caf9d30334840385e4814715ec0

See more details on using hashes here.

File details

Details for the file quacknet-1.0-py3-none-any.whl.

File metadata

  • Download URL: quacknet-1.0-py3-none-any.whl
  • Upload date:
  • Size: 29.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.1

File hashes

Hashes for quacknet-1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 96ffde70883514ded0d00b04f6cd4f2c5e015723bf29316b31dde3b48eeb9b88
MD5 315a1bbfa5de581368edc4b7ea590cf6
BLAKE2b-256 8684df7d08b8a1a0de03dd1f1b5e5e56e0f4df709b56c7267e78d48c460783d5

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page