Usage

Node

At present, the published version of brain.js is approximately 1.0.0, featuring only Feed-forward NN. All other models are beta and are being jazzed up and battle hardened.
You can still download the latest, though. They are cool!

Browser

Download the latest brain.js for browser. Training is computationally expensive, so you should try to train the network offline (or on a Worker) and use the toFunction() or toJSON() options to plug the pre-trained network into your website.

Training

Use train() to train the network with an array of training data. The network has to be trained with all the data in bulk in one call to train(). More training patterns will probably take longer to train, but will usually result in a network better
at classifying new patterns.

Data format

For training with NeuralNetwork

Each training pattern should have an input and an output, both of which can be either an array of numbers from 0 to 1 or a hash of numbers from 0 to 1. For the color contrast demo it looks something like this:

For training with RNN, LSTM and GRU

Each training pattern can either:

Be an array of values

Be a string

Have an input and an output

Either of which can an array of values or a string

CAUTION: When using an array of values, you can use ANY value, however, the values are represented in the neural network by a single input. So the more distinct values has the larger your input layer. If you have a hundreds, thousands, or millions of floating point values THIS IS NOT THE RIGHT CLASS FOR THE JOB. Also, when deviating from strings, this gets into beta

Example using direct strings:

constnet=newbrain.recurrent.LSTM();
net.train([
'doe, a deer, a female deer',
'ray, a drop of golden sun',
'me, a name I call myself',
]);
constoutput=net.run('doe'); // ', a deer, a female deer'

Example using strings with inputs and outputs:

constnet=newbrain.recurrent.LSTM();
net.train([
{ input:'I feel great about the world!', output:'happy' },
{ input:'The world is a terrible place!', output:'sad' },
]);
constoutput=net.run('I feel great about the world!'); // 'happy'

Training Options

train() takes a hash of options as its second argument:

net.train(data, {
// Defaults values --> expected validation
iterations:20000, // the maximum times to iterate the training data --> number greater than 0
errorThresh:0.005, // the acceptable error percentage from training data --> number between 0 and 1
log:false, // true to use console.log, when a function is supplied it is used --> Either true or a function
logPeriod:10, // iterations between logging out --> number greater than 0
learningRate:0.3, // scales with delta to effect training rate --> number between 0 and 1
momentum:0.1, // scales with next layer's change value --> number between 0 and 1
callback:null, // a periodic call back that can be triggered while training --> null or function
callbackPeriod:10, // the number of iterations through the training data between callback calls --> number greater than 0
timeout:Infinity// the max number of milliseconds to train for --> number greater than 0
});

The network will stop training whenever one of the two criteria is met: the training error has gone below the threshold (default 0.005), or the max number of iterations (default 20000) has been reached.

By default training will not let you know how it's doing until the end, but set log to true to get periodic updates on the current training error of the network. The training error should decrease every time. The updates will be printed to console. If you set log to a function, this function will be called with the updates instead of printing to the console.

The learning rate is a parameter that influences how quickly the network trains. It's a number from 0 to 1. If the learning rate is close to 0, it will take longer to train. If the learning rate is closer to 1, it will train faster, but training results may be constrained to a local minimum and perform badly on new data.(Overfitting) The default learning rate is 0.3.

The momentum is similar to learning rate, expecting a value from 0 to 1 as well, but it is multiplied against the next level's change value. The default value is 0.1

Any of these training options can be passed into the constructor or passed into the updateTrainingOptions(opts) method and they will be saved on the network and used during the training time. If you save your network to json, these training options are saved and restored as well (except for callback and log, callback will be forgotten and log will be restored using console.log).

A boolean property called invalidTrainOptsShouldThrow is set to true by default. While the option is true, if you enter a training option that is outside the normal range, an error will be thrown with a message about the abnormal option. When the option is set to false, no error will be sent, but a message will still be sent to console.warn with the related information.

Async Training

trainAsync() takes the same arguments as train (data and options). Instead of returning the results object from training, it returns a promise that when resolved will return the training results object.

toJSON() -> json

Serialize neural network to json

fromJSON(json)

Deserialize neural network from json

Failing

If the network failed to train, the error will be above the error threshold. This could happen if the training data is too noisy (most likely), the network does not have enough hidden layers or nodes to handle the complexity of the data, or it has not been trained for enough iterations.

If the training error is still something huge like 0.4 after 20000 iterations, it's a good sign that the network can't make sense of the given data.

RNN, LSTM, or GRU Output too short or too long

The instance of the net's property maxPredictionLength (default 100) can be set to adjust the output of the net;

Example:

constnet=newbrain.recurrent.LSTM();
// later in code, after training on a few novels, write me a new one!net.maxPredictionLength=1000000000; // Be careful!net.run('Once upon a time');

JSON

Serialize or load in the state of a trained network with JSON:

constjson=net.toJSON();
net.fromJSON(json);

Standalone Function

You can also get a custom standalone function from a trained network that acts just like run():

hiddenLayers

You can use this to specify the number of hidden layers in the network and the size of each layer. For example, if you want two hidden layers - the first with 3 nodes and the second with 4 nodes, you'd give:

hiddenLayers: [3, 4]

By default brain.js uses one hidden layer with size proportionate to the size of the input array.

Streams

The network now has a WriteStream. You can train the network by using pipe() to send the training data to the network.