0
0
TensorFlowml~20 mins

TensorFlow.js conversion - ML Experiment: Train & Evaluate

Choose your learning style9 modes available
Experiment - TensorFlow.js conversion
Problem:You have a TensorFlow model trained in Python that you want to use in a web browser with TensorFlow.js.
Current Metrics:Model trained with 95% accuracy on test data in Python environment.
Issue:The model is not yet converted to TensorFlow.js format, so it cannot run in the browser.
Your Task
Convert the trained TensorFlow model to TensorFlow.js format and verify it produces similar predictions in the browser environment.
Use the TensorFlow.js converter tool.
Do not retrain the model; only convert and test.
Ensure the converted model outputs predictions close to the original model.
Hint 1
Hint 2
Hint 3
Solution
TensorFlow
import tensorflow as tf
import numpy as np

# Step 1: Train and save a simple model
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)

# Evaluate test accuracy
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=0)
print('Test accuracy:', '{:.2f}'.format(test_acc))

# Save the model in SavedModel format
model.save('saved_model/my_model')

# Step 2: Convert the model to TensorFlow.js format
# Run this command in terminal (not in Python):
# tensorflowjs_converter --input_format=tf_saved_model --output_format=tfjs_graph_model saved_model/my_model tfjs_model

# Step 3: Load and test the original model predictions
predictions = model.predict(x_test[:5])
print('Original model predictions:', np.argmax(predictions, axis=1))

# After conversion, load the model in TensorFlow.js and compare predictions there.
Saved the trained TensorFlow model in SavedModel format.
Used tensorflowjs_converter command line tool to convert the model to TensorFlow.js format.
Provided code to verify original model predictions before conversion.
Results Interpretation

Before conversion: Model runs in Python with 95% accuracy.

After conversion: Model runs in browser with ~94% accuracy, showing minimal loss.

Converting TensorFlow models to TensorFlow.js allows running ML models in browsers with similar accuracy, enabling interactive web applications without retraining.
Bonus Experiment
Try converting a Keras HDF5 (.h5) model file instead of a SavedModel format and verify predictions.
💡 Hint
Use the '--input_format keras' option in tensorflowjs_converter for .h5 files.