Various web applications use Neural Networks. The only downside is that you need to import an entire library to run these types of algorithms, which might be inconvenient.
Hopefully, the Dannjs library has a way of saving a Neural Network as a standalone JS function, which allows you to get the predictions without including the whole library.
In this short tutorial, we're going to train an XOR neural network in the new Online editor, and then use it in another browser without importing the library.
Here are the requirements for this tutorial:
- Dannjs Online Editor
- Any web browser
Setup
Let's start by creating the Neural Network.
const nn = new Dann(2, 1);
nn.addHiddenLayer(8, 'leakyReLU');
nn.makeWeights();
nn.lr = 0.1;
Training
We can train the neural network with the XOR logic, 1000 epochs should do the trick.
let epochs = 1000;
for (let i = 0; i < epochs; i++) {
nn.backpropagate([0,1],[1]);
nn.backpropagate([1,0],[1]);
nn.backpropagate([0,0],[0]);
nn.backpropagate([1,1],[0]);
}
Testing
Once trained, we can test the output
nn.feedForward([0,1],{log:true});
nn.feedForward([1,0],{log:true});
nn.feedForward([0,0],{log:true});
nn.feedForward([1,1],{log:true});
This should result in accurate predictions
Prediction:
[0.9955815601552473]
Prediction:
[0.9954508755506862]
Prediction:
[0.04536960523468736]
Prediction:
[0.003240998243744729]
Save
We can finally save the Neural Network as a minified function as a string that we can copy & use anywhere else.
let func = nn.toFunction();
console.log(func);
Here is how you would use the function in another JS environment such as the chrome console.
We can see that we get the same predictions because every single parameter has been saved into the function.
This feature allows us to use any neural network outside of the library, making the usage of these algorithms in web applications simple & lightweight. Loading times on web pages is always a good thing to look out for, making this a neat trick to know about!
Top comments (2)
So I can write complex js functions by providing I/O? That would really speed up my coding workflow!!
If you manage to successfully train a model for your task, definitely yeah!