neural-net-from-scratch
A tiny neural network library built from scratch in NumPy.
Why does this exist?
I wanted to know how autograd actually works, not just "PyTorch handles it" but how: how the computation graph gets built, how gradients flow backwards, what an optimizer actually does when you call .step(). Best way to learn was to build it myself!
Everything here is pure NumPy. No PyTorch, no JAX, no C extensions. If you want a fast production framework, use PyTorch. If you want to read a few hundred lines of Python that spells out what those frameworks do under the hood, this might be useful.
Installation
Requires Python 3.14+.
Library use (in a project)
uv add neural-net-from-scratch
Or with the demo example included:
uv add "neural-net-from-scratch[examples]"
Try the demo (no project needed)
uvx --from "neural-net-from-scratch[examples]" nn-regression-1d
Note: uvx grabs the package into an ephemeral environment, runs the demo, and cleans up after itself.
Quickstart
Fit a small MLP to y = x² + 1:
import numpy as np
from neural_net.activation import ReLU
from neural_net.layer import Linear
from neural_net.loss_function import Mse
from neural_net.model import Model
from neural_net.node import Node
from neural_net.optimizer import Sgd
class MyModel(Model):
def __init__(self):
self.linear1 = Linear(1, 16, seed=42)
self.relu = ReLU()
self.linear2 = Linear(16, 1, seed=43)
def forward(self, x: Node) -> Node:
return self.linear2(self.relu(self.linear1(x)))
rng = np.random.default_rng(7)
X_train = rng.uniform(0, 1, size=(500, 1))
y_true = X_train**2 + 1 + rng.normal(scale=0.03, size=X_train.shape)
model = MyModel()
model.train(
x_train=X_train,
y_true=y_true,
loss=Mse(),
optimizer=Sgd(model.parameters(), learning_rate=0.04),
num_epochs=2000,
batch_size=40,
shuffle=True,
)
X_test = np.linspace(0, 1, 100).reshape(-1, 1)
y_pred = model.predict(X_test)[0]
That's the whole thing. Subclass Model, define your layers in __init__, wire them together in forward, call .train(...).
Examples
Once you install with the examples extra, you get a CLI demo:
uv run nn-regression-1d
That runs a 3×4 grid of 1D regression fits — three hidden-layer sizes (8, 32, 128) against four optimizers (SGD, Momentum, RMSprop, Adam) — on a non-linear target (sin(2πx) + 0.3·sin(6πx) + x³ + 1.5). Each cell shows the fit and final loss. Source lives at src/neural_net/examples/regression_1d.py if you want to poke at it.
There's also a binary classification demo:
uv run nn-classification-2d
That trains three MLPs (hidden sizes 8, 32, 128) to classify 2D points into a multi-region target — a wavy horizontal stripe plus two isolated islands. Layout is a 2×3 grid: the top row shows training data colored by the model's predicted class, and the bottom row shows the learned probability surface as a heatmap with the true region boundary overlaid as a dashed line. Uses BceWithLogits loss and Adam. Source at src/neural_net/examples/classification_2d.py.
Core concepts
A quick tour of the building blocks:
Node— a NumPy array with autograd metadata attached (who created it, what its parents are, its accumulated gradient, whether it needs one). The autograd graph is a graph of Nodes.Layer— a stateless-ish transformation with aforward()and abackward(). Calling one builds a new Node and hooks it into the graph.LinearandAddlive here.Activation— same as Layer, just semantically for non-parametric nonlinearities.ReLUlives here.LossFunction— takes(y_pred, y_true), returns a scalar Node you can call.backward()on.Mseis included.Optimizer— walks the model's parameters and applies updates.Sgd,Momentum,RMSprop, andAdamare all included. You construct one withmodel.parameters()and pass it totrain().Model— subclass this, drop your layers into__init__, wire them inforward(). Getparameters(),predict(), and a fulltrain()loop for free.
The flow when you train:
- Forward pass through your
Modelbuilds a computation graph ofNodes. - The loss node sits at the root of that graph.
.backward()on the root does a topological sort and walks backwards, accumulating gradients on every Node withrequires_grad=True.- The optimizer applies those gradients to your parameters.
- Repeat.
That's it! No magic layers, no framework internals hiding anything. Read the source in src/neural_net/ and you can trace every step.
License
MIT. See LICENSE.
Metadata
Release files for neural-net-from-scratch 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| neural_net_from_scratch-0.2.0.tar.gz | 48.5 kB | Without provenance | Details for neural_net_from_scratch-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| neural_net_from_scratch-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for neural_net_from_scratch-0.2.0-py3-none-any.whl |
Total release size: 65.8 kB
Release files / neural_net_from_scratch-0.2.0.tar.gz
| Download URL | neural_net_from_scratch-0.2.0.tar.gz |
|---|---|
| Size | 48.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
f8e6a481c16ccd4ebcd1dea8db56ac392ef1cadc44d1f4a1ff37e6986672ad8c
|
|
BLAKE2b-256 checksum How to use checksums |
892958dac7cf89c05997fa2b521001168d6428f085781df78037031b2f7ac256
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.11.2 {"installer":{"name":"uv","version":"0.11.2","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / neural_net_from_scratch-0.2.0-py3-none-any.whl
| Download URL | neural_net_from_scratch-0.2.0-py3-none-any.whl |
|---|---|
| Size | 17.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
f77ac3d627982444007fdc9c051c6824e1cdcf88819305ab27caa0e5d7431ff1
|
|
BLAKE2b-256 checksum How to use checksums |
90cf59fc724ae85ac8455adf63c2e7c1bcdc9a1bb328cd041e64413ed15007e4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.11.2 {"installer":{"name":"uv","version":"0.11.2","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for neural-net-from-scratch 0.2.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.