在本地部署模型

了解如何使用 Azure 机器学习将模型部署为 Azure 机器学习计算实例上的 Web 服务。 如果满足下列任一条件,请使用计算实例:

  • 你需要快速部署并验证你的模型。
  • 正在测试一个开发中的模型。

提示

将模型从计算实例上的 Jupyter Notebook 部署到同一 VM 上的 Web 服务是本地部署。 在这种情况下,“本地”计算机是计算实例。

注意

Azure 机器学习终结点 (v2) 提供了经过改进的简化部署体验。 终结点同时支持实时和批量推理场景。 终结点提供了一个统一的接口,以用于跨计算类型调用和管理模型部署。 请参阅什么是 Azure 机器学习终结点?

先决条件

部署到计算实例

用于演示本地部署的示例笔记本包含在计算实例中。 使用以下步骤加载笔记本,并将模型部署为 VM 上的 Web 服务:

  1. Azure 机器学习工作室中,选择“笔记本”,然后在“示例笔记本”下选择 "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;

    • 笔记本 VM:https://<vm_name>-<local_service_port>.<azure_region_of_workspace>.notebooks.ml.azure.cn/score
    • 计算实例:https://<vm_name>-<local_service_port>.<azure_region_of_workspace>.instances.ml.azure.cn/score

    例如,

    • 笔记本 VM:https://vm-name-6789.chinaeast2.notebooks.ml.azure.cn/score
    • 计算实例:https://vm-name-6789.chinaeast2.instances.ml.azure.cn/score

测试服务

若要将示例数据提交到正在运行的服务,请使用以下代码。 将 service_url 值替换为在上一步获取的 URL:

注意

对计算实例上的部署进行身份验证时,将使用 Azure Active Directory 进行身份验证。 对示例代码中 interactive_auth.get_authentication_header() 的调用将使用 AAD 对你进行身份验证,并返回一个标头,然后可使用该标头向计算实例上的服务进行身份验证。 有关详细信息,请参阅为 Azure 机器学习资源和工作流设置身份验证

对 Azure Kubernetes 服务或 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.chinaeast2.notebooks.ml.azure.cn/score"
# for a compute instance, the url would be https://vm-name-6789.chinaeast2.instances.ml.azure.cn/score
resp = requests.post(service_url, test_sample, headers=headers)
print("prediction:", resp.text)

后续步骤