logo.png

Sign Up    FAQs

Find What Matters

 

Creating a Simple AI in the Browser with TensorFlow.js

ci3.png

Prologue

Machine learning has become an increasingly popular field in recent years, and thanks to tools like TensorFlow.js, it's now possible to train and run machine learning models directly in the browser. TensorFlow.js is a JavaScript library for machine learning that provides a variety of pre-trained models and the ability to fine-tune these models for your own purposes. In this tutorial, we'll show you how to create a simple AI in the browser using TensorFlow.js.

There are many ways to create an AI that works in a web browser, but one way to get started is to use a JavaScript library called TensorFlow.js.

TensorFlow.js is a library for machine learning in JavaScript that allows you to train and run machine learning models directly in the browser. It's easy to use and provides a variety of pre-trained models that you can use or fine-tune for your own purposes.

Example

1. Include The TensorFlow.js Library

First, you'll need to include the TensorFlow.js library in your HTML file:

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.4.0/dist/tf.min.js"></script>

2. Prepare The Data

Next, you'll need to prepare some data for your model to train on. This data should be in the form of a 2D array, with each row representing an input example and each column representing a feature of the input. For example, if you have a model that takes in two input features and outputs a single value, your data might look like this:

const data = {
  inputs: [[0, 0], [0, 1], [1, 0], [1, 1]],
  labels: [[0], [1], [1], [0]]
};

3. Create The Model

Once you have your data, you can create a model using the tf.sequential function:

const model = tf.sequential();

This creates an empty model that you can add layers to.

4. Add Layers To The Model

Next, you'll need to add some layers to your model. You can do this using the model.add function and specifying the type of layer you want to add. There are many types of layers available in TensorFlow.js, including fully-connected (dense) layers, convolutional layers, and recurrent layers.

For example, to add a fully-connected (dense) layer with 32 units, you can do the following:

model.add(tf.layers.dense({units: 32, inputShape: [data.inputs[0].length]}));

This adds a dense layer with 32 units and an input shape that is determined by the number of columns in the input data.

You can add as many layers as you like to your model. Just make sure to specify the inputShape for the first layer and any layers that come after a layer with a different output shape.

5. Compile The Model

After you've added all the layers you want, you'll need to compile your model by specifying an optimizer and a loss function. You can do this using the model.compile function:

model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});

This specifies that the model should be optimized using stochastic gradient descent and that the loss should be calculated using the mean squared error. There are many other optimizers and loss functions.

6. Train The Model

Finally, you can train your model using the model.fit function:

const inputs = tf.tensor2d(data.inputs);
const labels = tf.tensor2d(data.labels);

await model.fit(inputs, labels, {epochs: 100});

This trains the model on the input data and labels, using 100 epochs. An epoch is a full pass through the training data.

7. Use The Model

Once the model is trained, you can use it to make predictions on new data. To do this, you can use the model.predict function:

const output = model.predict(tf.tensor2d([[0, 1]]));
console.log(output.dataSync());

This will print the prediction for the input [0, 1] to the console.

8. Sample Example

A simple AI model that can learn to perform the XOR operation. It has two inputs and one output, and it has two hidden layers with 32 units each. The model is trained using stochastic gradient descent and the mean squared error loss function.

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.4.0/dist/tf.min.js"></script>
<script>
  // Prepare the data
  const data = {
    inputs: [[0, 0], [0, 1], [1, 0], [1, 1]],
    labels: [[0], [1], [1], [0]]
  };

  // Create the model
  const model = tf.sequential();
  model.add(tf.layers.dense({units: 32, inputShape: [data.inputs[0].length]}));
  model.add(tf.layers.dense({units: 1}));

  // Compile the model
  model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});

  // Train the model
  (async function() {
    const inputs = tf.tensor2d(data.inputs);
    const labels = tf.tensor2d(data.labels);

    await model.fit(inputs, labels, {epochs: 100});
    console.log('Training complete');
  })();
</script>

Conclusion

That's a basic example of how to use TensorFlow.js to create a simple AI in the browser. You can find more information and examples in the TensorFlow.js documentation. With TensorFlow.js, you can build and train machine learning models directly in the browser, making it easier than ever to build intelligent web applications.