Giter VIP home page Giter VIP logo

neural-network-with-numpy's Introduction

Recognition of handwritten numbers

GHA workflow badge codecov

Model

Deep Neural network (DNN) implementation with MNIST db from scratch using NumPy. The layout of the network is set to be modular, so you can explore variations of layers and other hyperparameters with it. Regardless of the number of layers, the model will be fully connected so we can call it MLP (Multilayer perceptron). Feel free to tune the model way you like.

Gif demonstrating forward prop in the model with 2 hidden layers [source]

GUI

If you don't wish to explore the training and the modularity of the model, you can test it with the GUI provided with the pre-trained model. There is a simple Tkinter GUI implemented where you can draw your own digits. Those will be inputted to the model and you will be provided with the guess of the model. The implementation is not nearly as good as it could be, but with properly centered drawings, it seems to perform really nicely. The model included will be always the best current version possible. Applying some sort of centering algorithm to the picture would increase the accuracy regardless of the accuracy of the pre-trained model #TODO.

Current model used in GUI: test_data accuracy = 98.16%

Training simple CLI

If you want you can train the model with your own parameters. Follow the instructions, please.

In the training you can choose custom values for these parameter:

  • Number of hidden layers [positive number] ~Exmpl = 3
  • Size of those layers [postive number] ~Exmpl = 256, 128 ,64
  • Learning rate [positive number] ~Exmpl = 0.03
  • Epochs [positive number] ~Exmpl = 10
  • Batch size [positive number] ~Exmpl = 32
  • Activation function [RelU, Sigmoid]

Installing

You need to have Python installed with Poetry to run this application. Clone the repository to your desired path.

# You should use
$ poetry shell

# Install dependencies
$ poetry install

# Run the GUI to test the pre-trained model
$ poetry run invoke startgui

# Download the data to csv format
$ poetry run invoke dowloadmnist

# Run the training cli
$ poetry run invoke train

Docs

Future / Todos

  • Refactor more towards OOP to add more flexibility
  • Add more datasets
  • Add CNN , RNN implementation
  • Evaluate docs such as time and space complexity
  • Refactor loss function / add cross-entropy
  • Add more precision to to gui / deploy the gui as website
  • Add math docs to backprop

neural-network-with-numpy's People

Contributors

juusosaavalainen avatar isakpulkki avatar

Watchers

Kostas Georgiou avatar  avatar

neural-network-with-numpy's Issues

Vertaisarviointi 2

Kloonasin projektin 23.2.2023 klo 8:30.

Sovellus näyttää hyvältä! Valmiiksi treenattua mallia oli hauska kokeilla ja olin yllättynyt siitä, miten hyvin se tunnisti numeroita.

Käyttöohje olisi ollut tarpeen yrittäessäni itse treenata mallia. Asiaan perehtymättömänä oli hankala vastata kysymyksiin kuten "Learning rate / alpha ?" tietämättä, minkälaisia arvoja tähän voisi kokeilla. Implementation-dokumentissa oli kirjoitettu hieman aiheesta, mutta olisi hyvä olla vielä erillinen käyttöohje, jossa selitettäisiin lyhyesti eri parametrien merkitykset.

Koodi on pääsääntöisesti siistiä ja jaettu lyhyisiin metodeihin. Hyvä!

Muutamia pieniä huomioita:

  • Hakemistorakennetta voisi vähän järjestellä uudelleen. Esimerkiksi GUI on nyt model-kansiossa, mielestäni se voisi olla omassa kansiossaan src-kansion alla.
  • Löytyy yksittäisiä funktioita (esim. tämä), jotka ovat pitkiä ja sisältävät paljon kommentteja. Näitä voisi koettaa jakaa pienempiin osasiin selkeyden vuoksi.
  • Polkuja oli paikoin kovakoodattu, esim. täällä. Pythonin os.path-moduulista löytyy tapoja luoda polkuja, joiden pitäisi toimia riippumatta siitä millä käyttöjärjestelmällä ohjelmaa suoritetaan.
  • Tyhjiä rivejä oli monin paikoin enemmän kuin tarvitsisi. Esim. pylintin avulla tällaiset pienet tyylivirheet saa korjattua melko pienellä vaivalla.

Kaikkiaan oikein hyvää työtä, tsemppiä viimeisiin viikkoihin!

Vertaisarviointi

Ladattu: 18.2.2023, 16.25

Hyvältä näyttää! Ohjelma toimii odotetulla tavalla ja hyvin. 98%+ tarkkuus alkaa olemaan jo aika kova! Myös GUI on ollut kiva lisäys projektiin ja antaa käyttäjälle mahdollisuuden visualisoida neuroverkon forwardprop funktiota hyvin.

Muutamia kommentteja tuli mieleen:

  1. Datasetin hoito? Onko datasetin koneelle lataukseen jokin erityinen syy?

Komento:

poetry run invoke dowloadmnist

Ei datasettiä ainakaan itselläni lataa koneelle ja sen seurauksena en saa neuroverkon treenaamista käyntiin. Tensorflowin tf.keras.datasets funktiolla saisi suoraan nätisti datat ohjelman muistiin ja ei tarvitsisi erikseen käyttäjän koneelle latailla suurehkoja tiedostoja.

  1. Projektin arkkitehtuuri on toteutettu hiukan sekavalla tavalla. Mielestäni jakamalla ohjelman luokkiin saataisiin helppolukuisempi lopputulos. Tämä ei tässä tilanteessa kovin isoa työtä vaatisi ja riittäisi vain siirtää nykyiset utility.py funktiot luokan sisään ja tehdä niistä sen luokan metodeja.

  2. Itse koodissa on mielestäni parantamisen varaa. Koodissa on jonkin verran kovakoodattuja osia esim. numero 48000, joka oletettavasti kuvaa training samplesi kokoa esiintyy pariin otteeseen:

mini_batches = [data[j:j + batchsize] for j in range(0, 48000, batchsize)]

Entä jos mallia halutaan treenata eri kokoisella training setillä?

Myös gui.py filussa esiintyy seuraava line:

predictedout = activations[f'A4']

Tekee neuroverkon layerien muuttamisesta hankalaa, sillä tämä viittaa outputlayeriin, mutta olettaa, että output layer on aina samalla indeksillä.

Nämä kovakoodaukset olisi helppo fixata myös tuolla tavalla, että jaat ohjelman luokkiin, niin voit luokan initalisaatiossa spesifioida esim.

NeuralNetwork(..., training_set_size=48000)
# Sitten def __init__ seuraavanlaisesti:
self.training_set_size = training_set_size 
  1. Koodista löytyy useita "turhia" kommentteja, varmaan unohtuneet sinne, mutta vaikeuttaa koodin lukemista. Tässä pari jotka jäi mieleen:
# hardcoded thinks that training will be with whole dataset this will not stay

#######################################################################
# ___________GRADIEN_DESC, ACCURACY, PREDICTS, MONITORING______________#

#############
#  TiraLab  #
#  2023/III #
#  Author:  #
#  Juuso S  #
#           #
#############

Tarvitseeko seuraavan osan myöskään olla itse koodissa? Tämä sopisi enemmän mielestäni dokumentaation puolelle:

#########################################################################################################################################################
    #                                                                                                                                                       #
    # Set the wanted layers and other setable hyperparams                                                                                                   #
    #                  333                         ___________HIDDEN LAYERS I-III_____________                                                                 #
    #                                           | L1(in)  L2     L3       L4      L5(out) |                                                                 #
    # Right now im experiementing with this:    |  784  | 256 | 256/2 | 256/2/2 |    10   | ;model with 3 hidden layers.                                    #
    #                                           |_________________________________________|                                                                 #
    #                                                                                                                                                       #
    # these seems to get good outputs more tuning will be doned                                                                                             #
    #                                                                                                                                                       #
    # with alpha = 0.5 , it seems like going above 25 epoch does not change much and above 90 can be found around 10 epoch , 25 epoch yielded 0.02 better.  #
    # alpha 0.5 :: 15epoch = 0.9191 , 20epoch = 0.9223, 25epoch = 0.926 , 50epoch = 0.9384, 75epoch = 0.9476// 200 = 0.9517 #W TEST DATA                    #
    # it takes about 5080 sek to train 75 epoch, with batching = sized 190 epoch 200 === testacc == 0.9601. with batching size 10 and epochs =150 tacc=0.9774                                                                                                              #
    #                                                                                                                                                       #
    #           0.9801 with layer above lr = 0.02 epoch 150 batching in 10 samples                                                                                               #
    #########################################################################################################################################################
  1. Koodissa weights & biases tallennetaan hashmappiin. Nopeuden kannalta tämä on hyvä tapa hoitaa tallennus, mutta hashmapin avaimet on nimetty mielestäni sekavasti, esim.
gradients[f'dW{layer}'] = 1 / trainingsize * \
            np.dot(derivatives[f'dZ{layer}'], activations[f'A{layer-1}'].T)
gradients[f'db{layer}'] = 1 / trainingsize * \
            np.sum(derivatives[f'dZ{layer}'], axis=1, keepdims=True)

dW ja db oletettavasti viittaa delta_weights ja delta_biases, mutta selkeyden kannalta ehkä parempi olisi nimetä ne kuvailevammin.

  1. GUI ei tunnista numeroita, jotka piirretään GUI:n reunoille.

Tässä oli muutamia kommentteja joita itsellä heräsi mieleen koodia lukiessa, kuten sanoin projekti toimii hyvin ja kuten kuuluukin. Kiva myös, että olet lisännyt tuen sigmoidille ja relulle jolloin käyttäjä voi halutessaan kokeilla treenaamista molemmilla aktivaatiofunktioilla.

Kovakoodatut kohdat ja treenidatan händläämisen kun vielä saa fixattua niin alkaa olemaan jo hyvin käyttäjä ystävällinen projekti.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.