Werkzeugserie: TensorFlow Decision Forest_(6) Modellvorhersage


Vorhersagen aus TensorFlow Decision Forest ( TF-DF ) . In diesem Artikel lernen Sie verschiedene Möglichkeiten kennen, Vorhersagen mithilfe eines zuvor trainierten TF-DF- Modells mithilfe der Python-API zu generieren .

Hinweis: Die in diesem Artikel vorgestellte Python-API ist einfach zu verwenden und ideal zum Experimentieren. Andere APIs wie TensorFlow Serving und C++ API eignen sich jedoch besser für Produktionssysteme, da sie schneller und stabiler sind. Eine umfassende Liste aller Serving APIs finden Sie hier .

In diesem Artikel werden Sie:

  1. Verwenden Sie model.predict()die Funktion pd_dataframe_to_tf_dataset, um Vorhersagen für einen TensorFlow-Datensatz zu treffen, der mit erstellt wurde.
  2. Verwenden Sie model.predict()eine Funktion, um Vorhersagen für einen manuell erstellten TensorFlow-Datensatz zu treffen.
  3. Verwenden Sie model.predict()Funktionen, um Vorhersagen für Numpy-Arrays zu treffen.
  4. Verwenden Sie die CLI-API, um Vorhersagen zu treffen.
  5. Vergleichen Sie die Inferenzgeschwindigkeit Ihres Modells mithilfe der CLI-API.

wichtiger Hinweis

Der für die Vorhersage verwendete Datensatz sollte dieselben Feature-Namen und -Typen haben wie der für das Training verwendete Datensatz . Andernfalls wird es höchstwahrscheinlich zu einem Fehler kommen.

Beispielsweise wird das Training eines Modells mit zwei Funktionen f1und der Versuch, Vorhersagen für einen Datensatz ohne diese zu generieren, fehlschlagen. Beachten Sie, dass es in Ordnung ist, (einige oder alle) Merkmalswerte auf „fehlend“ zu setzen. Wenn Sie ein Modell mit numerischen Merkmalen (z. B. float32) trainieren und dieses Modell auf einen Datensatz mit Textmerkmalen (z. B. Zeichenfolgen) anwenden, schlägt dies ebenfalls fehl.f2f2f2f2

Obwohl die Keras-API es abstrahiert, können sich ein in Python instanziiertes Modell (z. B. mit tfdf.keras.RandomForestModel()) und ein von der Festplatte geladenes Modell (z. B. mit tf.keras.models.load_model()) unterschiedlich verhalten. Es ist erwähnenswert, dass in Python instanziierte Modelle automatisch die erforderlichen Typkonvertierungen durchführen. Wenn beispielsweise float64ein Feature einem Modell bereitgestellt wird float32, das das Feature erwartet, wird diese Konvertierung implizit durchgeführt. Diese Konvertierung ist jedoch für von der Festplatte geladene Modelle nicht möglich. Daher müssen die Trainingsdaten und Inferenzdaten immer genau vom gleichen Typ sein.

aufstellen

Zuerst installieren wir TensorFlow Decision Forests…

# 安装tensorflow_decision_forests库
!pip install tensorflow_decision_forests
Collecting tensorflow_decision_forests
  Using cached tensorflow_decision_forests-1.1.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (16.2 MB)
Requirement already satisfied: wheel in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorflow_decision_forests) (0.37.1)
Requirement already satisfied: six in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorflow_decision_forests) (1.16.0)
Requirement already satisfied: absl-py in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorflow_decision_forests) (1.3.0)
Requirement already satisfied: tensorflow~=2.11.0 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorflow_decision_forests) (2.11.0)
Collecting wurlitzer
  Using cached wurlitzer-3.0.3-py3-none-any.whl (7.3 kB)
Requirement already satisfied: numpy in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorflow_decision_forests) (1.24.0rc2)
Requirement already satisfied: pandas in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorflow_decision_forests) (1.5.2)
Requirement already satisfied: tensorflow-estimator<2.12,>=2.11.0 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorflow~=2.11.0->tensorflow_decision_forests) (2.11.0)
Requirement already satisfied: h5py>=2.9.0 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorflow~=2.11.0->tensorflow_decision_forests) (3.7.0)
Requirement already satisfied: wrapt>=1.11.0 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorflow~=2.11.0->tensorflow_decision_forests) (1.14.1)
Requirement already satisfied: opt-einsum>=2.3.2 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorflow~=2.11.0->tensorflow_decision_forests) (3.3.0)
Requirement already satisfied: tensorflow-io-gcs-filesystem>=0.23.1 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorflow~=2.11.0->tensorflow_decision_forests) (0.28.0)
Requirement already satisfied: libclang>=13.0.0 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorflow~=2.11.0->tensorflow_decision_forests) (14.0.6)
Requirement already satisfied: packaging in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorflow~=2.11.0->tensorflow_decision_forests) (22.0)
Requirement already satisfied: grpcio<2.0,>=1.24.3 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorflow~=2.11.0->tensorflow_decision_forests) (1.51.1)
Requirement already satisfied: typing-extensions>=3.6.6 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorflow~=2.11.0->tensorflow_decision_forests) (4.4.0)
Requirement already satisfied: gast<=0.4.0,>=0.2.1 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorflow~=2.11.0->tensorflow_decision_forests) (0.4.0)
Requirement already satisfied: protobuf<3.20,>=3.9.2 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorflow~=2.11.0->tensorflow_decision_forests) (3.19.6)
Requirement already satisfied: termcolor>=1.1.0 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorflow~=2.11.0->tensorflow_decision_forests) (2.1.1)
Requirement already satisfied: setuptools in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorflow~=2.11.0->tensorflow_decision_forests) (65.6.3)
Requirement already satisfied: astunparse>=1.6.0 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorflow~=2.11.0->tensorflow_decision_forests) (1.6.3)
Requirement already satisfied: google-pasta>=0.1.1 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorflow~=2.11.0->tensorflow_decision_forests) (0.2.0)
Requirement already satisfied: flatbuffers>=2.0 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorflow~=2.11.0->tensorflow_decision_forests) (22.12.6)
Requirement already satisfied: keras<2.12,>=2.11.0 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorflow~=2.11.0->tensorflow_decision_forests) (2.11.0)
Requirement already satisfied: tensorboard<2.12,>=2.11 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorflow~=2.11.0->tensorflow_decision_forests) (2.11.0)
Requirement already satisfied: python-dateutil>=2.8.1 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from pandas->tensorflow_decision_forests) (2.8.2)
Requirement already satisfied: pytz>=2020.1 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from pandas->tensorflow_decision_forests) (2022.6)
Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorboard<2.12,>=2.11->tensorflow~=2.11.0->tensorflow_decision_forests) (0.4.6)
Requirement already satisfied: werkzeug>=1.0.1 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorboard<2.12,>=2.11->tensorflow~=2.11.0->tensorflow_decision_forests) (2.2.2)
Requirement already satisfied: requests<3,>=2.21.0 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorboard<2.12,>=2.11->tensorflow~=2.11.0->tensorflow_decision_forests) (2.28.1)
Requirement already satisfied: google-auth<3,>=1.6.3 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorboard<2.12,>=2.11->tensorflow~=2.11.0->tensorflow_decision_forests) (2.15.0)
Requirement already satisfied: markdown>=2.6.8 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorboard<2.12,>=2.11->tensorflow~=2.11.0->tensorflow_decision_forests) (3.4.1)
Requirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorboard<2.12,>=2.11->tensorflow~=2.11.0->tensorflow_decision_forests) (0.6.1)
Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from tensorboard<2.12,>=2.11->tensorflow~=2.11.0->tensorflow_decision_forests) (1.8.1)
Requirement already satisfied: pyasn1-modules>=0.2.1 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from google-auth<3,>=1.6.3->tensorboard<2.12,>=2.11->tensorflow~=2.11.0->tensorflow_decision_forests) (0.3.0rc1)
Requirement already satisfied: cachetools<6.0,>=2.0.0 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from google-auth<3,>=1.6.3->tensorboard<2.12,>=2.11->tensorflow~=2.11.0->tensorflow_decision_forests) (5.2.0)
Requirement already satisfied: rsa<5,>=3.1.4 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from google-auth<3,>=1.6.3->tensorboard<2.12,>=2.11->tensorflow~=2.11.0->tensorflow_decision_forests) (4.9)
Requirement already satisfied: requests-oauthlib>=0.7.0 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.12,>=2.11->tensorflow~=2.11.0->tensorflow_decision_forests) (1.3.1)
Requirement already satisfied: importlib-metadata>=4.4 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from markdown>=2.6.8->tensorboard<2.12,>=2.11->tensorflow~=2.11.0->tensorflow_decision_forests) (5.1.0)
Requirement already satisfied: idna<4,>=2.5 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from requests<3,>=2.21.0->tensorboard<2.12,>=2.11->tensorflow~=2.11.0->tensorflow_decision_forests) (3.4)
Requirement already satisfied: certifi>=2017.4.17 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from requests<3,>=2.21.0->tensorboard<2.12,>=2.11->tensorflow~=2.11.0->tensorflow_decision_forests) (2022.12.7)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from requests<3,>=2.21.0->tensorboard<2.12,>=2.11->tensorflow~=2.11.0->tensorflow_decision_forests) (1.26.13)
Requirement already satisfied: charset-normalizer<3,>=2 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from requests<3,>=2.21.0->tensorboard<2.12,>=2.11->tensorflow~=2.11.0->tensorflow_decision_forests) (2.1.1)
Requirement already satisfied: MarkupSafe>=2.1.1 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from werkzeug>=1.0.1->tensorboard<2.12,>=2.11->tensorflow~=2.11.0->tensorflow_decision_forests) (2.1.1)
Requirement already satisfied: zipp>=0.5 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from importlib-metadata>=4.4->markdown>=2.6.8->tensorboard<2.12,>=2.11->tensorflow~=2.11.0->tensorflow_decision_forests) (3.11.0)
Requirement already satisfied: pyasn1<0.6.0,>=0.4.6 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from pyasn1-modules>=0.2.1->google-auth<3,>=1.6.3->tensorboard<2.12,>=2.11->tensorflow~=2.11.0->tensorflow_decision_forests) (0.5.0rc2)
Requirement already satisfied: oauthlib>=3.0.0 in /tmpfs/src/tf_docs_env/lib/python3.9/site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.12,>=2.11->tensorflow~=2.11.0->tensorflow_decision_forests) (3.2.2)
Installing collected packages: wurlitzer, tensorflow_decision_forests
Successfully installed tensorflow_decision_forests-1.1.0 wurlitzer-3.0.3

…und importieren Sie die in diesem Beispiel verwendeten Bibliotheken.

# 导入所需的库
import tensorflow_decision_forests as tfdf  # 导入决策森林库
import os  # 导入操作系统库
import numpy as np  # 导入numpy库,用于数值计算
import pandas as pd  # 导入pandas库,用于数据处理
import tensorflow as tf  # 导入tensorflow库,用于构建和训练模型
import math  # 导入math库,用于数学计算

2022-12-14 12:06:51.603857: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer.so.7'; dlerror: libnvinfer.so.7: cannot open shared object file: No such file or directory
2022-12-14 12:06:51.603946: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer_plugin.so.7'; dlerror: libnvinfer_plugin.so.7: cannot open shared object file: No such file or directory
2022-12-14 12:06:51.603955: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.

model.predict(...)und pd_dataframe_to_tf_datasetFunktion

TensorFlow Decision Forests implementiert die Keras- Modell-API.
Daher hat das TF-DF-Modell predictdie Funktion, Vorhersagen zu treffen. Diese Funktion verwendet einen TensorFlow-Datensatz als Eingabe und gibt ein Array von Vorhersagen aus.
Der einfachste Weg, einen TensorFlow-Datensatz zu erstellen, ist die Verwendung von Pandas und tfdf.keras.pd_dataframe_to_tf_dataset(...)der Funktion.

Das folgende Beispiel zeigt, wie man pd_dataframe_to_tf_datasetmit . einen TensorFlow-Datensatz erstellt.

# 创建一个名为pd_dataset的DataFrame对象
pd_dataset = pd.DataFrame({
    
    
    "feature_1": [1,2,3],  # 创建一个名为feature_1的列,包含值1,2,3
    "feature_2": ["a", "b", "c"],  # 创建一个名为feature_2的列,包含值"a","b","c"
    "label": [0, 1, 0],  # 创建一个名为label的列,包含值0,1,0
})
feature_1 feature_2 Etikett
0 1 A 0
1 2 B 1
2 3 C 0
# 将Pandas数据集转换为TensorFlow数据集
tf_dataset = tfdf.keras.pd_dataframe_to_tf_dataset(pd_dataset, label="label")

# 遍历TensorFlow数据集中的每个样本
for features, label in tf_dataset:
  # 打印特征
  print("Features:", features)
  # 打印标签
  print("label:", label)
Features: {'feature_1': <tf.Tensor: shape=(3,), dtype=int64, numpy=array([1, 2, 3])>, 'feature_2': <tf.Tensor: shape=(3,), dtype=string, numpy=array([b'a', b'b', b'c'], dtype=object)>}
label: tf.Tensor([0 1 0], shape=(3,), dtype=int64)

Hinweis: „pd_“ steht für „Pandas“. „tf_“ steht für „TensorFlow“.

Ein TensorFlow-Datensatz ist eine Funktion, die eine Folge von Werten ausgibt. Die Werte können einfache Arrays (sogenannte Tensoren) oder in Strukturen organisierte Arrays (z. B. in einem Wörterbuch organisierte Arrays) sein.

predictDas folgende Beispiel zeigt den Prozess des Trainings und der Schlussfolgerung (Verwendung) eines Spielzeugdatensatzes :

# 创建一个Pandas的训练数据集
pd_train_dataset = pd.DataFrame({
    
    
    "feature_1": np.random.rand(1000),  # 创建一个包含1000个随机数的特征1列
    "feature_2": np.random.rand(1000),  # 创建一个包含1000个随机数的特征2列
})

# 添加一个标签列,标签值为特征1是否大于特征2的布尔值
pd_train_dataset["label"] = pd_train_dataset["feature_1"] > pd_train_dataset["feature_2"] 

# 返回创建的训练数据集
pd_train_dataset
feature_1 feature_2 Etikett
0 0,683035 0,952359 FALSCH
1 0,486641 0,669202 FALSCH
2 0,685580 0,967570 FALSCH
3 0,233815 0,725952 FALSCH
4 0,250187 0,503956 FALSCH
... ... ... ...
995 0,676669 0,043817 WAHR
996 0,564827 0,605345 FALSCH
997 0,996968 0,488901 WAHR
998 0,987390 0,097840 WAHR
999 0,692132 0,738431 FALSCH

1000 Zeilen × 3 Spalten

# 创建一个包含两个特征的数据集
pd_serving_dataset = pd.DataFrame({
    
    
    "feature_1": np.random.rand(500),  # 创建一个包含500个随机数的特征1列
    "feature_2": np.random.rand(500),  # 创建一个包含500个随机数的特征2列
})

# 输出数据集
pd_serving_dataset
feature_1 feature_2
0 0,326467 0,689151
1 0,807447 0,075198
2 0,095011 0,947676
3 0,851319 0,819100
4 0,488305 0,274047
... ... ...
495 0,480803 0,238047
496 0,633565 0,722966
497 0,945247 0,128379
498 0,267938 0,503427
499 0,185848 0,901847

500 Zeilen × 2 Spalten

Konvertieren wir den Pandas-Datenrahmen in einen TensorFlow-Datensatz:

# 将Pandas数据集转换为TensorFlow数据集
tf_train_dataset = tfdf.keras.pd_dataframe_to_tf_dataset(pd_train_dataset, label="label")

# 将Pandas数据集转换为用于模型服务的TensorFlow数据集
tf_serving_dataset = tfdf.keras.pd_dataframe_to_tf_dataset(pd_serving_dataset)

Wir können jetzt tf_train_datasetein Modell trainieren für:



# 创建一个RandomForestModel对象,并设置verbose参数为0(不显示训练过程的详细信息)
model = tfdf.keras.RandomForestModel(verbose=0)

# 使用tf_train_dataset数据集对模型进行训练
model.fit(tf_train_dataset)

WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.9/site-packages/tensorflow/python/autograph/pyct/static_analysis/liveness.py:83: Analyzer.lamba_check (from tensorflow.python.autograph.pyct.static_analysis.liveness) is deprecated and will be removed after 2023-09-23.
Instructions for updating:
Lambda fuctions will be no more assumed to be used in the statement where they are used, or at least in the same block. https://github.com/tensorflow/tensorflow/issues/56089


[INFO 2022-12-14T12:06:58.981628493+00:00 kernel.cc:1175] Loading model from path /tmpfs/tmp/tmp0b3hukdi/model/ with prefix 0234a68d9d6c49ee
[INFO 2022-12-14T12:06:59.017961685+00:00 abstract_model.cc:1306] Engine "RandomForestOptPred" built
[INFO 2022-12-14T12:06:59.017993244+00:00 kernel.cc:1021] Use fast generic engine


WARNING:tensorflow:AutoGraph could not transform <function simple_ml_inference_op_with_handle at 0x7f76793294c0> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: could not get source code
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING: AutoGraph could not transform <function simple_ml_inference_op_with_handle at 0x7f76793294c0> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: could not get source code
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert





<keras.callbacks.History at 0x7f76701969d0>

Generieren Sie dann tf_serving_datasetVorhersageergebnisse für:

# 使用模型对tf_serving_dataset进行预测,并打印出前10个预测结果
predictions = model.predict(tf_serving_dataset, verbose=0)[:10]
print(predictions)
array([[0.        ],
       [0.99999917],
       [0.        ],
       [0.29666647],
       [0.99999917],
       [0.        ],
       [0.99999917],
       [0.99999917],
       [0.99999917],
       [0.        ]], dtype=float32)

model.predict(...)und manueller TF-Datensatz

Im vorherigen Abschnitt haben wir gezeigt, wie man mit pd_dataframe_to_tf_datasetFunktionen einen TF-Datensatz erstellt. Diese Option ist einfach, aber für große Datenmengen nicht geeignet. Stattdessen bietet TensorFlow mehrere Optionen zum Erstellen eines TensorFlow-Datensatzes.
Das folgende Beispiel zeigt, wie tf.data.Dataset.from_tensor_slices()Funktionen zum Erstellen eines Datensatzes verwendet werden.

# 创建一个数据集对象,使用tf.data.Dataset.from_tensor_slices()方法,将一个列表[1,2,3,4,5]转换为数据集
dataset = tf.data.Dataset.from_tensor_slices([1,2,3,4,5])

# 遍历数据集中的每个元素
for value in dataset:
    # 打印当前元素的值,使用value.numpy()方法将Tensor对象转换为NumPy数组
    print("value:", value.numpy())
value: 1
value: 2
value: 3
value: 4
value: 5

TensorFlow-Modelle werden mithilfe eines Mini-Batch-Trainings trainiert: Anstatt die Proben einzeln einzugeben, werden sie in „Batches“ gruppiert. Bei neuronalen Netzen beeinflusst die Stapelgröße die Qualität des Modells, und der optimale Wert muss vom Benutzer während des Trainings ermittelt werden. Bei Entscheidungswäldern hat die Batchgröße keinen Einfluss auf das Modell. Aus Kompatibilitätsgründen erfordert TensorFlow Decision Forest jedoch, dass der Datensatz stapelweise verarbeitet wird . batch()Sie können die Funktion zur Stapelverarbeitung nutzen .

# 创建一个数据集对象,使用tf.data.Dataset.from_tensor_slices()方法,将一个列表[1,2,3,4,5]转换为数据集
# 使用batch()方法将数据集分成大小为2的批次
dataset = tf.data.Dataset.from_tensor_slices([1,2,3,4,5]).batch(2)

# 遍历数据集中的每个批次
for value in dataset:
    # 打印当前批次的值,使用numpy()方法将张量转换为numpy数组
    print("value:", value.numpy())
value: [1 2]
value: [3 4]
value: [5]

TensorFlow Decision Forest erwartet, dass der Datensatz eine von zwei Strukturen aufweist:

  • Funktionen, Etiketten
  • Merkmale, Etiketten, Gewichte

Features können ein zweidimensionales Array (wobei jede Spalte ein Feature und jede Zeile ein Beispiel ist) oder ein Array-Wörterbuch sein.

Hier ist ein Beispieldatensatz, der mit TensorFlow Decision Forest kompatibel ist:

# 创建一个包含单个2D数组的数据集
tf_dataset = tf.data.Dataset.from_tensor_slices(
    ([[1,2],[3,4],[5,6]], # 特征
    [0,1,0], # 标签
    )).batch(2)

# 遍历数据集中的每个批次
for features, label in tf_dataset:
  print("features:", features) # 打印特征
  print("label:", label) # 打印标签
features: tf.Tensor(
[[1 2]
 [3 4]], shape=(2, 2), dtype=int32)
label: tf.Tensor([0 1], shape=(2,), dtype=int32)
features: tf.Tensor([[5 6]], shape=(1, 2), dtype=int32)
label: tf.Tensor([0], shape=(1,), dtype=int32)
# 创建一个包含特征字典的数据集
tf_dataset = tf.data.Dataset.from_tensor_slices(
    ({
    
    
    "feature_1": [1,2,3], # 特征1
    "feature_2": [4,5,6], # 特征2
    },
    [0,1,0], # 标签
    )).batch(2) # 批量大小为2

# 遍历数据集中的每个批次
for features, label in tf_dataset:
  print("features:", features) # 打印特征字典
  print("label:", label) # 打印标签
features: {'feature_1': <tf.Tensor: shape=(2,), dtype=int32, numpy=array([1, 2], dtype=int32)>, 'feature_2': <tf.Tensor: shape=(2,), dtype=int32, numpy=array([4, 5], dtype=int32)>}
label: tf.Tensor([0 1], shape=(2,), dtype=int32)
features: {'feature_1': <tf.Tensor: shape=(1,), dtype=int32, numpy=array([3], dtype=int32)>, 'feature_2': <tf.Tensor: shape=(1,), dtype=int32, numpy=array([6], dtype=int32)>}
label: tf.Tensor([0], shape=(1,), dtype=int32)

Lassen Sie uns die zweite Option verwenden, um ein Modell zu trainieren.

# 导入必要的库已经完成,不需要再添加import语句
# 生成一个包含两个特征和一个标签的数据集
# 特征1和特征2都是100个随机数
# 标签是一个100个元素的布尔型数组,每个元素都是随机生成的,大于等于0.5为True,小于0.5为False
tf_dataset = tf.data.Dataset.from_tensor_slices(
    ({
    
    
    "feature_1": np.random.rand(100),
    "feature_2": np.random.rand(100),
    },
    np.random.rand(100) >= 0.5, # Label
    )).batch(2)

# 创建一个随机森林模型
# verbose=0表示不输出训练过程中的详细信息
model = tfdf.keras.RandomForestModel(verbose=0)

# 使用生成的数据集进行训练
model.fit(tf_dataset)
[INFO 2022-12-14T12:07:00.416575763+00:00 kernel.cc:1175] Loading model from path /tmpfs/tmp/tmpvzrrxxmw/model/ with prefix 0bc6f955d2d1456e
[INFO 2022-12-14T12:07:00.440516186+00:00 kernel.cc:1021] Use fast generic engine





<keras.callbacks.History at 0x7f75f016e220>

predictFunktionen können direkt auf dem Trainingsdatensatz verwendet werden:

# 使用模型对tf_dataset进行预测,verbose=0表示不显示进度条
# 返回结果为前10个预测值
model.predict(tf_dataset, verbose=0)[:10]
array([[0.43666634],
       [0.58999956],
       [0.42999968],
       [0.73333275],
       [0.75666606],
       [0.20666654],
       [0.67666614],
       [0.66666615],
       [0.82333267],
       [0.3999997 ]], dtype=float32)

model.predict(...)und model.predict_on_batch()Verwendung in Wörterbüchern

In einigen Fällen ist es möglich, Funktionen zu verwenden, die Arrays (oder Wörterbücher von Arrays) anstelle von TensorFlow-Datensätzen verwenden predict.

Das folgende Beispiel verwendet ein zuvor trainiertes Modell und ein Wörterbuch mit NumPy-Arrays.

# 使用模型对输入数据进行预测,返回前10个预测结果
model.predict({
    
    
    "feature_1": np.random.rand(100),
    "feature_2": np.random.rand(100),
    }, verbose=0)[:10]
array([[0.6533328 ],
       [0.5399996 ],
       [0.2133332 ],
       [0.22999986],
       [0.16333325],
       [0.18333323],
       [0.3766664 ],
       [0.5066663 ],
       [0.20333321],
       [0.8633326 ]], dtype=float32)

Im vorherigen Beispiel wurde das Array automatisch gestapelt. Alternativ können Sie predict_on_batcheine Funktion verwenden, um sicherzustellen, dass alle Beispiele im selben Batch ausgeführt werden.

# 获取前10个预测结果
model.predict_on_batch({
    
    
    "feature_1": np.random.rand(100),
    "feature_2": np.random.rand(100),
    })[:10]
array([[0.54666626],
       [0.21666653],
       [0.18333323],
       [0.5299996 ],
       [0.5499996 ],
       [0.12666662],
       [0.6299995 ],
       [0.06000001],
       [0.33999977],
       [0.08999998]], dtype=float32)

**Hinweis:** Wenn predictes bei Rohdaten nicht funktioniert, wie im obigen Beispiel, versuchen Sie es mit predict_on_batcheiner Funktion oder der Konvertierung der Rohdaten in einen TensorFlow-Datensatz.

Verwendung des YDF-Formats zur Inferenz

Dieses Beispiel zeigt, wie ein trainiertes TF-DF-Modell mithilfe der CLI-API ( einer der anderen Serving-APIs ) ausgeführt wird. Wir werden auch das Benchmark-Tool verwenden, um die Inferenzgeschwindigkeit des Modells zu messen.

Lassen Sie uns zunächst ein Modell trainieren und speichern:

# 创建一个梯度提升树模型对象,verbose参数设置为0表示不输出训练过程的详细信息
model = tfdf.keras.GradientBoostedTreesModel(verbose=0)

# 将pandas的训练数据集转换为TensorFlow的数据集,并指定"label"列作为标签
train_dataset = tfdf.keras.pd_dataframe_to_tf_dataset(pd_train_dataset, label="label")

# 使用转换后的训练数据集来训练模型
model.fit(train_dataset)

# 将训练好的模型保存到文件中
model.save("my_model")
2022-12-14 12:07:00.950798: W external/ydf/yggdrasil_decision_forests/learner/gradient_boosted_trees/gradient_boosted_trees.cc:1765] Subsample hyperparameter given but sampling method does not match.
2022-12-14 12:07:00.950839: W external/ydf/yggdrasil_decision_forests/learner/gradient_boosted_trees/gradient_boosted_trees.cc:1778] GOSS alpha hyperparameter given but GOSS is disabled.
2022-12-14 12:07:00.950846: W external/ydf/yggdrasil_decision_forests/learner/gradient_boosted_trees/gradient_boosted_trees.cc:1787] GOSS beta hyperparameter given but GOSS is disabled.
2022-12-14 12:07:00.950852: W external/ydf/yggdrasil_decision_forests/learner/gradient_boosted_trees/gradient_boosted_trees.cc:1799] SelGB ratio hyperparameter given but SelGB is disabled.
[INFO 2022-12-14T12:07:01.160357659+00:00 kernel.cc:1175] Loading model from path /tmpfs/tmp/tmpo37712qo/model/ with prefix 391746915b7842cb
[INFO 2022-12-14T12:07:01.164736847+00:00 kernel.cc:1021] Use fast generic engine
WARNING:absl:Found untraced functions such as call_get_leaves, _update_step_xla while saving (showing 2 of 2). These functions will not be directly callable after loading.


INFO:tensorflow:Assets written to: my_model/assets


INFO:tensorflow:Assets written to: my_model/assets

Exportieren wir den Datensatz auch in eine CSV-Datei:

# 将pd_serving_dataset保存为dataset.csv文件
pd_serving_dataset.to_csv("dataset.csv")

Laden wir das CLI-Tool für Yggdrasil Decision Forests herunter und extrahieren es .

# 下载 Yggdrasil Decision Forests 的命令行工具
!wget https://github.com/google/yggdrasil-decision-forests/releases/download/1.0.0/cli_linux.zip

# 解压缩下载的文件
!unzip cli_linux.zip
--2022-12-14 12:07:01--  https://github.com/google/yggdrasil-decision-forests/releases/download/1.0.0/cli_linux.zip
Resolving github.com (github.com)... 140.82.114.3
Connecting to github.com (github.com)|140.82.114.3|:443... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://objects.githubusercontent.com/github-production-release-asset-2e65be/360444739/bfcd0b9d-5cbc-42a8-be0a-02131875f9a6?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20221214%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20221214T120701Z&X-Amz-Expires=300&X-Amz-Signature=94e7b8fd2c219cbe6305222b34f566360eb9fea8ea35e8303519f09b04744b93&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=360444739&response-content-disposition=attachment%3B%20filename%3Dcli_linux.zip&response-content-type=application%2Foctet-stream [following]
--2022-12-14 12:07:01--  https://objects.githubusercontent.com/github-production-release-asset-2e65be/360444739/bfcd0b9d-5cbc-42a8-be0a-02131875f9a6?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20221214%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20221214T120701Z&X-Amz-Expires=300&X-Amz-Signature=94e7b8fd2c219cbe6305222b34f566360eb9fea8ea35e8303519f09b04744b93&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=360444739&response-content-disposition=attachment%3B%20filename%3Dcli_linux.zip&response-content-type=application%2Foctet-stream
Resolving objects.githubusercontent.com (objects.githubusercontent.com)... 185.199.111.133, 185.199.110.133, 185.199.109.133, ...
Connecting to objects.githubusercontent.com (objects.githubusercontent.com)|185.199.111.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 31516027 (30M) [application/octet-stream]
Saving to: ‘cli_linux.zip’


cli_linux.zip         0%[                    ]       0  --.-KB/s               
cli_linux.zip         2%[                    ] 727.40K  3.47MB/s               
cli_linux.zip        13%[=>                  ]   4.01M  9.90MB/s               
cli_linux.zip        53%[=========>          ]  16.01M  26.1MB/s               
cli_linux.zip       100%[===================>]  30.06M  38.2MB/s    in 0.8s    

2022-12-14 12:07:03 (38.2 MB/s) - ‘cli_linux.zip’ saved [31516027/31516027]

Archive:  cli_linux.zip
  inflating: README                  
  inflating: cli.txt                 
  inflating: train                   
  inflating: show_model              
  inflating: show_dataspec           
  inflating: predict                 
  inflating: infer_dataspec          
  inflating: evaluate                
  inflating: convert_dataset         
  inflating: benchmark_inference     
  inflating: edit_model              
  inflating: synthetic_dataset       
  inflating: grpc_worker_main        
  inflating: LICENSE                 
  inflating: CHANGELOG.md            

Lassen Sie uns abschließend Vorhersagen treffen:

Anmerkung:

  • TensorFlow Decision Forest (TF-DF) basiert auf der Yggdrasil Decision Forest (YDF)-Bibliothek und TF-DF-Modelle enthalten intern immer ein YDF-Modell. Beim Speichern eines TF-DF-Modells auf der Festplatte enthält das TF-DF-Modellverzeichnis ein assetsUnterverzeichnis mit dem YDF-Modell. Dieses YDF-Modell funktioniert mit allen YDF-Tools . Im nächsten Beispiel verwenden wir die Werkzeuge predictund benchmark_inference. Weitere Einzelheiten finden Sie in der Dokumentation zum Modellformat .
  • Das YDF-Tool geht davon aus, dass der Typ des Datensatzes über ein Präfix angegeben wird, z. B. csv:. Weitere Einzelheiten finden Sie im YDF-Benutzerhandbuch .
# 该代码是用于执行预测的脚本

# 导入必要的库

# 执行预测
# 使用"./predict"命令来执行预测
# "--model=my_model/assets"参数指定了模型的路径
# "--dataset=csv:dataset.csv"参数指定了数据集的路径和格式
# "--output=csv:predictions.csv"参数指定了预测结果的输出路径和格式
!./predict --model=my_model/assets --dataset=csv:dataset.csv --output=csv:predictions.csv
[INFO abstract_model.cc:1296] Engine "GradientBoostedTreesQuickScorerExtended" built
[INFO predict.cc:133] Run predictions with semi-fast engine

Wir können nun einen Blick auf die Vorhersagen werfen:

# 读取CSV文件"predictions.csv"并将其存储为一个DataFrame对象
data = pd.read_csv("predictions.csv")
1 2
0 0,966779 0,033221
1 0,031773 0,968227
2 0,966779 0,033221
3 0,600073 0,399927
4 0,030885 0,969115
... ... ...
495 0,030885 0,969115
496 0,948252 0,051748
497 0,031773 0,968227
498 0,966996 0,033004
499 0,966779 0,033221

500 Zeilen × 2 Spalten

Die Inferenzgeschwindigkeit eines Modells kann mithilfe von Benchmark-Inferenztools gemessen werden .

**Hinweis:** Vor YDF-Version 1.1.0 musste der für die Basislinieninferenz verwendete Datensatz eine __LABELSpalte haben.

# 创建一个空的标签列
pd_serving_dataset["__LABEL"] = 0

# 将数据集保存为csv文件
pd_serving_dataset.to_csv("dataset.csv")
# 运行benchmark_inference脚本进行推理性能测试

# 参数说明:
# --model:指定模型的路径,这里是my_model/assets
# --dataset:指定数据集的路径和格式,这里是csv:dataset.csv,表示数据集是以csv格式存储在dataset.csv文件中
# --batch_size:指定每个推理批次的大小,这里是100
# --warmup_runs:指定预热运行的次数,用于消除冷启动的影响,这里是10次
# --num_runs:指定总共运行的次数,用于统计平均推理性能,这里是50次
!./benchmark_inference \
  --model=my_model/assets \
  --dataset=csv:dataset.csv \
  --batch_size=100 \
  --warmup_runs=10 \
  --num_runs=50
[INFO benchmark_inference.cc:245] Loading model
[INFO benchmark_inference.cc:248] The model is of type: GRADIENT_BOOSTED_TREES
[INFO benchmark_inference.cc:250] Loading dataset
[INFO benchmark_inference.cc:259] Found 3 compatible fast engines.
[INFO benchmark_inference.cc:262] Running GradientBoostedTreesGeneric
[INFO decision_forest.cc:639] Model loaded with 27 root(s), 1471 node(s), and 2 input feature(s).
[INFO benchmark_inference.cc:262] Running GradientBoostedTreesQuickScorerExtended
[INFO benchmark_inference.cc:262] Running GradientBoostedTreesOptPred
[INFO decision_forest.cc:639] Model loaded with 27 root(s), 1471 node(s), and 2 input feature(s).
[INFO benchmark_inference.cc:268] Running the slow generic engine
batch_size : 100  num_runs : 50
time/example(us)  time/batch(us)  method
----------------------------------------
         0.22425          22.425  GradientBoostedTreesOptPred [virtual interface]
          0.2465           24.65  GradientBoostedTreesQuickScorerExtended [virtual interface]
          0.6875           68.75  GradientBoostedTreesGeneric [virtual interface]
           1.825           182.5  Generic slow engine
----------------------------------------

In diesem Benchmark können wir die Inferenzgeschwindigkeit verschiedener Inferenz-Engines sehen. Beispielsweise bedeutet „Zeit/Beispiel(us) = 0,6315“ (was von Lauf zu Lauf variieren kann), dass die Inferenz eines Beispiels 0,63 Mikrosekunden dauert. Mit anderen Worten: Das Modell kann etwa 1,6 Millionen Mal pro Sekunde ausgeführt werden.

**Hinweis:** TF-DF und andere APIs wählen immer automatisch die schnellste verfügbare Inferenz-Engine aus.

Guess you like

Origin blog.csdn.net/wjjc1017/article/details/135189626