Let's play with Dinfio!
In this playground, we are going to build a neural network using neural module to recognise handwritten numbers. We will use MNIST dataset that contains 60,000 greyscale images with 28x28 pixels each for training, and 10,000 greyscale images for testing.
$ dima install neural
' Neural Network in Dinfio
import neural
import fileio
start
' Construct the model with 784 inputs, 2 hidden layers, 10 outputs, and learning rate: 0.01
model = neural_network([784, 20, 10, 10], 0.01)
' Load the MNIST dataset
path = getfoldername(getcurrentfile())
dataset_train = mnist(path & "/dataset/train-images.idx3-ubyte", path & "/dataset/train-labels.idx1-ubyte")
dataset_test = mnist(path & "/dataset/t10k-images.idx3-ubyte", path & "/dataset/t10k-labels.idx1-ubyte")
' Train the model with epochs: 5
train(model, dataset_train, 5)
' Test the model and calculate its accuracy
test(model, dataset_test)
stop
function train(model, dataset, epochs = 3)
writeln("Total training data: " & dataset.size())
for i, 1, epochs
writeln("Training... Epoch: " & i & " of " & epochs)
for j, 0, dataset.size() - 1
expected = dataset.outputs(j)
model.feed_forward(dataset.inputs(j))
model.back_propagation(expected)
error = calculate_error(model.outputs(), expected)
endfor
endfor
stop
function test(model, dataset)
total_errors = 0
writeln("Testing")
for i, 0, dataset.size() - 1
input = dataset.inputs(i)
expected = dataset.outputs(i)
model.feed_forward(input)
outputs = model.outputs()
predicted = argmax(outputs)
expc = argmax(expected)
err = calculate_error(outputs, expected)
if predicted != expc; total_errors += 1; endif
endfor
writeln("Total errors: " & total_errors & " - Total data: " & dataset.size() & " - Accuracy: " & (((dataset.size() - total_errors) / dataset.size()) * 100) & "%")
stop