TensorFlow.js Python Library

4.22.0 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to create a simple Keras model, train it, and then use `tensorflowjs.converters.save_keras_model` to convert it into the TensorFlow.js Layers format, ready for web deployment. The output is a directory containing `model.json` and weight files.

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)

view raw JSON →