這些操作說明解釋如何訓練 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 模型包含多個檔案。範例模型包含以下項目
- assets.zip
- group1-shard1of1.bin
- model.json
在網路上使用 Tensorflow.js 模型
使用此範本載入 TFJS 相依性並執行 TFDF 模型。將模型路徑變更為模型伺服的位置,並修改提供給 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>