Skip to main content

neuralkit

Python 3.8+ License: MIT Version Zero Dependencies

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

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:

  1. DataLoader generates mini-batches.
  2. Sequential.forward(x_batch) cascades activations through stacked Layer objects.
  3. LossFunction.forward(pred, y_batch) evaluates scalar loss + penalty from Regularizer.
  4. LossFunction.backward() computes initial upstream gradient $\frac{\partial L}{\partial y}$.
  5. Sequential.backward(grad) propagates gradients via chain rule across all layers.
  6. 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.json stores layer types, dimensions, and activation metadata.
  • weights.npz stores 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:

  1. Fork the repository.
  2. Create a feature branch (git checkout -b feature/amazing-feature).
  3. Add tests in tests/ for any new functionality.
  4. Ensure all tests pass: python -m unittest discover tests.
  5. 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

neuralkit-0.2.0.tar.gz (45.9 kB view details)

Uploaded Source

Built Distribution

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

neuralkit-0.2.0-py3-none-any.whl (45.8 kB view details)

Uploaded Python 3

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

Hashes for neuralkit-0.2.0.tar.gz
Algorithm Hash digest
SHA256 34f99e1273d4229ed76d0c8ddc9447280afd5c6f253703140da2219e86e6af10
MD5 6bbb9e10f4b65fe1811804745bd54e75
BLAKE2b-256 7cc0b1c71d418996d15ab98b1da5123c1db7f2714a84b286dc4fbed0acf2a2e1

See more details on using hashes here.

Provenance

The following attestation bundles were made for neuralkit-0.2.0.tar.gz:

Publisher: publish.yml on 14k5hy4/neuralkit

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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

Hashes for neuralkit-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 9e85281b8cdb967c7591bfceccf32ae6c232d5c92d4a51ab1e6c93466e786fb0
MD5 d8a098a1abf8918a10e192082717b3a1
BLAKE2b-256 c977f59f6969264b8be7fa6179bf2fb85998d6d983d45b6224d90f132ab28b58

See more details on using hashes here.

Provenance

The following attestation bundles were made for neuralkit-0.2.0-py3-none-any.whl:

Publisher: publish.yml on 14k5hy4/neuralkit

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

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