Exécuter des modèles TensorFlow Decision Forests avec TensorFlow.js

Ces instructions expliquent comment entraîner un modèle TF-DF et l'exécuter sur le Web à l'aide de TensorFlow.js.

Des instructions détaillées

Former un modèle dans TF-DF

Pour essayer ce tutoriel, vous avez d'abord besoin d'un modèle TF-DF. Vous pouvez utiliser votre propre modèle ou entraîner un modèle avec le didacticiel pour débutants .

Si vous souhaitez simplement entraîner rapidement un modèle dans Google Colab, vous pouvez utiliser l'extrait de code suivant.

!pip install tensorflow_decision_forests -U -qq
import tensorflow as tf
import tensorflow_decision_forests as tfdf
import pandas as pd

# Download the dataset, load it into a pandas dataframe and convert it to TensorFlow format.
!wget -q https://storage.googleapis.com/download.tensorflow.org/data/palmer_penguins/penguins.csv -O /tmp/penguins.csv
dataset_df = pd.read_csv("/tmp/penguins.csv")
train_ds = tfdf.keras.pd_dataframe_to_tf_dataset(dataset_df, label="species")

# Create and train the model
model_1 = tfdf.keras.GradientBoostedTreesModel()
model_1.fit(train_ds)

Convertir le modèle

Les instructions suivantes supposent que vous avez enregistré votre modèle TF-DF sous le chemin /tmp/my_saved_model . Exécutez l'extrait suivant pour convertir le modèle en TensorFlow.js.

!pip install tensorflow tensorflow_decision_forests 'tensorflowjs>=4.4.0'
!pip install tf_keras

# Prepare and load the model with TensorFlow
import tensorflow as tf
import tensorflowjs as tfjs
from google.colab import files

# Save the model in the SavedModel format
tf.saved_model.save(model_1, "/tmp/my_saved_model")

# Convert the SavedModel to TensorFlow.js and save as a zip file
tfjs.converters.tf_saved_model_conversion_v2.convert_tf_saved_model("/tmp/my_saved_model", "./tfjs_model")

# Download the converted TFJS model
!zip -r tfjs_model.zip tfjs_model/
files.download("tfjs_model.zip")

Une fois l'exécution de Google Colab terminée, il télécharge le modèle TFJS converti sous forme de fichier zip. Décompressez ce fichier avant de l'utiliser à l'étape suivante.

Un modèle Tensorflow.js décompressé se compose d'un certain nombre de fichiers. L'exemple de modèle contient les éléments suivants :

  • actifs.zip
  • groupe1-fragment1of1.bin
  • modèle.json

Utiliser le modèle Tensorflow.js sur le Web

Utilisez ce modèle pour charger les dépendances TFJS et exécuter le modèle TFDF. Modifiez le chemin du modèle vers l'endroit où votre modèle est servi et modifiez le tenseur donné à executeAsync.

  <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.5.0/dist/tf.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-tfdf/dist/tf-tfdf.min.js"></script>
  <script>
    (async () =>{
      // Load the model.
      // Tensorflow.js currently needs the absolute path to the model including the full origin.
      const model = await tfdf.loadTFDFModel('https://path/to/unzipped/model/model.json');
      // Perform an inference
      const result = await model.executeAsync({
            "island": tf.tensor(["Torgersen"]),
            "bill_length_mm": tf.tensor([39.1]),
            "bill_depth_mm": tf.tensor([17.3]),
            "flipper_length_mm": tf.tensor([3.1]),
            "body_mass_g": tf.tensor([1000.0]),
            "sex": tf.tensor(["Female"]),
            "year": tf.tensor([2007], [1], 'int32'),
      });
      // The result is a 6-dimensional vector, the first half may be ignored
      result.print();
    })();
  </script>

Des questions?

Consultez la documentation TensorFlow Decision Forests et la documentation TensorFlow.js .