TensorFlow.js Python Library
The `tensorflowjs` Python package provides utilities to convert trained Keras or TensorFlow SavedModel models into a format consumable by TensorFlow.js, enabling them to run directly in a web browser or Node.js environment. It facilitates the deployment of machine learning models on the web. The current version is 4.22.0, with releases typically aligned with major TensorFlow versions.
Warnings
- breaking Compatibility with TensorFlow versions is crucial. Using `tensorflowjs` with a significantly older or newer `tensorflow` package can lead to conversion errors or unexpected behavior. Always check the official documentation for supported TensorFlow versions for your `tensorflowjs` package.
- gotcha Custom TensorFlow Operations or Keras Layers are not automatically converted to their JavaScript equivalents. If your model uses custom ops/layers, you will likely need to implement their logic manually in JavaScript for them to work in TensorFlow.js.
- deprecated While `.h5` (HDF5) Keras model files can often be converted, the recommended and most robust format for saving TensorFlow and Keras models is the TensorFlow SavedModel format (`model.save('path', save_format='tf')`). Conversion from SavedModel is generally more reliable.
- gotcha Converting very large models can be resource-intensive (memory and CPU) and slow. Ensure your conversion environment has sufficient resources.
Install
-
pip install tensorflowjs
Imports
- save_keras_model
from tensorflowjs.converters import save_keras_model
- convert_tf_saved_model
from tensorflowjs.converters import convert_tf_saved_model
Quickstart
import tensorflow as tf
import tensorflowjs as tfjs
import os
import shutil
# Create a simple Keras model
model = tf.keras.Sequential([
tf.keras.layers.Dense(units=1, input_shape=[1])
])
model.compile(optimizer='sgd', loss='mean_squared_error')
# Train the model (dummy data)
hs = model.fit([1, 2, 3, 4], [0, -1, -2, -3], epochs=1)
# Define output directory
output_dir = 'my_tfjs_model'
if os.path.exists(output_dir):
shutil.rmtree(output_dir)
# Convert the Keras model to TensorFlow.js format
tfjs.converters.save_keras_model(model, output_dir)
print(f"Model converted and saved to: {output_dir}/")
print("You can now serve this model with `tensorflowjs_converter --input_format=tfjs_layers_model <path-to-model-json-file>` or directly load it in JavaScript.")
# Clean up (optional)
# shutil.rmtree(output_dir)