-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add expressions, optimizers, and support for MLPs
- Loading branch information
0 parents
commit d5cbd69
Showing
12 changed files
with
1,078 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
__pycache__ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
Copyright © 2024 Parsiad Azimzadeh | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
<p align="center"> | ||
<img alt="micrograd_pp" src="https://raw.githubusercontent.com/parsiad/micrograd-pp/main/logo.png"> | ||
</p> | ||
|
||
<a href="https://github.com/parsiad/micrograd-pp"><img alt="GitHub" src="https://img.shields.io/badge/github-%23121011.svg?logo=github"></a> | ||
|
||
Micrograd++ is a minimalistic wrapper around NumPy which adds support for automatic differentiation. | ||
Designed as a learning tool, Micrograd++ provides an accessible entry point for those interested in understanding automatic differentiation or seeking a clean, educational resource. | ||
Explore backpropagation and deepen your understanding of machine learning with Micrograd++. | ||
|
||
Micrograd++ draws inspiration from Andrej Karpathy's awesome [micrograd](https://github.com/karpathy/micrograd) library, prioritizing simplicity and readability over speed. | ||
Unlike micrograd, which tackles scalar inputs, Micrograd++ supports tensor inputs (specifically, NumPy arrays). | ||
This makes it possible to train larger networks. | ||
|
||
## Usage | ||
|
||
Micrograd++ is not yet pip-able. | ||
Therefore, you will have to clone the Micrograd++ repository to your home directory and include it via the PYTHONPATH in any script or notebook you want to use Micrograd++ in: | ||
|
||
```python | ||
import sys | ||
sys.path.insert(0, os.path.expanduser("~/micrograd-pp/python")) | ||
``` | ||
|
||
## Example: MNIST | ||
|
||
![](https://upload.wikimedia.org/wikipedia/commons/f/f7/MnistExamplesModified.png) | ||
|
||
[MNIST](https://en.wikipedia.org/wiki/MNIST_database) is a dataset of handwritten digits (0-9) commonly used for training and testing image processing systems. | ||
It consists of 28x28 pixel grayscale images, with a total of 60,000 training samples and 10,000 test samples. | ||
It's widely used in machine learning for digit recognition tasks. | ||
|
||
Below is an example of using Micrograd++ to train a simple [feedforward neural network](https://en.wikipedia.org/wiki/Feedforward_neural_network) to recognize digits. | ||
|
||
```python | ||
import micrograd_pp as mpp | ||
import numpy as np | ||
|
||
mnist = mpp.datasets.load_mnist(normalize=True) | ||
train_images, train_labels, test_images, test_labels = mnist | ||
|
||
# Flatten images | ||
train_images = train_images.reshape(-1, 28 * 28) | ||
test_images = test_images.reshape(-1, 28 * 28) | ||
|
||
# Drop extra training examples | ||
trim = train_images.shape[0] % batch_sz | ||
train_images = train_images[: train_images.shape[0] - trim] | ||
|
||
# Shuffle | ||
indices = np.random.permutation(train_images.shape[0]) | ||
train_images = train_images[indices] | ||
train_labels = train_labels[indices] | ||
|
||
# Make batches | ||
n_batches = train_images.shape[0] // batch_sz | ||
train_images = np.split(train_images, n_batches) | ||
train_labels = np.split(train_labels, n_batches) | ||
|
||
# Optimizer | ||
opt = mpp.SGD(lr=0.01) | ||
|
||
# Feedforward neural network | ||
model = mpp.Sequential( | ||
mpp.Linear(28 * 28, 128, bias=False), | ||
mpp.ReLU(), | ||
mpp.Linear(128, 10, bias=False), | ||
) | ||
|
||
# Train | ||
accuracy = float("nan") | ||
for epoch in range(n_epochs): | ||
for batch_index in np.random.permutation(np.arange(n_batches)): | ||
x = mpp.Constant(train_images[batch_index]) | ||
y = train_labels[batch_index] | ||
fx = model(x) | ||
fx_max = fx.max(dim=1) | ||
delta = fx - fx_max.expand(fx.shape) | ||
log_sum_exp = delta.exp().sum(dim=1).log().squeeze() | ||
loss = -(delta[np.arange(batch_sz), y] - log_sum_exp).sum() / batch_sz | ||
loss.backward(opt=opt) | ||
opt.step() | ||
test_x = mpp.Constant(test_images) | ||
test_fx = model(test_x) | ||
pred_labels = np.argmax(test_fx.value, axis=1) | ||
accuracy = (pred_labels == test_labels).mean().item() | ||
print(f"Test accuracy at epoch {epoch}: {accuracy * 100:.2f}%") | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
{ | ||
"extraPaths": ["python"] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
from ._expr import Constant, Expr, Parameter, maximum, relu | ||
from ._nn import Linear, ReLU, Sequential | ||
from ._opt import SGD | ||
|
||
from . import datasets | ||
|
||
__all__ = ( | ||
"Constant", | ||
"Expr", | ||
"Linear", | ||
"Parameter", | ||
"ReLU", | ||
"Sequential", | ||
"SGD", | ||
"datasets", | ||
"maximum", | ||
"relu", | ||
) |
Oops, something went wrong.