TensorFlow.js conversion lets you use machine learning models directly in a web browser. This means you can run AI without needing a server.
0
0
TensorFlow.js conversion
Introduction
You want to run a trained TensorFlow model inside a website.
You want users to get instant AI results without internet delays.
You want to share your AI model easily without complex setup.
You want to build interactive AI demos that run on any device.
You want to protect user data by running AI locally in the browser.
Syntax
TensorFlow
tensorflowjs_converter \ --input_format=tf_saved_model \ /path/to/saved_model \ /path/to/tfjs_target_dir
The command converts a TensorFlow SavedModel to TensorFlow.js format.
You can also convert Keras models or frozen graphs by changing --input_format.
Examples
Convert a TensorFlow SavedModel folder
my_model to TensorFlow.js format in tfjs_model folder.TensorFlow
tensorflowjs_converter --input_format=tf_saved_model ./my_model ./tfjs_model
Convert a Keras H5 model file
model.h5 to TensorFlow.js format.TensorFlow
tensorflowjs_converter --input_format=keras ./model.h5 ./tfjs_keras_model
Convert a frozen TensorFlow graph to TensorFlow.js format, specifying output nodes.
TensorFlow
tensorflowjs_converter --input_format=tf_frozen_model --output_node_names='output_node' ./frozen_model.pb ./tfjs_frozen_modelSample Model
This code creates a simple neural network, saves it, and converts it to TensorFlow.js format using the command line tool inside Python.
TensorFlow
import tensorflow as tf import tensorflowjs as tfjs # Create a simple Keras model model = tf.keras.Sequential([ tf.keras.layers.Dense(10, activation='relu', input_shape=(5,)), tf.keras.layers.Dense(1, activation='sigmoid') ]) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) # Save the model in TensorFlow SavedModel format model.save('saved_model') # Convert the saved model to TensorFlow.js format import subprocess subprocess.run([ 'tensorflowjs_converter', '--input_format=tf_saved_model', 'saved_model', 'tfjs_model' ]) print('Model converted to TensorFlow.js format in folder tfjs_model')
OutputSuccess
Important Notes
Make sure you have tensorflowjs installed: pip install tensorflowjs.
The conversion creates files that can be loaded in JavaScript with tf.loadLayersModel().
Check the TensorFlow.js documentation for advanced options like quantization.
Summary
TensorFlow.js conversion lets you run TensorFlow models in web browsers.
You convert models using the tensorflowjs_converter tool.
Converted models can be loaded easily in JavaScript for fast, local AI.