neuralkit
A lightweight, zero-dependency neural network framework built strictly from scratch in Python. No PyTorch, no TensorFlow — just NumPy.
Every forward pass, backward pass, gradient computation, parameter update, and initialization strategy is implemented from first principles. If you can build it from scratch, you can debug it, optimize it, and truly understand it.
Table of Contents
- Installation
- Quick Start
- Architecture Overview
- What's Implemented
- Comparison with Other Frameworks
- Documentation
- Contributing
- License
Installation
git clone https://github.com/14k5hy4/neuralkit.git
cd neuralkit
pip install -e .
Core requirement: NumPy (>= 1.20.0).
Optional: Matplotlib (for plotting loss curves, confusion matrices, and decision boundaries).
Quick Start
Train a neural network to solve the non-linear XOR classification problem:
import numpy as np
from neuralkit.model import Sequential
from neuralkit.layers import Dense
from neuralkit.activations import Sigmoid
from neuralkit.losses import MSELoss
from neuralkit.optimizers import SGD
from neuralkit.trainer import Trainer
# XOR dataset
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([[0], [1], [1], [0]])
# Define model architecture
model = Sequential([
Dense(2, 8, activation=Sigmoid()),
Dense(8, 1, activation=Sigmoid()),
])
# Train with full-batch SGD
trainer = Trainer(model, SGD(lr=2.0), MSELoss())
history = trainer.fit(X, y, epochs=3000, verbose=False)
# Inference
predictions = model.predict(X)
print("Predictions:\n", np.round(predictions, 2))
# [[0.02], [0.98], [0.98], [0.02]]
Explore runnable examples in examples/:
Architecture Overview
+-------------------+
| ArrayDataset |
+---------+---------+
|
v
+-------------------+
| DataLoader |
+---------+---------+
| (x_batch, y_batch)
v
+------------------+ +-------------------+ +-------------------+
| Optimizer |<--| Trainer |-->| Loss Function |
| (SGD/Adam/RMS) | +---------+---------+ | (MSE/CrossEnt) |
+--------+---------+ | +---------+---------+
| v |
| +-------------------+ |
+----------->| Sequential |<-----------+
+---------+---------+
|
+---------------+---------------+
| | |
v v v
+------------+ +------------+ +------------+
| Dense #1 | | Dropout | | Dense #2 |
+------------+ +------------+ +------------+
Execution Flow per Iteration:
DataLoadergenerates mini-batches.Sequential.forward(x_batch)cascades activations through stackedLayerobjects.LossFunction.forward(pred, y_batch)evaluates scalar loss + penalty fromRegularizer.LossFunction.backward()computes initial upstream gradient $\frac{\partial L}{\partial y}$.Sequential.backward(grad)propagates gradients via chain rule across all layers.Optimizer.step(layers)updates parameters $\mathbf{W} \leftarrow \mathbf{W} - \eta \cdot \nabla_{\mathbf{W}} L$.
What's Implemented
Layers & Activations
| Module | Description / Formulations |
|---|---|
Dense |
Fully-connected layer: $y = xW + b$. Supports custom weight initializers. |
Dropout |
Inverted dropout — scales active units by $\frac{1}{1-p}$ during training. |
BatchNorm |
Batch normalization (Ioffe & Szegedy, 2015) with learnable $\gamma, \beta$ & running averages. |
Flatten |
Reshapes multi-dimensional tensors to $(N, d_{flat})$. |
ReLU |
Rectified Linear Unit: $f(x) = \max(0, x)$. |
LeakyReLU |
$f(x) = x$ if $x > 0$ else $\alpha x$ with configurable slope. |
ELU |
Exponential Linear Unit: $f(x) = x$ if $x > 0$ else $\alpha(e^x - 1)$. |
Swish |
Self-gated activation: $f(x) = x \cdot \sigma(x)$. |
Sigmoid |
Logistic sigmoid with range clipping to prevent floating-point overflow. |
Tanh |
Hyperbolic tangent activation. |
Softmax |
Numerically stable softmax with log-sum-exp stabilization. |
| Layer Wrappers | ReLULayer, SigmoidLayer, TanhLayer, LeakyReLULayer, ELULayer, SwishLayer. |
Loss Functions & Regularization
| Module | Description |
|---|---|
MSELoss |
Mean Squared Error: $\frac{1}{n} \sum (y - \hat{y})^2$. |
CrossEntropyLoss |
Binary & Categorical Cross-Entropy with probability clipping. |
SoftmaxCrossEntropy |
Fused logit-level softmax cross-entropy ($\nabla z = \frac{p - y}{n}$). |
L1 |
Lasso penalty: $\lambda \sum |
L2 |
Ridge penalty: $\frac{1}{2} \lambda \sum W^2$. |
ElasticNet |
Combined L1/L2 regularization penalty. |
Optimizers & Schedulers
| Module | Features |
|---|---|
SGD |
Stochastic Gradient Descent with Nesterov/standard momentum, weight decay, and gradient clipping. |
Adam |
Adaptive Moment Estimation (Kingma & Ba) with bias-corrected 1st & 2nd moments. |
RMSProp |
Root Mean Square Propagation (Hinton) with uncentered and centered variants. |
| Clipping | All optimizers support clip_value (min/max) and clip_norm (global norm threshold). |
StepLR |
Multiplies learning rate by $\gamma$ every $N$ epochs. |
ExponentialLR |
Exponentially decays LR each epoch. |
CosineAnnealingLR |
Cosine annealing schedule down to $\eta_{min}$. |
ReduceLROnPlateau |
Dynamically drops LR when validation loss plateaus. |
Weight Initialization
| Strategy | Target Activation / Formulation |
|---|---|
he_normal, he_uniform |
Kaiming He init ($std = \sqrt{2 / fan_in}$) for ReLU networks. |
xavier_normal, xavier_uniform |
Glorot init ($std = \sqrt{2 / (fan_in + fan_out)}$) for Sigmoid/Tanh. |
lecun_normal |
LeCun init ($std = \sqrt{1 / fan_in}$) for SELU/linear units. |
zeros, ones, constant |
Deterministic initialization routines. |
Data Pipeline & Cross-Validation
| Class / Function | Capability |
|---|---|
ArrayDataset |
In-memory dataset container for feature matrix & targets. |
DataLoader |
Mini-batching, shuffling, and tail-batch handling (drop_last). |
transforms |
StandardScaler, MinMaxScaler, Normalize, OneHotEncoder, Compose. |
splits |
Stratified and random train_test_split & train_val_test_split. |
cross_validation |
k_fold_split and cross_validate with stratified fold generation. |
Metrics & Evaluation
| Metric | Types Supported |
|---|---|
| Classification | accuracy, precision, recall, f1_score (macro/micro), confusion_matrix, classification_report. |
| Regression | mse, rmse, mae, r2_score. |
Visualization
| Function | Description |
|---|---|
plot_training_history |
Side-by-side epoch curves for training/validation loss and metrics. |
plot_confusion_matrix |
Annotated heatmap matrix of true vs predicted labels. |
plot_decision_boundary |
2D decision boundary contour plot over feature space. |
Model Serialization
Save and reload fully trained model state without re-compiling:
# Save model definition and weights
model.save("saved_models/iris_classifier")
# Reload model
from neuralkit.model import Sequential
model = Sequential.load("saved_models/iris_classifier")
architecture.jsonstores layer types, dimensions, and activation metadata.weights.npzstores binary compressed weight and bias tensors.
Comparison with Other Frameworks
| Feature | neuralkit |
PyTorch | scikit-learn |
|---|---|---|---|
| Dependencies | NumPy only | PyTorch, CUDA, C++ | NumPy, SciPy, Cython |
| Primary Purpose | Educational / First-principles | Production / Research | Classical ML |
| Autograd Engine | Explicit manual backprop | Dynamic computation graph | N/A |
| Code Visibility | 100% readable Python | C++ backend core | C / Cython backends |
| Model Customization | Full transparency | High | Fixed API wrappers |
Documentation
Full guides and detailed API documentation are available in the docs/ directory:
- Getting Started Guide: Detailed walkthrough for building models, using callbacks, metrics, and data pipelines.
- API Reference: Complete signature breakdown for all modules.
Contributing
Contributions are welcome! If you'd like to extend neuralkit:
- Fork the repository.
- Create a feature branch (
git checkout -b feature/amazing-feature). - Add tests in
tests/for any new functionality. - Ensure all tests pass:
python -m unittest discover tests. - Submit a Pull Request.
License
Distributed under the MIT License. See LICENSE for more details.
See CHANGELOG.md for version history.
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file neuralkit-0.2.0.tar.gz.
File metadata
- Download URL: neuralkit-0.2.0.tar.gz
- Upload date:
- Size: 45.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via:
twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
34f99e1273d4229ed76d0c8ddc9447280afd5c6f253703140da2219e86e6af10
|
|
| MD5 |
6bbb9e10f4b65fe1811804745bd54e75
|
|
| BLAKE2b-256 |
7cc0b1c71d418996d15ab98b1da5123c1db7f2714a84b286dc4fbed0acf2a2e1
|
Provenance
The following attestation bundles were made for neuralkit-0.2.0.tar.gz:
Publisher:
publish.yml on 14k5hy4/neuralkit
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
neuralkit-0.2.0.tar.gz -
Subject digest:
34f99e1273d4229ed76d0c8ddc9447280afd5c6f253703140da2219e86e6af10 - Sigstore transparency entry: 2342891879
- Sigstore integration time:
-
Permalink:
14k5hy4/neuralkit@05e604ef1f638fea4cb049378e2da22bf52a54aa -
Branch / Tag:
refs/heads/master - Owner: https://github.com/14k5hy4
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@05e604ef1f638fea4cb049378e2da22bf52a54aa -
Trigger Event:
workflow_dispatch
-
Statement type:
File details
Details for the file neuralkit-0.2.0-py3-none-any.whl.
File metadata
- Download URL: neuralkit-0.2.0-py3-none-any.whl
- Upload date:
- Size: 45.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via:
twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9e85281b8cdb967c7591bfceccf32ae6c232d5c92d4a51ab1e6c93466e786fb0
|
|
| MD5 |
d8a098a1abf8918a10e192082717b3a1
|
|
| BLAKE2b-256 |
c977f59f6969264b8be7fa6179bf2fb85998d6d983d45b6224d90f132ab28b58
|
Provenance
The following attestation bundles were made for neuralkit-0.2.0-py3-none-any.whl:
Publisher:
publish.yml on 14k5hy4/neuralkit
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
neuralkit-0.2.0-py3-none-any.whl -
Subject digest:
9e85281b8cdb967c7591bfceccf32ae6c232d5c92d4a51ab1e6c93466e786fb0 - Sigstore transparency entry: 2342891905
- Sigstore integration time:
-
Permalink:
14k5hy4/neuralkit@05e604ef1f638fea4cb049378e2da22bf52a54aa -
Branch / Tag:
refs/heads/master - Owner: https://github.com/14k5hy4
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@05e604ef1f638fea4cb049378e2da22bf52a54aa -
Trigger Event:
workflow_dispatch
-
Statement type: