在本機部署模型

了解如何使用 Azure Machine Learning 將模型部署為 Azure Machine Learning 計算執行個體上的 Web 服務。 如果下列其中一個條件成立,請使用計算執行個體:

  • 您需要快速部署及驗證模型。
  • 您正在測試處於開發狀態的模型。

提示

將模型從計算執行個體上的 Jupyter Notebook 部署到相同 VM 上的 Web 服務是本機部署。 在此情況下,「本機」電腦是計算執行個體。

注意

Azure Machine Learning 端點 (v2) 提供經過改良且更簡單的部署體驗。 端點同時支援即時和 Batch 推斷案例。 端點會提供整合介面,以叫用和管理跨計算類型的模型部署。 請參閱什麼是 Azure Machine Learning 端點?

必要條件

  • 執行計算執行個體的 Azure Machine Learning 工作區。 如需詳細資訊,請參閱建立資源以開始

部署至計算執行個體

您的計算執行個體上包含了示範本機部署的範例筆記本。 使用下列步驟來載入筆記本,並在 VM 上將模型部署為 Web 服務:

  1. Azure Machine Learning 工作室,選取 [筆記本],然後選取 [範例筆記本] 下的 how-to-use-azureml/deployment/deploy-to-local/register-model-deploy-local.ipynb。 將此筆記本複製到您的使用者資料夾。

  2. 尋找在步驟 1 中複製的筆記本,選擇或建立計算執行個體以執行筆記本。

    Screenshot of the running local service on notebook

  3. 筆記本會顯示服務執行所在的 URL 和連接埠。 例如: https://localhost:6789 。 您也可以執行包含 print('Local service port: {}'.format(local_service.port)) 的儲存格來顯示連接埠。

    Screenshot of the running local service port

  4. 若要從計算執行個體測試服務,請使用 https://localhost:<local_service.port> URL。 若要從遠端用戶端進行測試,請取得在計算執行個體上所執行服務的公用 URL。 您可以使用下列公式來判斷公用 URL;

    • Notebook VM:https://<vm_name>-<local_service_port>.<azure_region_of_workspace>.notebooks.azureml.net/score
    • 計算執行個體:https://<vm_name>-<local_service_port>.<azure_region_of_workspace>.instances.azureml.net/score

    例如,

    • Notebook VM:https://vm-name-6789.northcentralus.notebooks.azureml.net/score
    • 計算執行個體:https://vm-name-6789.northcentralus.instances.azureml.net/score

測試服務

若要將範例資料提交至正在執行的服務,請使用下列程式碼。 將 service_url 的值取代為上一個步驟中的 URL:

注意

對計算執行個體上的部署進行驗證時,會使用 Microsoft Entra ID 來進行驗證。 範例程式碼中對 interactive_auth.get_authentication_header() 的呼叫會使用 Microsoft Entra ID 來驗證您,並傳回可接著用來對計算執行個體上的服務進行驗證的標頭。 如需詳細資訊,請參閱設定 Azure Machine Learning 資源和工作流程的驗證

對 Azure Kubernetes Service 或 Azure 容器執行個體上的部署進行驗證時,會使用不同的驗證方法。 如需詳細資訊,請參閱部署為 Web 服務的 Azure 機器模型設定驗證

import requests
import json
from azureml.core.authentication import InteractiveLoginAuthentication

# Get a token to authenticate to the compute instance from remote
interactive_auth = InteractiveLoginAuthentication()
auth_header = interactive_auth.get_authentication_header()

# Create and submit a request using the auth header
headers = auth_header
# Add content type header
headers.update({'Content-Type':'application/json'})

# Sample data to send to the service
test_sample = json.dumps({'data': [
    [1,2,3,4,5,6,7,8,9,10],
    [10,9,8,7,6,5,4,3,2,1]
]})
test_sample = bytes(test_sample,encoding = 'utf8')

# Replace with the URL for your compute instance, as determined from the previous section
service_url = "https://vm-name-6789.northcentralus.notebooks.azureml.net/score"
# for a compute instance, the url would be https://vm-name-6789.northcentralus.instances.azureml.net/score
resp = requests.post(service_url, test_sample, headers=headers)
print("prediction:", resp.text)

下一步