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.1.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.1-py3-none-any.whl (70.6 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: snn_samsit-0.1.1.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.1.tar.gz
Algorithm Hash digest
SHA256 27daa3b944d4e07b183480e0a27c92246008d79b1debd5059ed97e4fd199dd44
MD5 8beedc8cf9b63c7b535929ea3810ba4e
BLAKE2b-256 ae8995520a03e7a5e7a203c3c1f3fb6fe0ba1a2721c805d8267d65913cd6bcb5

See more details on using hashes here.

File details

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

File metadata

  • Download URL: snn_samsit-0.1.1-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.1-py3-none-any.whl
Algorithm Hash digest
SHA256 17363e4a42c17a1af4430113eaecc3c20d9f90e4b74f0177185e343457ac7113
MD5 85fc64ebdf5fab3376a77c3f2f7b9137
BLAKE2b-256 668b9c5d5cd4efabad62e9cd6f85bbd755e769dfd08798da1c83db3453b8d3f6

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