Запуск моделей лесов решений TensorFlow с помощью TensorFlow.js

В этих инструкциях объясняется, как обучить модель TF-DF и запустить ее в Интернете с помощью TensorFlow.js.

Подробные инструкции

Обучите модель в TF-DF

Чтобы опробовать этот урок, вам сначала понадобится модель TF-DF. Вы можете использовать свою собственную модель или обучить ее с помощью руководства для начинающих .

Если вы просто хотите быстро обучить модель в Google Colab, вы можете использовать следующий фрагмент кода.

!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)

Преобразование модели

Дальнейшие инструкции предполагают, что вы сохранили свою модель TF-DF по пути /tmp/my_saved_model . Запустите следующий фрагмент, чтобы преобразовать модель в 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")

Когда Google Colab завершает работу, он загружает преобразованную модель TFJS в виде zip-файла. Разархивируйте этот файл, прежде чем использовать его на следующем шаге.

Разархивированная модель Tensorflow.js состоит из нескольких файлов. Пример модели содержит следующее:

  • активы.zip
  • группа1-shard1of1.bin
  • модель.json

Используйте модель Tensorflow.js в Интернете.

Используйте этот шаблон для загрузки зависимостей TFJS и запуска модели TFDF. Измените путь к модели туда, где обслуживается ваша модель, и измените тензор, переданный для выполненияAsync.

  <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>

Вопросы?

Ознакомьтесь с документацией по лесам решений TensorFlow и документацией TensorFlow.js .