如何使用 Azure 机器学习工作室(经典版)Web 服务How to consume an Azure Machine Learning Studio (classic) web service

适用于: yes机器学习工作室(经典) noAzure 机器学习APPLIES TO: yesMachine Learning Studio (classic) noAzure Machine Learning

将 Azure 机器学习工作室(经典版)预测模型部署为 Web 服务后,可以使用 REST API 向其发送数据并获取预测。Once you deploy an Azure Machine Learning Studio (classic) predictive model as a Web service, you can use a REST API to send it data and get predictions. 可以实时或者以批处理模式发送数据。You can send the data in real-time or in batch mode.

可以在以下位置查找有关如何使用机器学习工作室(经典版)创建和部署机器学习 Web 服务的详细信息:You can find more information about how to create and deploy a Machine Learning Web service using Machine Learning Studio (classic) here:

概述Overview

外部应用程序可使用 Azure 机器学习 Web 服务实时与机器学习服务工作流评分模型通信。With the Azure Machine Learning Web service, an external application communicates with a Machine Learning workflow scoring model in real time. 机器学习 Web 服务调用将预测结果返回到外部应用程序。A Machine Learning Web service call returns prediction results to an external application. 若要执行机器学习 Web 服务调用,可以传递部署 Web 服务时创建的 API 密钥。To make a Machine Learning Web service call, you pass an API key that is created when you deploy a prediction. 机器学习 Web 服务基于 REST(流行的 Web 编程项目体系结构)。The Machine Learning Web service is based on REST, a popular architecture choice for web programming projects.

Azure 机器学习工作室(经典版)有两种类型的服务:Azure Machine Learning Studio (classic) has two types of services:

  • 请求响应服务 (RRS) - 低延迟、高度可缩放的服务,针对从机器学习工作室(经典版)创建和部署的无状态模型提供接口。Request-Response Service (RRS) – A low latency, highly scalable service that provides an interface to the stateless models created and deployed from the Machine Learning Studio (classic).
  • 批处理执行服务 (BES) - 为一批数据记录进行评分的异步服务。Batch Execution Service (BES) – An asynchronous service that scores a batch for data records.

有关机器学习 Web 服务的详细信息,请参阅 Deploy a Machine Learning Web service(部署机器学习 Web 服务)。For more information about Machine Learning Web services, see Deploy a Machine Learning Web service.

获取授权密钥Get an authorization key

部署实验时,会为 Web 服务生成 API 密钥。When you deploy your experiment, API keys are generated for the Web service. 可从多个位置检索密钥。You can retrieve the keys from several locations.

从 Microsoft Azure 机器学习 Web 服务门户检索From the Microsoft Azure Machine Learning Web Services portal

登录到 Microsoft Azure 机器学习 Web 服务门户。Sign in to the Microsoft Azure Machine Learning Web Services portal.

为新的机器学习 Web 服务检索 API 密钥:To retrieve the API key for a New Machine Learning Web service:

  1. 在 Azure 机器学习 Web 服务门户中,单击“Web 服务” 顶部菜单。In the Azure Machine Learning Web Services portal, click Web Services the top menu.
  2. 单击想要为其检索密钥的 Web 服务。Click the Web service for which you want to retrieve the key.
  3. 单击顶部菜单上的“使用” 。On the top menu, click Consume.
  4. 复制并保存“主密钥” 。Copy and save the Primary Key.

为经典机器学习 Web 服务检索 API 密钥:To retrieve the API key for a Classic Machine Learning Web service:

  1. 在 Azure 机器学习 Web 服务门户中,单击“经典 Web 服务” 顶部菜单。In the Azure Machine Learning Web Services portal, click Classic Web Services the top menu.
  2. 单击正在使用的 Web 服务。Click the Web service with which you are working.
  3. 单击想要为其检索密钥的终结点。Click the endpoint for which you want to retrieve the key.
  4. 单击顶部菜单上的“使用” 。On the top menu, click Consume.
  5. 复制并保存“主密钥” 。Copy and save the Primary Key.

经典 Web 服务Classic Web service

还可以从机器学习工作室(经典版)来检索经典 Web 服务的密钥。You can also retrieve a key for a Classic Web service from Machine Learning Studio (classic).

机器学习工作室(经典版)Machine Learning Studio (classic)

  1. 在机器学习工作室(经典版)左侧,单击“Web 服务” 。In Machine Learning Studio (classic), click WEB SERVICES on the left.
  2. 单击一个 Web 服务。Click a Web service. “API 密钥” 位于“仪表板” 选项卡。The API key is on the DASHBOARD tab.

连接到机器学习 Web 服务Connect to a Machine Learning Web service

可使用支持 HTTP 请求和响应的编程语言连接到机器学习 Web 服务。You can connect to a Machine Learning Web service using any programming language that supports HTTP request and response. 可从机器学习 Web 服务帮助页,查看 C#、Python 和 R 示例。You can view examples in C#, Python, and R from a Machine Learning Web service help page.

机器学习 API 帮助部署 Web 服务时会创建机器学习 API 帮助。Machine Learning API help Machine Learning API help is created when you deploy a Web service. 请参阅教程 3:部署信用风险模型See Tutorial 3: Deploy credit risk model. 机器学习 API 帮助包含有关预测 Web 服务的详细信息。The Machine Learning API help contains details about a prediction Web service.

  1. 单击正在使用的 Web 服务。Click the Web service with which you are working.
  2. 单击想要为其查看 API 帮助页的终结点。Click the endpoint for which you want to view the API Help Page.
  3. 单击顶部菜单上的“使用” 。On the top menu, click Consume.
  4. 在请求响应或批处理执行终结点下方单击“API 帮助页” 。Click API help page under either the Request-Response or Batch Execution endpoints.

查看新 Web 服务的机器学习 API 帮助To view Machine Learning API help for a New Web service

Azure 机器学习 Web 服务门户In the Azure Machine Learning Web Services Portal:

  1. 在顶部菜单单击“WEB 服务” 。Click WEB SERVICES on the top menu.
  2. 单击想要为其检索密钥的 Web 服务。Click the Web service for which you want to retrieve the key.

单击“使用 Web 服务” 获取请求响应和批处理执行服务以及 C#、R 和 Python 示例代码的 URI。Click Use Web Service to get the URIs for the Request-Response and Batch Execution Services and Sample code in C#, R, and Python.

单击“Swagger API” 从提供的 URI 为调用的 API 获取基于 Swagger 的文档。Click Swagger API to get Swagger based documentation for the APIs called from the supplied URIs.

C# 示例C# Sample

若要连接到机器学习 Web 服务,请使用 HttpClient 传递 ScoreData。To connect to a Machine Learning Web service, use an HttpClient passing ScoreData. ScoreData 包含 FeatureVector以及表示 ScoreData 的具有数字特征的 N 维向量。ScoreData contains a FeatureVector, an n-dimensional vector of numerical features that represents the ScoreData. 使用 API 密钥对机器学习服务进行身份验证。You authenticate to the Machine Learning service with an API key.

若要连接到机器学习 Web 服务,必须安装 Microsoft.AspNet.WebApi.Client NuGet 包。To connect to a Machine Learning Web service, the Microsoft.AspNet.WebApi.Client NuGet package must be installed.

在 Visual Studio 中安装 Microsoft.AspNet.WebApi.Client NuGetInstall Microsoft.AspNet.WebApi.Client NuGet in Visual Studio

  1. 从 UCI 发布下载数据集:成人 2 类数据集 Web 服务。Publish the Download dataset from UCI: Adult 2 class dataset Web Service.
  2. 单击“工具” > “NuGet 包管理器” > “包管理器控制台” 。Click Tools > NuGet Package Manager > Package Manager Console.
  3. 选择 Microsoft.AspNet.WebApi.Client 安装包Choose Install-Package Microsoft.AspNet.WebApi.Client.

运行代码示例To run the code sample

  1. 发布“示例 1:从 UCI 下载数据集:成人 2 类数据集”实验(机器学习示例集合的一部分)。Publish "Sample 1: Download dataset from UCI: Adult 2 class dataset" experiment, part of the Machine Learning sample collection.
  2. 使用 Web 服务密钥分配 API 密钥。Assign apiKey with the key from a Web service. 请参阅上面的获取授权密钥See Get an authorization key above.
  3. 使用请求 URI 分配服务 URI。Assign serviceUri with the Request URI.

以下是完整请求的示例。Here is what a complete request will look like.

using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace CallRequestResponseService
{
    class Program
    {
        static void Main(string[] args)
        {
            InvokeRequestResponseService().Wait();
        }

        static async Task InvokeRequestResponseService()
        {
            using (var client = new HttpClient())
            {
                var scoreRequest = new
                {
                    Inputs = new Dictionary<string, List<Dictionary<string, string>>> () {
                        {
                            "input1",
                            // Replace columns labels with those used in your dataset
                            new List<Dictionary<string, string>>(){new Dictionary<string, string>(){
                                    {
                                        "column1", "value1"
                                    },
                                    {
                                        "column2", "value2"
                                    },
                                    {
                                        "column3", "value3"
                                    }
                                }
                            }
                        },
                    },
                    GlobalParameters = new Dictionary<string, string>() {}
                };

                // Replace these values with your API key and URI found on https://services.azureml.net/
                const string apiKey = "<your-api-key>"; 
                const string apiUri = "<your-api-uri>";
                
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Bearer", apiKey);
                client.BaseAddress = new Uri(apiUri);

                // WARNING: The 'await' statement below can result in a deadlock
                // if you are calling this code from the UI thread of an ASP.NET application.
                // One way to address this would be to call ConfigureAwait(false)
                // so that the execution does not attempt to resume on the original context.
                // For instance, replace code such as:
                //      result = await DoSomeTask()
                // with the following:
                //      result = await DoSomeTask().ConfigureAwait(false)

                HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest);

                if (response.IsSuccessStatusCode)
                {
                    string result = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("Result: {0}", result);
                }
                else
                {
                    Console.WriteLine(string.Format("The request failed with status code: {0}", response.StatusCode));

                    // Print the headers - they include the request ID and the timestamp,
                    // which are useful for debugging the failure
                    Console.WriteLine(response.Headers.ToString());

                    string responseContent = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseContent);
                }
            }
        }
    }
}

Python 示例Python Sample

若要连接到机器学习 Web 服务,请使用 Python 2.X 的 urllib2 库和 Python 3.X 的 urllib.request 库。To connect to a Machine Learning Web service, use the urllib2 library for Python 2.X and urllib.request library for Python 3.X. 将传递 ScoreData,其中包含 FeatureVector 以及表示 ScoreData 的具有数字特征的 N 维向量。You will pass ScoreData, which contains a FeatureVector, an n-dimensional vector of numerical features that represents the ScoreData. 使用 API 密钥对机器学习服务进行身份验证。You authenticate to the Machine Learning service with an API key.

运行代码示例To run the code sample

  1. 部署“示例 1:从 UCI 下载数据集:成人 2 类数据集”实验(机器学习示例集合的一部分)。Deploy "Sample 1: Download dataset from UCI: Adult 2 class dataset" experiment, part of the Machine Learning sample collection.
  2. 使用 Web 服务密钥分配 API 密钥。Assign apiKey with the key from a Web service. 请参阅本文开始处附近的获取授权密钥部分。See the Get an authorization key section near the beginning of this article.
  3. 使用请求 URI 分配服务 URI。Assign serviceUri with the Request URI.

以下是完整请求的示例。Here is what a complete request will look like.

import urllib2 # urllib.request and urllib.error for Python 3.X
import json

data = {
    "Inputs": {
        "input1":
        [
            {
                'column1': "value1",   
                'column2': "value2",   
                'column3': "value3"
            }
        ],
    },
    "GlobalParameters":  {}
}

body = str.encode(json.dumps(data))

# Replace this with the URI and API Key for your web service
url = '<your-api-uri>'
api_key = '<your-api-key>'
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}

# "urllib.request.Request(url, body, headers)" for Python 3.X
req = urllib2.Request(url, body, headers)

try:
    # "urllib.request.urlopen(req)" for Python 3.X
    response = urllib2.urlopen(req)

    result = response.read()
    print(result)
# "urllib.error.HTTPError as error" for Python 3.X
except urllib2.HTTPError, error: 
    print("The request failed with status code: " + str(error.code))

    # Print the headers - they include the request ID and the timestamp, which are useful for debugging the failure
    print(error.info())
    print(json.loads(error.read())) 

R 示例R Sample

若要连接到机器学习 Web 服务,请使用 RCurl 和 rjson 库发出请求,并处理返回的 JSON 响应 。To connect to a Machine Learning Web Service, use the RCurl and rjson libraries to make the request and process the returned JSON response. 将传递 ScoreData,其中包含 FeatureVector 以及表示 ScoreData 的具有数字特征的 N 维向量。You will pass ScoreData, which contains a FeatureVector, an n-dimensional vector of numerical features that represents the ScoreData. 使用 API 密钥对机器学习服务进行身份验证。You authenticate to the Machine Learning service with an API key.

以下是完整请求的示例。Here is what a complete request will look like.

library("curl")
library("httr")
library("rjson")

requestFailed = function(response) {
    return (response$status_code >= 400)
}

printHttpResult = function(response, result) {
    if (requestFailed(response)) {
        print(paste("The request failed with status code:", response$status_code, sep=" "))
    
        # Print the headers - they include the request ID and the timestamp, which are useful for debugging the failure
        print(response$headers)
    }
    
    print("Result:") 
    print(fromJSON(result))  
}

req = list(
    Inputs = list(
            "input1" = list(
                "ColumnNames" = list("Col1", "Col2", "Col3"),
                "Values" = list( list( "0", "value", "0" ),  list( "0", "value", "0" )  )
            )                ),
        GlobalParameters = setNames(fromJSON('{}'), character(0))
)

body = enc2utf8(toJSON(req))
api_key = "abc123" # Replace this with the API key for the web service
authz_hdr = paste('Bearer', api_key, sep=' ')

response = POST(url= "<your-api-uri>",
        add_headers("Content-Type" = "application/json", "Authorization" = authz_hdr),
        body = body)

result = content(response, type="text", encoding="UTF-8")

printHttpResult(response, result)

JavaScript 示例JavaScript Sample

若要连接到机器学习 Web 服务,请在项目中使用 request npm 库。To connect to a Machine Learning Web Service, use the request npm package in your project. 还将使用 JSON 对象设置输入的格式并分析结果。You will also use the JSON object to format your input and parse the result. 使用 npm install request --save 进行安装,或将 "request": "*" 添加到 dependencies 下的 package.json,并运行 npm installInstall using npm install request --save, or add "request": "*" to your package.json under dependencies and run npm install.

以下是完整请求的示例。Here is what a complete request will look like.

let req = require("request");

const uri = "<your-api-uri>";
const apiKey = "<your-api-key>";

let data = {
    "Inputs": {
        "input1":
        [
            {
                'column1': "value1",
                'column2': "value2",
                'column3': "value3"
            }
        ],
    },
    "GlobalParameters": {}
}

const options = {
    uri: uri,
    method: "POST",
    headers: {
        "Content-Type": "application/json",
        "Authorization": "Bearer " + apiKey,
    },
    body: JSON.stringify(data)
}

req(options, (err, res, body) => {
    if (!err && res.statusCode == 200) {
        console.log(body);
    } else {
        console.log("The request failed with status code: " + res.statusCode);
    }
});