r/learnmachinelearning • • 6d ago

Project I built a neural network from scratch using only NumPy.

Post image

I wanted to know what actually happens inside loss.backward().

So I built a neural network with nothing but NumPy. Every gradient derived on paper, every layer written by hand, every derivative checked numerically.

98.05% on MNIST.

Code and derivations: https://github.com/Meckmin/mnist-numpy-from-scratch

138 Upvotes

12 comments sorted by

33

u/Background-Funny1237 5d ago edited 5d ago

my brother, you are overfitting

edit: val loss has been stagnating for the last 15 epochs while train loss gets lower and lower, this is why it seems like overfitting to me

2

u/Necessary_Guest_4412 5d ago

Thanks for the feedback

2

u/CryptographerOne7003 5d ago

could be, I stared so much at val loss that it tells me nothing anymore.

1

u/Asvp_bmoo 4d ago

Nailed it.

1

u/kbr89 5d ago

A largest relative gradient error below 4e-9 is what makes the 98% believable, and it's more than most from-scratch repos do. A network with one hidden layer lands near 98% on MNIST, so the next things to learn come from changing the problem more than from tuning this one:

  1. Write a tiny autograd next: a value class that records each operation with its local derivative, then walks the graph backwards in topological order. That's what loss.backward() does, and your hand-derived layer gradients become a handful of local rules plus the chain rule. Karpathy's micrograd is small enough to read in one sitting if you want to compare afterwards.
  2. Add a convolution layer using im2col and run the same numerical gradient check on it. Conv backward is where from-scratch versions usually break, mostly on index bookkeeping.
  3. Train the same network on Fashion-MNIST. A plain MLP lands around 88 to 90% there, and initialization, learning rate and regularization start making differences that MNIST mostly hides.

Also, as another commenter pointed out, if the validation loss has flattened while the training loss keeps falling, early stopping or a little weight decay is worth trying before adding capacity.

1

u/Necessary_Guest_4412 5d ago

thank you so much for advices, I noted them all down πŸ™πŸ»

0

u/Exact-Contact-3837 5d ago

How does this have so many likes, I made this post about a month ago and I've just not stopped seeing just more and more "...from scratch" posts on this sub with ridiculous amounts of likes. Reddit is falling bruh

1

u/Asvp_bmoo 4d ago

@article{lecun2010mnist,
title={MNIST handwritten digit database},
author={LeCun, Yann and Cortes, Corinna and Burges, CJ},
journal={ATT Labs [Online]. Available: http://yann.lecun.com/exdb/mnist},
volume={2},
year={2010}
}

Because it’s Lecun.

0

u/Necessary_Guest_4412 5d ago

its a very common project.

0

u/mtbdork 5d ago

Reddit (and social media writ large) is at least 85% bot activity.