NeuralNetwork

Illustration of brain

Description

Create your own neural network and train it in the browser with the ml5.neuralNetwork. Collect data to train your neural network or use existing data to train your neural network in real-time. Once it is trained, your neural network and do classification or regression tasks.

Quickstart

In general the steps for using the ml5.neuralNetwork look something like:

  • Step 1: load data or create some data
  • Step 2: set your neural network options & initialize your neural network
  • Step 4: add data to the neural network
  • Step 5: normalize your data
  • Step 6: train your neural network
  • Step 7: use the trained model to make a classification
  • Step 8: do something with the results

The below examples are quick

Creating data in real-time

  1. // Step 1: load data or create some data
  2. const data = [
  3. {r:255, g:0, b:0, color:'red-ish'},
  4. {r:254, g:0, b:0, color:'red-ish'},
  5. {r:253, g:0, b:0, color:'red-ish'},
  6. {r:0, g:0, b:255, color:'blue-ish'},
  7. {r:0, g:0, b:254, color:'blue-ish'},
  8. {r:0, g:0, b:253, color:'blue-ish'},
  9. ];
  10. // Step 2: set your neural network options
  11. const options = {
  12. task: 'classification',
  13. debug: true
  14. }
  15. // Step 3: initialize your neural network
  16. const nn = ml5.neuralNetwork(options);
  17. // Step 4: add data to the neural network
  18. data.forEach(item => {
  19. const inputs = {
  20. r: item.r,
  21. g: item.g,
  22. b: item.b
  23. };
  24. const output = {
  25. color: item.color
  26. };
  27. nn.addData(inputs, output);
  28. });
  29. // Step 5: normalize your data;
  30. nn.normalizeData();
  31. // Step 6: train your neural network
  32. const trainingOptions = {
  33. epochs: 32,
  34. batchSize: 12
  35. }
  36. nn.train(trainingOptions, finishedTraining);
  37. // Step 7: use the trained model
  38. function finishedTraining(){
  39. classify();
  40. }
  41. // Step 8: make a classification
  42. function classify(){
  43. const input = {
  44. r: 255,
  45. g: 0,
  46. b: 0
  47. }
  48. nn.classify(input, handleResults);
  49. }
  50. // Step 9: define a function to handle the results of your classification
  51. function handleResults(error, result) {
  52. if(error){
  53. console.error(error);
  54. return;
  55. }
  56. console.log(result); // {label: 'red', confidence: 0.8};
  57. }

Loading Existing Data

External data: "data/colorData.json"

  1. [
  2. {"r":255, "g":0, "b":0, "color": "red-ish"},
  3. {"r":254, "g":0, "b":0, "color": "red-ish"}
  4. {"r":253, "g":0, "b":0, "color": "red-ish"},
  5. {"r":0, "g":0, "b":255, "color": "blue-ish"}
  6. {"r":0, "g":0, "b":254, "color": "blue-ish"}
  7. {"r":0, "g":0, "b":253, "color": "blue-ish"}
  8. ];

In your JavaScript: "script.js"

  1. // Step 1: set your neural network options
  2. const options = {
  3. dataUrl: "data/colorData.json",
  4. task: 'classification',
  5. debug: true
  6. }
  7. // Step 2: initialize your neural network
  8. const nn = ml5.neuralNetwork(options, dataLoaded);
  9. // Step 3: normalize data and train the model
  10. function dataLoaded(){
  11. nn.normalizeData();
  12. trainModel();
  13. }
  14. // Step 4: train the model
  15. function trainModel(){
  16. const trainingOptions = {
  17. epochs: 32,
  18. batchSize: 12
  19. }
  20. nn.train(trainingOptions, finishedTraining);
  21. }
  22. // Step 5: use the trained model
  23. function finishedTraining(){
  24. classify();
  25. }
  26. // Step 6: make a classification
  27. function classify(){
  28. const input = {
  29. r: 255,
  30. g: 0,
  31. b: 0
  32. }
  33. nn.classify(input, handleResults);
  34. }
  35. // Step 7: define a function to handle the results of your classification
  36. function handleResults(error, result) {
  37. if(error){
  38. console.error(error);
  39. return;
  40. }
  41. console.log(results); // {label: 'red', confidence: 0.8};
  42. }

Usage

Quick Reference

  • For your reference, a few typical uses are showcased below:

    • Example 1:

      1. const options = {
      2. inputs: 1,
      3. outputs: 1,
      4. task: 'regression'
      5. }
      6. const nn = ml5.neuralNetwork(options)
    • Example 2: loading data as a csv

      1. const options = {
      2. dataUrl: 'weather.csv',
      3. inputs: ['avg_temperature', 'humidity'],
      4. outputs: ['rained'],
      5. task: 'classification'
      6. }
      7. const nn = ml5.neuralNetwork(options, modelLoaded)
    • Example 3: loading data as a json

      1. /**
      2. The weather json looks something like:
      3. {"data": [
      4. {"xs": {"avg_temperature":20, "humidity": 0.2}, "ys": {"rained": "no"}},
      5. {"xs": {"avg_temperature":30, "humidity": 0.9}, "ys": {"rained": "yes"}}
      6. ] }
      7. * */
      8. const options = {
      9. dataUrl: 'weather.json',
      10. inputs: ['avg_temperature', 'humidity'],
      11. outputs: ['rained'],
      12. task: 'classification'
      13. }
      14. const nn = ml5.neuralNetwork(options, modelLoaded)
    • Example 4: specifying labels for a blank neural network

      1. const options = {
      2. inputs: ['x', 'y'],
      3. outputs: ['label'],
      4. task: 'classification',
      5. };
      6. const nn = ml5.neuralNetwork(options);
    • Example 5: creating a convolutional neural network for image classification by setting task: imageClassification.

      1. const IMAGE_WIDTH = 64;
      2. const IMAGE_HEIGHT = 64;
      3. const IMAGE_CHANNELS = 4;
      4. const options = {
      5. task: 'imageClassification',
      6. inputs:[IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_CHANNELS],
      7. outputs: ['label']
      8. }
      9. const nn = ml5.neuralNetwork(options);

Initialization & Parameters

There are a number of ways to initialize the ml5.neuralNetwork. Below we cover the possibilities:

  1. Minimal Configuration Method
  2. Defining inputs and output labels as numbers or as arrays of labels
  3. Loading External Data
  4. Loading a pre-trained Model
  5. A convolutional neural network for image classification tasks
  6. Defining custom layers

Minimal Configuration Method

Minimal Configuration Method: If you plan to create data in real-time, you can just set the type of task you want to accomplish ('regression' | 'classification') and then create the neuralNetwork. You will have to add data later on, but ml5 will figure the inputs and outputs based on the data your add.

  1. const options = {
  2. task: 'regression' // or 'classification'
  3. }
  4. const nn = ml5.neuralNetwork(options)

Defining inputs and output labels as numbers or as arrays of labels

Defining inputs and output labels as numbers or as arrays of labels: If you plan to create data in real-time, you can just set the type of task you want to accomplish ('regression' | 'classification') and then create the neuralNetwork. To be more specific about your inputs and outputs, you can also define the names of the labels for your inputs and outputs as arrays OR the number of inputs and outputs. You will have to add data later on. Note that if you add data as JSON, your JSON Keys should match those defined in the options. If you add data as arrays, make sure the order you add your data match those given in the options.

  • As arrays of labels

    1. const options = {
    2. task: 'classification' // or 'regression'
    3. inputs:['r', 'g','b'],
    4. outputs: ['color']
    5. }
    6. const nn = ml5.neuralNetwork(options)
  • As numbers

    1. const options = {
    2. task: 'classification' // or 'regression'
    3. inputs: 3, // r, g, b
    4. outputs: 2 // red-ish, blue-ish
    5. }
    6. const nn = ml5.neuralNetwork(options)

Loading External Data

Loading External Data: You can initialize ml5.neuralNetwork specifying an external url to some data structured as a CSV or a JSON file. If you pass in data as part of the options, you will need to provide a callback function that will be called when your data has finished loading. Furthermore, you will need to specify which properties in the data that ml5.neuralNetwork will use for inputs and outputs.

  1. const options = {
  2. dataUrl: 'data/colorData.csv'
  3. task: 'classification' // or 'regression'
  4. inputs: ['r', 'g','b'], // r, g, b
  5. outputs: ['color'] // red-ish, blue-ish
  6. }
  7. const nn = ml5.neuralNetwork(options, dataLoaded)
  8. function dataLoaded(){
  9. // continue on your neural network journey
  10. nn.normalizeData();
  11. // ...
  12. }

Loading a pre-trained Model

Loading a pre-trained Model: If you’ve trained a model using the ml5.neuralNetwork and saved it out using the ml5.neuralNetwork.save() then you can load in the model, the weights, and the metadata.

  1. const options = {
  2. task: 'classification' // or 'regression'
  3. }
  4. const nn = ml5.neuralNetwork(options);
  5. const modelDetails = {
  6. model: 'model/model.json',
  7. metadata: 'model/model_meta.json',
  8. weights: 'model/model.weights.bin'
  9. }
  10. nn.load(modelDetails, modelLoaded)
  11. function modelLoaded(){
  12. // continue on your neural network journey
  13. // use nn.classify() for classifications or nn.predict() for regressions
  14. }

A convolutional neural network for image classification tasks

A convolutional neural network for image classification tasks: You can use convolutional neural networks in the ml5.neuralNetwork by setting the task:"imageClassification".

  1. const IMAGE_WIDTH = 64;
  2. const IMAGE_HEIGHT = 64;
  3. const IMAGE_CHANNELS = 4;
  4. const options = {
  5. task: 'imageClassification',
  6. inputs:[IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_CHANNELS],
  7. outputs: ['label']
  8. }
  9. const nn = ml5.neuralNetwork(options);

Defining Custom Layers

Defaults: By default the ml5.neuralNetwork has simple default architectures for the classification, regression and imageClassificaiton tasks.

  • default classification layers:

    1. layers:[
    2. {
    3. type: 'dense',
    4. units: this.options.hiddenUnits,
    5. activation: 'relu',
    6. },
    7. {
    8. type: 'dense',
    9. activation: 'softmax',
    10. },
    11. ];
  • default regression layers:

    1. layers: [
    2. {
    3. type: 'dense',
    4. units: this.options.hiddenUnits,
    5. activation: 'relu',
    6. },
    7. {
    8. type: 'dense',
    9. activation: 'sigmoid',
    10. },
    11. ];
  • default imageClassification layers:

    1. layers = [
    2. {
    3. type: 'conv2d',
    4. filters: 2,
    5. kernelSize: 2,
    6. strides: 2,
    7. activation: 'relu',
    8. kernelInitializer: 'varianceScaling',
    9. },
    10. {
    11. type: 'maxPooling2d',
    12. poolSize: [1, 1],
    13. strides: [1, 1],
    14. },
    15. {
    16. type: 'conv2d',
    17. filters: 1,
    18. kernelSize: 1,
    19. strides: 1,
    20. activation: 'relu',
    21. kernelInitializer: 'varianceScaling',
    22. },
    23. {
    24. type: 'maxPooling2d',
    25. poolSize: [1, 1],
    26. strides: [1, 1],
    27. },
    28. {
    29. type: 'flatten',
    30. },
    31. {
    32. type: 'dense',
    33. kernelInitializer: 'varianceScaling',
    34. activation: 'softmax',
    35. },
    36. ];

Defining Custom Layers: You can define custom neural network architecture by defining your layers in the options that are passed to the ml5.neuralNetwork on initialization.

  • A neural network with 3 layers

    1. const options = {
    2. debug: true,
    3. task: 'classification',
    4. layers: [
    5. {
    6. type: 'dense',
    7. units: 16,
    8. activation: 'relu'
    9. },
    10. {
    11. type: 'dense',
    12. units: 16,
    13. activation: 'sigmoid'
    14. },
    15. {
    16. type: 'dense',
    17. activation: 'sigmoid'
    18. }
    19. ]
    20. };
    21. const nn = ml5.neuralNetwork(options);

Arguments for ml5.neuralNetwork(options)

The options that can be specified are:

  1. const DEFAULTS = {
  2. inputs: [], // can also be a number
  3. outputs: [], // can also be a number
  4. dataUrl: null,
  5. modelUrl: null,
  6. layers: [], // custom layers
  7. task: null, // 'classification', 'regression', 'imageClassificaiton'
  8. debug: false, // determines whether or not to show the training visualization
  9. learningRate: 0.2,
  10. hiddenUnits: 16,
  11. };

Properties

propertydescriptiondatatype
.callbackthe callback to be called after data is loaded on initializationfunction
.optionsthe options for how the neuralNetwork should be configured on initializationobject
.neuralNetworkthe neuralNetwork class where all of the tensorflow.js model operations are organizedclass
.neuralNetworkDatathe neuralNetworkData class where all of the data handling operations are organizedclass
.neuralNetworkVisthe neuralNetworkVis class where all of the tf-vis operations are organizedclass
.dataThe property that stores all of the training data after .train() is calledclass
.readyset to true if the model is loaded and ready, false if it is not.boolean

Methods

Overview

methoddescription
.addData()adds data to the neuralNetworkData.data.raw array
.normalizeData()normalizes the data stored in neuralNetworkData.data.raw and stores the normalized values in the neuralNetwork.data.training array
.train()uses the data in the neuralNetwork.data.training array to train your model
.predict()for regression tasks, allows you to make a prediction based on an input array or JSON object.
.predictMultiple()for regression tasks, allows you to make a prediction based on an input array of arrays or array of JSON objects.
.classify()for classification tasks, allows you to make a classification based on an input array or JSON object.
.classifyMultiple()for classification tasks, allows you to make classifications based on an input array of arrays or array of JSON objects.
.saveData()allows you to save your data out from the neuralNetworkData.data.raw array
.loadData()allows you to load data previously saved from the .saveData() function
.save()allows you to save the trained model
.load()allows you to load a trained model

.addData()

If you are not uploading data using the dataUrl property of the options given to the constructor, then you can add data to a “blank” neural network class using the .addData() function.

  1. neuralNetwork.addData(xs, ys);

📥 Inputs

  • xs: Required. Array | Object.
    • If an array is given, then the inputs must be ordered as specified in the constructor. If no labels are given in the constructor, then the order that your data are added here will set the order of how you will pass data to .predict() or .classify().
    • If an object is given, then feed in key/value pairs.
    • if task:imageClassification: you can supply a HTMLImageElement or HTMLCanvasElement or a flat 1-D array of the pixel values such that the dimensions match with the defined image size in the options.inputs: [IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_CHANNELS]
  • ys: Required. Array | Object.
    • If an array is given, then the inputs must be ordered as specified in the constructor.
    • If an object is given, then feed in key/value pairs.

📤 Outputs

  • n/a: adds data to neuralNetwork.data.data.raw


.normalizeData()

normalizes the data on a scale from 0 to 1. The data being normalized are part of the NeuralNetworkData class which can be accessed in: neuralNetwork.data.data.raw

  1. neuralNetwork.normalizeData();

📥 Inputs

  • n/a

📤 Outputs

  • n/a: normalizes the data in neuralNetwork.data.data.raw and adds inputs and output tensors to neuralNetwork.data.data.tensor as well as the inputMin, inputMax, outputMin, and outputMax as tensors. The inputMin, inputMax, outputMin, and outputMax are also added to neuralNetwork.data.data as Numbers.


.train()

trains the model with the data loaded during the instantiation of the NeuralNetwork or the data added using neuralNetwork.addData()

  1. neuralNetwork.train(?optionsOrCallback, ?optionsOrWhileTraining, ?callback);

📥 Inputs

  • optionsOrCallback: Optional.

    • If an object of options is given, then optionsOrCallback will be an object where you can specify the batchSize and epochs:

      1. {
      2. batchSize: 24,
      3. epochs: 32,
      4. };
    • If a callback function is given here then this will be a callback that will be called when the training is finished.

      1. function doneTraining() {
      2. console.log('done!');
      3. }
    • If a callback function is given here and a second callback function is given, optionsOrCallback will be a callback function that is called after each epoch of training, and the optionsOrWhileTraining callback function will be a callback function that is called when the training has completed:

      1. function whileTraining(epoch, loss) {
      2. console.log(`epoch: ${epoch}, loss:${loss}`);
      3. }
      4. function doneTraining() {
      5. console.log('done!');
      6. }
      7. neuralNetwork.train(whileTraining, doneTraining);
  • optionsOrWhileTraining: Optional.

    • If an object of options is given as the first parameter, then optionsOrWhileTraining will be a callback function that is fired after the training as finished.
    • If a callback function is given as the first parameter to handle the whileTraining, then optionsOrWhileTraining will be a callback function that is fired after the training as finished.
  • callback: Optional. Function.

    • If an object of options is given as the first parameter and a callback function is given as a second parameter, then this callback parameter will be a callback function that is fired after the training as finished.

      1. const trainingOptions = {
      2. batchSize: 32,
      3. epochs: 12,
      4. };
      5. function whileTraining(epoch, loss) {
      6. console.log(`epoch: ${epoch}, loss:${loss}`);
      7. }
      8. function doneTraining() {
      9. console.log('done!');
      10. }
      11. neuralNetwork.train(trainingOptions, whileTraining, doneTraining);
  1. ```
  2. ```

📤 Outputs

  • n/a: Here, neuralNetwork.model is created and the model is trained.


.predict()

Given an input, will return an array of predictions.

  1. neuralNetwork.predict(inputs, callback);

📥 Inputs

  • inputs: Required. Array | Object.
    • If an array is given, then the input values should match the order that the data are specifed in the inputs of the constructor options.
    • If an object is given, then the input values should be given as a key/value pair. The keys must match the keys given in the inputs of the constructor options and/or the keys added when the data were added in .addData().
  • callback: Required. Function. A function to handle the results of .predict().

📤 Outputs

  • Array: Returns an array of objects. Each object contains {value, label}.


.predictMultiple()

Given an input, will return an array of arrays of predictions.

  1. neuralNetwork.predictMultiple(inputs, callback);

📥 Inputs

  • inputs: Required. Array of arrays | Array of objects.
    • If an array of arrays is given, then the input values of each child array should match the order that the data are specifed in the inputs of the constructor options.
    • If an array of objects is given, then the input values of each child object should be given as a key/value pair. The keys must match the keys given in the inputs of the constructor options and/or the keys added when the data were added in .addData().
  • callback: Required. Function. A function to handle the results of .predictMultiple().

📤 Outputs

  • Array: Returns an array of arrays. Each child array contains objects. Each object contains {value, label}.


.classify()

Given an input, will return an array of classifications.

  1. neuralNetwork.classify(inputs, callback);

📥 Inputs

  • inputs: Required. Array | Object.
    • If an array is given, then the input values should match the order that the data are specifed in the inputs of the constructor options.
    • If an object is given, then the input values should be given as a key/value pair. The keys must match the keys given in the inputs of the constructor options and/or the keys added when the data were added in .addData().
  • callback: Required. Function. A function to handle the results of .classify().

📤 Outputs

  • Array: Returns an array of objects. Each object contains {label, confidence}.


.classifyMultiple()

Given an input, will return an array of arrays of classifications.

  1. neuralNetwork.classifyMultiple(inputs, callback);

📥 Inputs

  • inputs: Required. Array of arrays | Array of objects.
    • If an array of arrays is given, then the input values of each child array should match the order that the data are specifed in the inputs of the constructor options.
    • If an array of objects is given, then the input values of each child object should be given as a key/value pair. The keys must match the keys given in the inputs of the constructor options and/or the keys added when the data were added in .addData().
  • callback: Required. Function. A function to handle the results of .classifyMultiple().

📤 Outputs

  • Array: Returns an array of arrays. Each child array contains objects. Each object contains {label, confidence}.


.saveData()

Saves the data that has been added

  1. neuralNetwork.saveData(?outputName, ?callback);

📥 Inputs

  • outputName: Optional. String. An output name you’d like your data to be called. If no input is given, then the name will be data_YYYY-MM-DD_mm-hh.
  • callback: Optional. function. A callback that is called after the data has been saved.

📤 Outputs

  • n/a: downloads the data to a .json file in your downloads folder.


.loadData()

loads the data to neuralNetwork.data.data.raw

  1. neuralnetwork.loadData(?filesOrPath, ?callback);

📥 Inputs

  • filesOrPath: REQUIRED. String | InputFiles. A string path to a .json data object or InputFiles from html input type="file". Must be structured for example as: {"data": [ { xs:{input0:1, input1:2}, ys:{output0:"a"}, ...]}
  • callback: Optional. function. A callback that is called after the data has been loaded.

📤 Outputs

  • n/a: set neuralNetwork.data.data.raw to the array specified in the "data" property of the incoming .json file.


.save()

Saves the trained model

  1. neuralNetwork.save(?outputName, ?callback);

📥 Inputs

  • outputName: Optional. String. An output name you’d like your model to be called. If no input is given, then the name will be model.
  • callback: Optional. function. A callback that is called after the model has been saved.

📤 Outputs

  • n/a: downloads the model to a .json file and a model.weights.bin binary file in your downloads folder.


.load()

Loads a pre-trained model

  1. neuralNetwork.load(?filesOrPath, ?callback);

📥 Inputs

  • filesOrPath: REQUIRED. String | InputFiles.

    • If a string path to the model.json data object is given, then the model.json, model_meta.json file and its accompanying model.weights.bin file will be loaded. Note that the names must match.
    • If InputFiles from html input type="file". Then make sure to select ALL THREE of the model.json, model_meta.json and the model.weights.bin file together to upload otherwise the load will throw an error.
    • Method 1: using a json object. In this case, the paths to the specific files are set directly.

      1. const modelInfo = {
      2. model: 'path/to/model.json',
      3. metadata: 'path/to/model_meta.json',
      4. weights: 'path/to/model.weights.bin',
      5. };
      6. neuralNetwork.load(modelInfo, modelLoadedCallback);
    • Method 2: specifying only the path to th model.json. In this case, the model_meta.json and the model.weights.bin are assumed to be in the same directory, named exactly like model_meta.json and model.weights.bin.

      1. neuralNetwork.load('path/to/model.json', modelLoadedCallback);
    • Method 3: using the <input type="file" multiple>

  • callback: Optional. function. A callback that is called after the model has been loaded.

📤 Outputs

  • n/a: loads the model to neuralNetwork.model

Examples

p5.js

p5 web editor

plain javascript

  • coming soon

Demo

No demos yet - contribute one today!

Tutorials

ml5.js: Train Your Own Neural Network (Coding Train)

ml5.js: Save Neural Network Training Data (Coding Train)

ml5.js: Save Neural Network Trained Model (Coding Train)

ml5.js: Neural Network Regression (Coding Train)

Acknowledgements

Contributors:

Credits:

  • Paper Reference | Website URL | Github Repo | Book reference | etc

Source Code