Skip to main content

A minimal neural network framework with autodiff and NumPy

Project description

nnetflow

A minimal neural network framework with autodiff, inspired by micrograd and pytorch.

Installation

pip install nnetflow

Usage

from nnetflow.nn import MLP, SGD, MSELoss from nnetflow.engine import Tensor

model = MLP(nin=3, nouts=[8, 2])

example

import numpy as np
from sklearn.datasets import make_regression
from nnetflow.nn import MLP, SGD, MSELoss
from nnetflow.engine import Tensor

X, Y = make_regression(n_samples=100, n_features=3, n_targets=2, noise=0.1, random_state=42)


data = []
for x, y in zip(X, Y):
    x_tensors = [Tensor([float(val)]) for val in x]
    y_tensors = [Tensor([float(val)]) for val in y]
    data.append((x_tensors, y_tensors))

model = MLP(nin=3, nouts=[8, 2])

loss_fn = MSELoss()
optimizer = SGD(model.parameters(), lr=0.001)

for epoch in range(200):
    total_loss = 0.0
    for x, y_true in data:
        y_pred = model(x)
        if not isinstance(y_pred, list):
            y_pred = [y_pred]
        loss = loss_fn(y_pred, y_true)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        total_loss += loss.data.item()
    if (epoch+1) % 10 == 0 or epoch == 0:
        print(f"Epoch {epoch+1}: Loss = {total_loss:.4f}")

param = model.parameters()[0]
orig = param.data.copy()
eps = 1e-4
param.data += eps
plus_loss = 0.0
for x, y_true in data:
    y_pred = model(x)
    if not isinstance(y_pred, list):
        y_pred = [y_pred]
    plus_loss += loss_fn(y_pred, y_true).data.item()
param.data = orig - eps
minus_loss = 0.0
for x, y_true in data:
    y_pred = model(x)
    if not isinstance(y_pred, list):
        y_pred = [y_pred]
    minus_loss += loss_fn(y_pred, y_true).data.item()
param.data = orig
fd_grad = (plus_loss - minus_loss) / (2 * eps)
optimizer.zero_grad()
for x, y_true in data:
    y_pred = model(x)
    if not isinstance(y_pred, list):
        y_pred = [y_pred]
    loss = loss_fn(y_pred, y_true)
    loss.backward()
print(f"Finite diff grad: {fd_grad:.6f}, Backprop grad: {param.grad.flatten()[0]:.6f}")

x_test = [Tensor([float(val)]) for val in X[0]]
y_pred = model(x_test)
print("Prediction:", [p.data for p in y_pred])
print("True:", Y[0])

...

See the docs/ folder for more details.

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

nnetflow-0.2.0.tar.gz (7.8 kB view details)

Uploaded Source

Built Distribution

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

nnetflow-0.2.0-py3-none-any.whl (6.5 kB view details)

Uploaded Python 3

File details

Details for the file nnetflow-0.2.0.tar.gz.

File metadata

  • Download URL: nnetflow-0.2.0.tar.gz
  • Upload date:
  • Size: 7.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.8.18

File hashes

Hashes for nnetflow-0.2.0.tar.gz
Algorithm Hash digest
SHA256 8eae70916fc4a7ed0c6313765bef3346ded90d46cb163d5a49780e77c0952667
MD5 776d89c87ba80a772c9f63a759fc6025
BLAKE2b-256 e996fbb4e60f06a080137b2218bcc6feac6377ac6e495cac88ca62626fc2d7da

See more details on using hashes here.

File details

Details for the file nnetflow-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: nnetflow-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 6.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.8.18

File hashes

Hashes for nnetflow-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ac0eb194c7d87e504f4c6ef792553a525eab5b4371902306d9f9da64d1087fd3
MD5 95bdfdeab22f5a0c68614ec315afcfb5
BLAKE2b-256 c5ea92e4a7858c20eb16dfeebb9caaf7ab48cdf167a7cca5d7a173e0ff6739c7

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