NeuroSketch
NeuroSketch is a lightweight educational deep learning framework that implements neural networks from first principles. Every stage of training, from forward propagation to backpropagation, is written manually using NumPy.
Here is a demo, comparing with PyTorch:
Features
Layers
- Fully Connected (
Linear) - Sequential model container (
Sequential) - Activation Functions
- ReLU
- LeakyReLU
- Sigmoid
- Tanh
- Softmax
- Swish
- HeavySide
Loss Functions
- MSELoss
- MAELoss
- BinaryCrossentropyLoss
- SparseCategoricalCrossentropyLoss
Optimizers
- SGD
- MOMENTUM
- ADAM
Utilities
DataLoader- Batch createion
- Dataset shuffling
- Optional dropping of incomplete batches
Weight Initialization
- He
- Xavier
- Zero
- Random (Default)
Installation
pip install neurosketch
Quick Example
import numpy as np
from NeuroSketch.engine.nn import Sequential, Linear
from NeuroSketch.engine.act import ReLU, Softmax
from NeuroSketch.losses import SparseCategoricalCrossentropyLoss
from NeuroSketch.optims import ADAM
from NeuroSketch.utils import DataLoader
x = np.random.randn(500, 20)
y = np.random.randint(5, size=500)
loader = DataLoader(x, y, batch_size=32, shuffle=True)
model = Sequential(
Linear(20, 64),
ReLU(),
Linear(64, 5),
Softmax()
)
criterion = SparseCategoricalCrossentropyLoss(model.layers[-1])
optimizer = ADAM(model, lr=1e-3)
for epoch in range(20):
total_loss = 0
for xb, yb in loader:
pred = model(xb)
loss = criterion(pred, yb)
criterion.backward()
optimizer.step()
total_loss += loss
print(f"Epoch {epoch+1}: {total_loss:.4f}")
Model Summary
print(model.summary())
Project Structure
src/
└── NeuroSketch/
│ ├── engine/
│ │ ├── _module.py
│ │ ├── act.py
│ │ └── nn.py
│ ├── losses.py
│ ├── optims.py
│ ├── utils.py
│ └── LICENSE
└──README.md
Framework Design
Forward Pass
Input
│
Model
│
Prediction
│
Loss
Backward Pass
Loss
│
criterion.backward()
│
optimizer.step()
│
*layers.backward()
|
Parameter Update
NeuroSketch follows a modular object-oriented design.
- Layers perform forward propagation and gradient computation.
- Losses compute the initial gradient i.e. of gradient of loss function with respect to the output of the last layer.
- Optimizers drive the complete backpropagation process, and update parameters.
No automatic differentiation or computational graph is used.
Training Flow
The syntax in training process is same for all cases
prediction = model(x_batch)
loss = criterion(prediction, y_batch)
criterion.backward()
optimizer.step()
Model setup:
-
First, import
DataLoaderobject, it is located asneurosketch.utils. Then, load your data asloaded_data = DataLoader(x: numpy.ndarray, y: numpy.ndarray, batch_size=<int>, shuffle=<bool>, drop_last=<bool>)here,batch_size; if None: full-batch, if value <int> given, mini-batch shuffle; if True: shuffles batches every epoch else: doesn't shuffle batches drop_last; if True: drops incomplete batch else: doesn't drop incomplete batch -
Import the
Sequentiallayer contatiner fromneurosketch.engine.nn -
Now, import the
Linearlayer object fromneurosketch.engine.nnand essential activations fromneurosketch.engine.nn.act -
You can define you model in two ways:
model = Sequential( <*layers> )
or
model = Sequential() model.add(layer1) model.add(layer2) model.add(layer3) ... ...
Note: The
Linearlayer requires you to enter two parameterin_featuresandout_featuresbecause shape of linear layer is (in_features x out_features). You can even specify weight initialization for each linear layer. Shape of weight: (out_features x in_feature). -
Now, import required loss from
neurosketch.lossesand required optimizer fromneurosketch.optims. -
To setup optimizer, you should pass entire model
modelinto it, and you can put enter the learning ratelr:optim = <Optimizer>(model: Sequential, lr=1e-3)or, for optimizers like Adam and Momentum, you can also edit the momentum parameterbeta=0.9forMOMENTUM;beta=0.9andgamma=0.999forADAM -
To setup the criterion function, you should pass the last layer of model
model.layers[-1]to define the criterion;criterion = <Loss>(model.layers[-1])and to find the loss, you can do:loss = criterion(pred, label) -
Now, you can iterate through epochs and
loaded_datalike:for epoch in range(epochs): for x_batch, y_batch in loaded_data: ... ...
and use the same trainig flow syntax mentioned above
Working Principle:
model(x_batch)does forward propagation for each layers, caches and intermediate values inside each layer objectcriterion(prediction, y_batch)returns the loss valuecritetion.backward()calls the.backward()of the loss function, this calculates gradient of loss with respect to output of modelprediction, this gets cached asgrad_nextof the last layer of the model, which is passed into the loss object during criterion definationcriterion = <Loss>(model.layers[-1])- Optimizer does backward pass to every layer of model from last layer, from what it caches the chained gradient upto previous layer as
grad_nextin the current layer by calling each layer's.backward(next_grad) - Then the optimizer filters updatable layer
Linearwhich has parametersdWanddB, fetches those and updates the parameters of all linear layers.
Requirements
- Python 3.7+
- NumPy
License
MIT License.
Release files for NeuroSketch 0.1.6
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| neurosketch-0.1.6.tar.gz | 11.1 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| neurosketch-0.1.6-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 21.2 kB
Release files / neurosketch-0.1.6.tar.gz
| Download URL | neurosketch-0.1.6.tar.gz |
|---|---|
| Size | 11.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
008f7b66cb7fab9c65654418b7bf468225426addb05c4aad9f014e1383d5c642
|
|
BLAKE2b-256 checksum How to use checksums |
c0dc22be9b81dfbeb892123486e8a81e61c2b087b15b99c1eada82422e5dcd1b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.14.4
|
Release files / neurosketch-0.1.6-py3-none-any.whl
| Download URL | neurosketch-0.1.6-py3-none-any.whl |
|---|---|
| Size | 10.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
eea16cf35aeebc05e30ced964ca1182cf0ce4e36dc4b928308510a4c9bf06a77
|
|
BLAKE2b-256 checksum How to use checksums |
3faf630be5bd0bb53c632a8c27720a1488de8eb430550b8664746e580e87ac3c
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.14.4
|