首頁  >  文章  >  後端開發  >  如何使用TensorFlow Serving在Python中部署模型?

如何使用TensorFlow Serving在Python中部署模型?

王林
王林轉載
2023-09-07 23:09:02752瀏覽

如何使用TensorFlow Serving在Python中部署模型?

部署機器學習模型對於使人工智慧應用程式發揮作用至關重要,為了在生產環境中有效地服務模型,TensorFlow Serving 提供了可靠的解決方案。當模型經過訓練並準備部署時,有效地為其提供服務以處理即時請求至關重要。 TensorFlow Serving 是一個強大的工具,有助於在生產環境中順利部署機器學習模式。

在本文中,我們將深入研究使用 TensorFlow Serving 在 Python 中部署模型所涉及的步驟。

什麼是模型部署?

模型部署涉及使經過訓練的機器學習模型可用於即時預測。這意味著將模型從開發環境轉移到生產系統,在那裡它可以有效地處理傳入的請求。 TensorFlow Serving 是專為部署機器學習模型而設計的專用高效能係統。

設定 TensorFlow 服務

首先,我們需要在我們的系統上安裝 TensorFlow Serving。請依照下列步驟設定 TensorFlow Serving -

第 1 步:安裝 TensorFlow Serving

首先使用套件管理器 pip 安裝 TensorFlow Serving。開啟命令提示字元或終端機並輸入以下命令 -

pip install tensorflow-serving-api

第 2 步:啟動 TensorFlow 服務伺服器

安裝後,透過執行下列指令啟動 TensorFlow Serving 伺服器 -

tensorflow_model_server --rest_api_port=8501 --model_name=my_model --model_base_path=/path/to/model/directory

`/path/to/model/directory` 替換為儲存訓練模型的路徑。

準備部署模型

在部署模型之前,需要將其儲存為 TensorFlow Serving 可以理解的格式。請按照以下步驟準備您的模型進行部署 -

以 SavedModel 格式儲存模型

在Python腳本中,使用以下程式碼將訓練後的模型儲存為SavedModel格式 -

import tensorflow as tf

# Assuming `model` is your trained TensorFlow model
tf.saved_model.save(model, '/path/to/model/directory')

定義模型簽章

模型簽章提供有關模型輸入和輸出張量的資訊。使用 `tf.saved_model.signature_def_utils.build_signature_def` 函數定義模型簽章。這是一個例子 -

inputs = {'input': tf.saved_model.utils.build_tensor_info(model.input)}
outputs = {'output': tf.saved_model.utils.build_tensor_info(model.output)}

signature = tf.saved_model.signature_def_utils.build_signature_def(
   inputs=inputs,
   outputs=outputs,
   method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME
)

使用簽名保存模型

要將模型與簽名一起儲存,請使用以下程式碼 -

builder = tf.saved_model.builder.SavedModelBuilder('/path/to/model/directory')
builder.add_meta_graph_and_variables(
   sess=tf.keras.backend.get_session(),
   tags=[tf.saved_model.tag_constants.SERVING],
   signature_def_map={
      tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: signature
   }
)
builder.save

()

使用 TensorFlow Serving 為模型提供服務

現在我們的模型已準備就緒,是時候使用 TensorFlow Serving 為其提供服務了。請依照以下步驟操作 -

與 TensorFlow Serving 建立連線

在Python腳本中,使用gRPC協定與TensorFlow Serving建立連線。這是一個例子 -

from tensorflow_serving.apis import predict_pb2
from tensorflow_serving.apis import prediction_service_pb2_grpc

channel = grpc.insecure_channel('localhost:8501')
stub = prediction_service_pb2_grpc.PredictionServiceStub(channel)

建立請求

要進行預測,請建立請求 protobuf 訊息並指定模型名稱和簽章名稱。這是一個例子 -

request = predict_pb2.PredictRequest()
request.model_spec.name = 'my_model'
request.model_spec.signature_name = tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
request.inputs['input'].CopyFrom(tf.contrib.util.make_tensor_proto(data, shape=data.shape))

`data` 替換為您要進行預測的輸入資料。

發送請求並獲取回應

將請求傳送到 TensorFlow Serving 並檢索回應。這是一個例子 -

response = stub.Predict(request, timeout_seconds)
output = tf.contrib.util.make_ndarray(response.outputs['output'])

`timeout_seconds`參數指定等待回應的最長時間。

測試部署的模型

為了確保部署的模型正常運行,必須使用範例輸入對其進行測試。以下是測試已部署模型的方法 -

準備範例資料

建立一組與模型的預期輸入格式相符的範例輸入資料。

向已部署的模型發送請求

建立請求並將其傳送到已部署的模型。

request = predict_pb2.PredictRequest()
request.model_spec.name = 'my_model'
request.model_spec.signature_name = tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
request.inputs['input'].CopyFrom(tf.contrib.util.make_tensor_proto(data, shape=data.shape))

評估輸出

將從已部署模型收到的輸出與預期輸出進行比較。此步驟可確保模型做出準確的預測。

擴充與監控部署

隨著預測需求的增加,擴展部署以處理大量傳入請求至關重要。此外,監控部署有助於追蹤已部署模型的效能和運作狀況。考慮實施以下擴展和監控策略 -

縮放

  • 使用 TensorFlow Serving 的多個執行個體進行負載平衡。

  • 使用 Docker 和 Kubernetes 等平台進行容器化。

監控

  • 收集請求延遲、錯誤率和吞吐量等指標。

  • 設定關鍵事件的警報和通知。

範例

下面的程式範例展示如何使用 TensorFlow 服務部署模型 -

import tensorflow as tf
from tensorflow import keras

# Load the trained model
model = keras.models.load_model("/path/to/your/trained/model")

# Convert the model to the TensorFlow SavedModel format
export_path = "/path/to/exported/model"
tf.saved_model.save(model, export_path)

# Start the TensorFlow Serving server
import os
os.system("tensorflow_model_server --port=8501 --model_name=your_model --model_base_path={}".format(export_path))

在上面的範例中,您需要將“/path/to/your/trained/model”替換為訓練模型的實際路徑。模型將使用 Keras 的 load_model() 函數載入。

接下來,模型將轉換為 TensorFlow SavedModel 格式並儲存在指定的匯出路徑中。

接著使用os.system()函數啟動TensorFlow Serving伺服器,函數執行tensorflow_model_server指令。此命令指定伺服器連接埠、模型名稱 (your_model) 以及匯出模型所在的基本路徑。

請確保您已安裝 TensorFlow Serving,並將檔案路徑替換為適合您系統的值。

期望的輸出

伺服器成功啟動後,它將準備好提供預測服務。您可以使用其他程式或 API 向伺服器發送預測請求,伺服器將根據載入的模型以預測輸出進行回應。

結論

總之,在生產環境中部署機器學習模型以利用其預測能力非常重要。在本文中,我們探討了使用 TensorFlow Serving 在 Python 中部署模型的流程。我們討論了 TensorFlow Serving 的安裝、準備部署模型、服務模型以及測試其效能。透過以下步驟,我們可以成功部署TensorFlow模型並做出精確的即時預測。

以上是如何使用TensorFlow Serving在Python中部署模型?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除