Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
brain.js/examples/javascript/stream-example.js /
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
50 lines (43 sloc)
1.26 KB
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
| const brain = require('brain.js'); | |
| const TrainStream = require('train-stream'); | |
| const net = new brain.NeuralNetwork(); | |
| const xor = [ | |
| { input: [0, 0], output: [0] }, | |
| { input: [0, 1], output: [1] }, | |
| { input: [1, 0], output: [1] }, | |
| { input: [1, 1], output: [0] }, | |
| ]; | |
| function readInputs(stream, data) { | |
| for (let i = 0; i < data.length; i++) { | |
| stream.write(data[i]); | |
| } | |
| // let it know we've reached the end of the inputs | |
| stream.endInputs(); | |
| } | |
| const trainingStream = new TrainStream({ | |
| neuralNetwork: net, | |
| /** | |
| * Write training data to the stream. Called on each training iteration. | |
| */ | |
| floodCallback: function () { | |
| readInputs(trainingStream, xor); | |
| }, | |
| /** | |
| * Called when the network is done training. | |
| */ | |
| doneTrainingCallback: function (obj) { | |
| console.log( | |
| `trained in ${obj.iterations} iterations with error: ${obj.error}` | |
| ); | |
| const result01 = net.run([0, 1]); | |
| const result00 = net.run([0, 0]); | |
| const result11 = net.run([1, 1]); | |
| const result10 = net.run([1, 0]); | |
| console.log('0 XOR 1: ', result01); // 0.987 | |
| console.log('0 XOR 0: ', result00); // 0.058 | |
| console.log('1 XOR 1: ', result11); // 0.087 | |
| console.log('1 XOR 0: ', result10); // 0.934 | |
| }, | |
| }); | |
| // kick it off | |
| readInputs(trainingStream, xor); |