TensorFlow.js Layers: High-Level Machine Learning Model API
A part of the TensorFlow.js ecosystem, TensorFlow.js Layers is a high-level API built on TensorFlow.js Core, enabling users to build, train and execute deep learning models in the browser. TensorFlow.js Layers is modeled after Keras and tf.keras and can load models saved from those libraries.
There are three ways to import TensorFlow.js Layers
- You can access TensorFlow.js Layers through the union package between the TensorFlow.js Core and Layers: @tensorflow/tfjs
- You can get [TensorFlow.js] Layers as a module:
tfjs-layershas peer dependency on tfjs-core, so if you import
@tensorflow/tfjs-layers, you also need to import
- As a standalone through unpkg.
Option 1 is the most convenient, but leads to a larger bundle size (we will be adding more packages to it in the future). Use option 2 if you care about bundle size.
Building, training and executing a model
The following example shows how to build a toy model with only one
to perform linear regression.
;// A sequential model is a container which you can add layers to.const model = tf;// Add a dense layer with 1 output unit.model;// Specify the loss type and optimizer for training.model;// Generate some synthetic data for training.const xs = tf;const ys = tf;// Train the model.await model;// Ater the training, perform inference.const output = model;output;
Loading a pretrained Keras model
You can also load a model previously trained and saved from elsewhere (e.g., from Python Keras) and use it for inference or transfer learning in the browser.
For example, in Python, save your Keras model using
which can be installed using
pip install tensorflowjs.
import tensorflowjs as tfjs# ... Create and train your Keras model.# Save your Keras model in TensorFlow.js format.# Then use your favorite web server to serve the directory at a URL, say#
To load the model with TensorFlow.js Layers:
;const model = await tf;// Now the model is ready for inference, evaluation or re-training.