Skip to main content

Neural Lab

PyPI version Python versions License: MIT

A neural network implementation built as an explicit graph of neurons and weighted connections.

Introduction

Neural Lab represents individual neurons and their connections explicitly. Backpropagation is done using explicitly computed gradients. The object-oriented API consists of Network, Layer, and Neuron constructors. The networks can be easily visualized using a visualization library.

Table of contents

Installation

To use the published package:

python -m pip install neural-lab

How it works

This implementation demonstrates each component of the API. A 3 layer neural network is constructed that has a 4 neuron input Layer and a 1 neuron output layer. The hidden layer has 8 neurons.

Implement a 3 layer neural network

Import the Network, Layer, and Neuron classes.

from neural_lab import Network, Layer, Neuron

Set a step.

step is the learning rate: it controls the size of weight and bias updates. Each update subtracts step times the corresponding gradient. Layer(step=...) supplies an initial default only to neurons whose step is None. Changing layer.step later does not change the neurons; update each neuron.step directly to change its learning rate.

STEP = 0.01

Construct a neural network by specifying the Neurons for each Layer and adding the Layers to a Network.

l1 = Layer(neurons=[Neuron() for i in range(0, 4)], step=STEP)
l2 = Layer(neurons=[Neuron() for i in range(0, 8)], step=STEP)
l3 = Layer(neurons=[Neuron()], step=STEP)
n1 = Network([l1, l2, l3], seed=42)

With the Network defined, you can train the network.

Here the network is trained to recognize the nibble 1111 as the decimal number 15.

n1.train([1,1,1,1], [15])

You can generate and print a prediction using the predict method. Because the network underwent just one iteration of training, the estimate will likely be inaccurate. The accuracy of the prediction can be improved by iteratively training the network. Please see the nibble challenge for an example of how to iteratively train the network.

prediction = n1.predict([1,1,1,1])
print(prediction)

How a neuron learns

Consider the training call from the example above:

n1.train([1, 1, 1, 1], [15])

The four inputs are the bits of 1111; the target output is 15. Here is how this one call changes the network. The excerpts below come from Network and Neuron.

1. Calculate a prediction

train checks that there is one target per output neuron and that every non-input neuron has a finite, positive learning rate (step). It then calls:

self.predict(X_train)

predict checks the inputs and connections, assigns the four input values, and calls activate on each hidden neuron, then the output neuron. Inside Neuron.activate:

total = self.bias
for source, weight in self.weights.items():
    total += source.value * weight
self.value = tanh(total) if self.activation == "tanh" else total

Each neuron adds its bias to the weighted inputs and stores its activation in value. This example uses linear activation, so value is simply total. Hidden neurons can also use tanh.

2. Clear old gradients and calculate the output error

Back in train, gradients from the previous call are cleared before calculating the output gradients:

for layer in self.layers:
    for neuron in layer.neurons:
        neuron.gradient = 0.0
        neuron.delta = 0.0
for neuron, target in zip(self.output_layer.neurons, y_train):
    neuron.gradient = neuron.value - target

The loss is half the sum of squared output errors. A neuron's gradient is the derivative of that loss with respect to its output. For our output neuron, this starts as the prediction minus 15.

3. Propagate gradients backward

train visits the output layer first, then the hidden layers:

for layer in reversed(self.layers[1:]):
    for neuron in layer.neurons:
        neuron.propagate()

Inside Neuron.propagate:

derivative = 1 - self.value ** 2 if self.activation == "tanh" else 1.0
self.delta = self.gradient * derivative
for source, weight in self.weights.items():
    source.gradient += self.delta * weight

delta is the derivative of the loss with respect to the weighted sum plus bias, before activation. For linear activation, the derivative is 1, so delta equals gradient. Each neuron passes a contribution back through each incoming connection. The += lets a source accumulate contributions from every neuron it feeds. Visiting layers in reverse ensures those contributions arrive before the source propagates its own gradient.

4. Update weights and biases

Only after the backward pass finishes does train change the parameters:

for layer in self.layers[1:]:
    for neuron in layer.neurons:
        for source in neuron.weights:
            neuron.weights[source] -= neuron.step * neuron.delta * source.value
        neuron.bias -= neuron.step * neuron.delta

A weight's gradient is delta * source.value; the bias gradient is delta. Subtracting step times each gradient updates the parameters. Waiting until this point means every backward calculation uses the same weights as the forward pass. The next call to predict uses the updated weights and biases.

Each incoming connection has its own weight in neuron.weights[source]. Neuron(bias=...) sets the initial bias, and Network(..., seed=42) initializes weights reproducibly in [-0.1, 0.1]. Connections added later accept an explicit weight; repeated connection calls preserve existing weights.

Explore a trained network

After training, remove a connection and compare predictions to see how it affects the network. This experiment is called an ablation.

Using your trained network as n1:

inputs = [1, 0, 1, 0]
source = n1.layers[1].neurons[0]
receiver = n1.output_layer.neurons[0]
weight = receiver.weights[source]
before = n1.predict(inputs)

source.disconnectRHS(receiver)
after = n1.predict(inputs)
print("Original prediction:", before)
print("Without the connection:", after)

source.connectRHS(receiver, weight=weight)

Try several inputs: a connection's effect can depend on the input.

You can also change an existing weight through receiver.weights[source]. Use the connection methods to add or remove edges so incoming weights and outgoing connections stay consistent.

Examples

The nibble challenge

Setup

Change directory into the example project from the repository root.

cd examples/the_nibble_challenge

Install the example dependencies.

pip install .

Explore the notebook

Open the nibble challenge notebook. It introduces all sixteen four-bit inputs, constructs a 4 → 8 → 1 network, compares initial and trained predictions, and lets you change an input to inspect weights and activations. With seed 42, a step of 0.01, and 10,000 training examples, the displayed R² rounds to 1.000000000.

The network learns a simple linear relationship. Training and evaluation both use all sixteen nibbles; hence, the experiment does not provide evidence of generalization. The notebook imports visualize_network from its visualization module.

Visualizations of the network before and after training

Nibble network before and after training

  • Edge thickness is proportional to the absolute connection weight. Blue is positive; orange is negative. Zero-weight edges have zero width.
  • Node area above a small visibility floor is proportional to absolute activation. Green nodes are inputs, red nodes are hidden, and yellow is the output.
  • Both panels use the same input, positions, and scales. Node size represents activity, not importance, and does not encode the activation's sign.

This visualization demonstrates that an irregular-looking network can learn a simple mapping almost perfectly: individual connections can reinforce or cancel one another.

The digits experiment

Setup

Change directory into the example project from the repository root.

cd examples/the_digits_experiment

Install the example dependencies.

pip install .

Explore the notebook

Open the digits experiment notebook. It starts by displaying the 8×8 digits dataset, then normalizes pixels, creates a training/test split, constructs a 64 → 16 → 10 network, trains, and evaluates unseen images. You can inspect an individual prediction and its ten output scores. Scores are not probabilities.

The reproducible settings use seed 42, 1,347 training images, 450 test images, 20 epochs, and a step of 0.001. The example achieves 90.22% test accuracy, compared with 10.22% for always predicting the most common training digit.

The notebook imports plot_predictions and plot_confusion_matrix from its visualization module.

Digits predictions and confusion matrix

The prediction figure shows the first twelve test images. The confusion matrix includes all 450 test images; rows show the true digit and columns show the predicted digit.

Digits predictions and confusion matrix

Tests

The suite in tests/test.py checks forward calculations, manual gradients, parameter updates, connection removal and restoration, and input validation.

Run all tests.

python -m unittest -v

Documentation maintenance

Regenerating README figures

The documentation-image project has its own dependencies and fixed seed-42 scenarios. From docs/, after following its environment setup:

python generate_images.py

It writes the nibble network image and the combined digits predictions and confusion matrix image to images/.

Support

If you have a feature request or run into any issues, feel free to submit an issue. You’re also welcome to reach out to one of the authors.

Metadata

Release files for neural-lab 0.5.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for neural-lab 0.5.0
File Size Uploaded Provenance Actions
neural_lab-0.5.0.tar.gz 767.2 kB Without provenance Details for neural_lab-0.5.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for neural-lab 0.5.0
File Interpreter ABI Platform Actions
neural_lab-0.5.0-py3-none-any.whl Python 3 none any Details for neural_lab-0.5.0-py3-none-any.whl

Total release size: 776.3 kB

Release files / neural_lab-0.5.0.tar.gz

Download URL neural_lab-0.5.0.tar.gz
Size 767.2 kB
Tags Source
SHA-256 checksum
How to use checksums
adf5765e7c6054506033c7626b1fec98443f27f7718048bbab5e135648146a21
BLAKE2b-256 checksum
How to use checksums
249d59048cd6be9db70407636c3427282414de1b2f7422e6b8c19e16877581a5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via python-httpx/0.28.1

Release files / neural_lab-0.5.0-py3-none-any.whl

Download URL neural_lab-0.5.0-py3-none-any.whl
Size 9.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
fb87f24dc0a186a2528033786085a0b1e2190955b2b3b48d481bde2efdccbce3
BLAKE2b-256 checksum
How to use checksums
505ac5efc41c5c36eb8bd836f2e2e5af98f619883c375ade015f7dbd504adf7f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via python-httpx/0.28.1

Security for neural-lab 0.5.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.5.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page