Skip to main content

Simple Neural Network — a pure-NumPy deep learning library with a Keras-like API

Project description

snn

A neural network / deep learning library built purely on NumPy — no TensorFlow, no PyTorch, no autograd. Every forward pass, backward pass, and weight update is implemented from scratch in vectorized NumPy.


Install

pip install -e .

Or just drop the snn/ folder next to your script and import snn.


Quickstart

from snn.model import Sequential
from snn.layers import Dense, Dropout, BatchNormalization
from snn.utils import to_categorical, train_test_split

# Build a model
model = Sequential([
    Dense(128, activation='relu'),
    BatchNormalization(),
    Dropout(0.3),
    Dense(64, activation='relu'),
    Dense(10, activation='softmax'),
])

# Compile
model.compile(
    optimizer='adam',
    loss='categorical_crossentropy',
    metrics=['accuracy'],
)

# Train
history = model.fit(
    X_train, y_train,
    epochs=20,
    batch_size=64,
    validation_data=(X_val, y_val),
)

# Evaluate
model.evaluate(X_test, y_test)

# Predict
y_pred = model.predict(X_test)

# Save / load weights
model.save_weights('my_weights')
model.load_weights('my_weights')

What's Included

Layers

Layer Description
Dense Fully-connected layer
Conv2D 2D convolution (channels-last)
MaxPooling2D Max pooling
AveragePooling2D Average pooling
GlobalAveragePooling2D Global average pool
GlobalMaxPooling2D Global max pool
BatchNormalization Batch norm (train/inference modes)
LayerNormalization Layer norm
Dropout Inverted dropout
SpatialDropout2D Channel-wise dropout for feature maps
Flatten Flatten to (N, -1)
Reshape Reshape (excluding batch dim)
SimpleRNN Vanilla RNN with BPTT
LSTM Long Short-Term Memory
GRU Gated Recurrent Unit

Activations

linear, relu, leaky_relu, elu, selu, sigmoid, tanh, softmax, softplus, swish, mish

Loss Functions

Loss String key
Mean Squared Error 'mse'
Mean Absolute Error 'mae'
Huber 'huber'
Binary Cross-entropy 'binary_crossentropy'
Categorical Cross-entropy 'categorical_crossentropy'
Sparse Categorical CE 'sparse_categorical_crossentropy'
KL Divergence 'kl_divergence'

Optimizers

Optimizer String key
SGD (+ momentum + Nesterov) 'sgd'
Adam 'adam'
AdamW 'adamw'
RMSprop 'rmsprop'
Adagrad 'adagrad'
Adadelta 'adadelta'

Initializers

zeros, ones, random_normal, random_uniform, glorot_uniform, glorot_normal, he_uniform, he_normal, lecun_uniform, lecun_normal

Metrics

accuracy, binary_accuracy, categorical_accuracy, sparse_categorical_accuracy, top_k_accuracy, precision, recall, f1_score, mse, mae, r2_score, confusion_matrix

Utilities

from snn.utils import (
    to_categorical,        # integer labels → one-hot
    normalize,             # min-max [0,1]
    standardize,           # zero mean, unit variance
    train_test_split,      # split arrays into train/test
    batch_generator,       # mini-batch iterator
    clip_gradients,        # global gradient norm clipping
    learning_rate_schedule,# exponential decay schedule
    cosine_annealing,      # cosine annealing schedule
    warmup_schedule,       # linear warmup + base schedule
    EarlyStopping,         # stop when metric stagnates
    ReduceLROnPlateau,     # reduce LR when metric plateaus
)

Examples

python examples/xor_example.py          # XOR truth table
python examples/classification_example.py  # moons + blobs datasets
python examples/regression_example.py      # sin(x) + polynomial fitting

Architecture

Every layer exposes:

  • forward(x, training=False) — computes the output
  • backward(grad) — computes and stores parameter gradients, returns input gradient
  • params property — dict of trainable arrays
  • grads property — dict of corresponding gradients

The Sequential model wires them together, calls optimizer.apply_gradients(params, grads) after each batch, and supports save_weights / load_weights via np.savez.


Design Principles

  • Pure NumPy — zero deep-learning framework dependencies
  • Vectorized — all operations work on full batches; no Python loops over samples
  • Keras-like API — familiar compile → fit → evaluate → predict interface
  • Explicit gradients — every backward pass is hand-derived, making it a great learning resource

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

snn_samsit-0.1.2.tar.gz (92.7 kB view details)

Uploaded Source

Built Distribution

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

snn_samsit-0.1.2-py3-none-any.whl (70.6 kB view details)

Uploaded Python 3

File details

Details for the file snn_samsit-0.1.2.tar.gz.

File metadata

  • Download URL: snn_samsit-0.1.2.tar.gz
  • Upload date:
  • Size: 92.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for snn_samsit-0.1.2.tar.gz
Algorithm Hash digest
SHA256 69670d44c0a48b2a038facdc1695da332ead1e6edabe61ef5e009de29d590191
MD5 a6361f55c9f447e3538aa649d94dd5e5
BLAKE2b-256 1e2f100fb1f2dec09f1d6c89152fc93914af96e2ba3f04a4eaa130d380424028

See more details on using hashes here.

File details

Details for the file snn_samsit-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: snn_samsit-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 70.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for snn_samsit-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 be5ffd0f2138b3c1bd024ef214d664ec46eff5342bb9c2765ade7ea9356d92f3
MD5 16e761cedaa282478aea346c2c25e8ef
BLAKE2b-256 b577ba762dc45ad2a7e48893780ce746113d0b63239bacde783daf215c4c3132

See more details on using hashes here.

Supported by

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