Skip to main content

nerva-tensorflow

PyPI License: BSL-1.0

nerva-tensorflow is a minimal, transparent implementation of multilayer perceptrons using TensorFlow tensors.
It is part of the Nerva project — a suite of Python and C++ libraries that provide well-specified, inspectable implementations of neural networks.

➡️ All equations in this repository are written in batch (minibatch) matrix form, meaning feedforward, backpropagation, and loss functions operate on minibatches of inputs rather than single examples.

🗺️ Overview

The nerva libraries aim to demystify neural networks by:

  • Providing precise mathematical specifications.
  • Implementing core concepts like backpropagation from scratch.
  • Avoiding automatic differentiation to foster understanding.

Currently supported: Multilayer Perceptrons (MLPs).
Future extensions to convolutional or recurrent networks are possible.


❓ Why Use nerva

If you're learning or teaching how neural networks work, most modern frameworks (e.g., PyTorch, TensorFlow) can be too opaque. nerva is different:

  • Every function has a clear mathematical interpretation.
  • Gradient computations are written by hand — no autograd.
  • Includes symbolic validation to ensure correctness.
  • Modular and backend-agnostic: choose between JAX, NumPy, PyTorch, or TensorFlow.
  • Used as a reference implementation for research and education.
  • Modularity: the core operations rely on a small set of primitive matrix operations, making the logic easy to inspect, test, and validate.

📦 Available Python Packages

Each backend has a dedicated PyPI package and GitHub repository:

Package Backend PyPI GitHub
nerva-jax JAX nerva-jax repo
nerva-numpy NumPy nerva-numpy repo
nerva-tensorflow TensorFlow nerva-tensorflow repo
nerva-torch PyTorch nerva-torch repo
nerva-sympy SymPy nerva-sympy repo

📝 nerva-sympy is intended for validation and testing — it depends on the other four.

See the nerva meta-repo for an overview of all Python and C++ variants.


🚀 Quick Start

Installation

The library can be installed in two ways: from the source repository or from the Python Package Index (PyPI).

# Install from the local repository
pip install .
# Install directly from PyPI
pip install nerva-tensorflow

Example: Define and Train an MLP

# Create a new MLP model
M = MultilayerPerceptron()
M.layers = [
    ActivationLayer(784, 1024, ReLUActivation()),
    ActivationLayer(1024, 512, ReLUActivation()),
    LinearLayer(512, 10)
]
for layer in M.layers:
    layer.set_optimizer("Momentum(0.9)")
    layer.set_weights("XavierNormal")

loss = StableSoftmaxCrossEntropyLossFunction()
learning_rate = ConstantScheduler(0.01)
epochs = 10

# Load data
train_loader, test_loader = create_npz_dataloaders("../data/mnist-flattened.npz", batch_size=100)

# Train the network
stochastic_gradient_descent(M, epochs, loss, learning_rate, train_loader, test_loader)

🧱 Architecture

Each major concept is implemented through clear interface classes. Implementations are modular and easy to replace:

Concept Interface Class Example Implementations
Layer Layer ActivationLayer, LinearLayer
Activation Function ActivationFunction ReLUActivation, SigmoidActivation
Loss Function LossFunction SoftmaxCrossEntropyLossFunction
Optimizer Optimizer GradientDescentOptimizer, MomentumOptimizer
Learning Rate Schedule LearningRateScheduler ConstantScheduler, ExponentialScheduler

🛠 Features

  • Feedforward and backpropagation logic match documented equations exactly.
  • Formulas use batch matrix form, enabling efficient computation over minibatches.
  • Customizable optimizers per parameter group using a composite pattern.
  • Symbolic gradient validation using nerva-sympy.
  • Lightweight command-line interface for experiments.

📚 Documentation

The full documentation is hosted on GitHub Pages:

From there you can access:

Relevant papers:

  1. Nerva: a Truly Sparse Implementation of Neural Networks

    arXiv:2407.17437 Introduces the library and reports sparse training experiments.

  2. Batch Matrix-form Equations and Implementation of Multilayer Perceptrons

    arXiv:2511.11918 Includes mathematical specifications and derivations.


🧪 Training Loop Internals

A mini-batch gradient descent loop with forward, backward, and optimizer steps can be implemented in just a few lines of code:

def stochastic_gradient_descent(M: MultilayerPerceptron,
                                epochs: int,
                                loss: LossFunction,
                                learning_rate: LearningRateScheduler,
                                train_loader: DataLoader):

    for epoch in range(epochs):
        lr = learning_rate(epoch)

        # Iterate over mini-batches X with target T
        for (X, T) in train_loader:
            Y = M.feedforward(X)
            DY = loss.gradient(Y, T) / Y.shape[0]
            M.backpropagate(Y, DY)
            M.optimize(lr)

✅ Symbolic Validation (Softmax Layer Example)

We validate the manually written backpropagation code using symbolic differentiation via SymPy.

This example validates the gradient of the softmax layer. It also illustrates how the gradients DZ, DW, Db and DX of the intermediate variable Z, the weights W, bias b and input X are calculated from the output Y and its gradient DY.

# Backpropagation gradients
DZ = hadamard(Y, DY - row_repeat(diag(Y.T * DY).T, K))
DW = DZ * X.T
Db = rows_sum(DZ)
DX = W.T * DZ

# Symbolic comparison
DW1 = gradient(loss(Y), w)
assert equal_matrices(DW, DW1)

🔢 Implementation via Matrix Operations

The validated backpropagation formulae are implemented directly using the library's core set of primitive matrix operations. This approach provides a significant advantage in clarity and maintainability by expressing all computations from loss functions and activation layers to gradient calculations through a single, global vocabulary of operations.

This stands in contrast to implementations that use hundreds of lines of scattered, special-case logic for the same mathematical result. By reducing complex formulae to a concise sequence of well-defined primitives, the implementation becomes both more readable and far easier to verify and debug.

For a complete reference of all available operations, see the Table of Matrix Operations.


📜 License

Distributed under the Boost Software License 1.0.
License file


🙋 Contributing

Bug reports and contributions are welcome via the GitHub issue tracker.

Metadata

Release files for nerva-tensorflow 1.0.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 nerva-tensorflow 1.0.0
File Size Uploaded Provenance Actions
nerva_tensorflow-1.0.0.tar.gz 34.7 kB Without provenance Details for nerva_tensorflow-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for nerva-tensorflow 1.0.0
File Interpreter ABI Platform Actions
nerva_tensorflow-1.0.0-py3-none-any.whl Python 3 none any Details for nerva_tensorflow-1.0.0-py3-none-any.whl

Total release size: 62.4 kB

Release files / nerva_tensorflow-1.0.0.tar.gz

Download URL nerva_tensorflow-1.0.0.tar.gz
Size 34.7 kB
Tags Source
SHA-256 checksum
How to use checksums
69d429ea8feb7586d74705fa0d2e08205f79e790bcb465bb11e0810fb66aae79
BLAKE2b-256 checksum
How to use checksums
358dd211c5f1eee6dda26b14c2df18bc3b6bcf95120e617edaa9ae92ef0ca250
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.3

Release files / nerva_tensorflow-1.0.0-py3-none-any.whl

Download URL nerva_tensorflow-1.0.0-py3-none-any.whl
Size 27.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c0cded2eaef865a4b2bb77be10a610fd79447a22e2ba982dd56d77dfabf51ad5
BLAKE2b-256 checksum
How to use checksums
881b200c892cf47a81410d8dcf45208d3475340bc5c0a222c9e3248d8e8b1419
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.3

Security for nerva-tensorflow 1.0.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.

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