渡邊 です。
今回は『 Azure Machine Learning Studio 』で構築した機械学習モデルをWebサービスとして公開する方法を紹介致します。
機械学習モデルのWebサービス公開
Azure Machine Learning Studio にログインし、Webサービスとして公開したい機械学習モデルを構築した Experiment を開きます。
実行済でない場合は、『 Run 』で実行します。
実行が完了したら、『Predictive Web Service』をクリックします。
『 Run 』で実行します。
実行が完了したら、『 DEPLOY WEB SERVICE 』をクリックします。
これで機械学習モデルがWebサービスとして公開されました。
Webサービス情報
前節で『 DEPLOY WEB SERVICE 』を選択すると、Webサービス(API)のダッシュボードが表示されます。
APIへのリクエストに必要な『 API key 』もこの画面に表示されます。
ここで『 REQUEST/RESPONSE 』をクリックします。
APIへのリクエストに必要な情報とレスポンスの仕様が表示されます。
- HTTPメソッド
- リクエストURI
- HTTPバージョン
- リクエストヘッダ
- リクエストボディ(サンプルリクエスト)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
{ "Inputs": { "input1": { "ColumnNames": [ "symboling", "normalized-losses", "make", "fuel-type", "aspiration", "num-of-doors", "body-style", "drive-wheels", "engine-location", "wheel-base", "length", "width", "height", "curb-weight", "engine-type", "num-of-cylinders", "engine-size", "fuel-system", "bore", "stroke", "compression-ratio", "horsepower", "peak-rpm", "city-mpg", "highway-mpg", "price" ], "Values": [ [ "0", "0", "value", "value", "value", "value", "value", "value", "value", "0", "0", "0", "0", "0", "value", "value", "0", "value", "0", "0", "0", "0", "0", "0", "0", "0" ], [ "0", "0", "value", "value", "value", "value", "value", "value", "value", "0", "0", "0", "0", "0", "value", "value", "0", "value", "0", "0", "0", "0", "0", "0", "0", "0" ] ] } }, "GlobalParameters": {} } |
- レスポンスヘッダ
- レスポンスボディ(サンプルレスポンス)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 |
{ "Results": { "output1": { "type": "DataTable", "value": { "ColumnNames": [ "symboling", "normalized-losses", "make", "fuel-type", "aspiration", "num-of-doors", "body-style", "drive-wheels", "engine-location", "wheel-base", "length", "width", "height", "curb-weight", "engine-type", "num-of-cylinders", "engine-size", "fuel-system", "bore", "stroke", "compression-ratio", "horsepower", "peak-rpm", "city-mpg", "highway-mpg", "price", "Scored Labels" ], "ColumnTypes": [ "Numeric", "Numeric", "String", "String", "String", "String", "String", "String", "String", "Numeric", "Numeric", "Numeric", "Numeric", "Numeric", "String", "String", "Numeric", "String", "Numeric", "Numeric", "Numeric", "Numeric", "Numeric", "Numeric", "Numeric", "Numeric", "Numeric" ], "Values": [ [ "0", "0", "value", "value", "value", "value", "value", "value", "value", "0", "0", "0", "0", "0", "value", "value", "0", "value", "0", "0", "0", "0", "0", "0", "0", "0", "0" ], [ "0", "0", "value", "value", "value", "value", "value", "value", "value", "0", "0", "0", "0", "0", "value", "value", "0", "value", "0", "0", "0", "0", "0", "0", "0", "0", "0" ] ] } } } } |
『 C# 』『 Python 』『 R 』の各プログラミング言語で、
このAPIにアクセスする際のサンプルコードも記載されています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
// This code requires the Nuget package Microsoft.AspNet.WebApi.Client to be installed. // Instructions for doing this in Visual Studio: // Tools -> Nuget Package Manager -> Package Manager Console // Install-Package Microsoft.AspNet.WebApi.Client 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 { public class StringTable { public string[] ColumnNames { get; set; } public string[,] Values { get; set; } } class Program { static void Main(string[] args) { InvokeRequestResponseService().Wait(); } static async Task InvokeRequestResponseService() { using (var client = new HttpClient()) { var scoreRequest = new { Inputs = new Dictionary () { { "input1", new StringTable() { ColumnNames = new string[] {"symboling", "normalized-losses", "make", "fuel-type", "aspiration", "num-of-doors", "body-style", "drive-wheels", "engine-location", "wheel-base", "length", "width", "height", "curb-weight", "engine-type", "num-of-cylinders", "engine-size", "fuel-system", "bore", "stroke", "compression-ratio", "horsepower", "peak-rpm", "city-mpg", "highway-mpg", "price"}, Values = new string[,] { { "0", "0", "value", "value", "value", "value", "value", "value", "value", "0", "0", "0", "0", "0", "value", "value", "0", "value", "0", "0", "0", "0", "0", "0", "0", "0" }, { "0", "0", "value", "value", "value", "value", "value", "value", "value", "0", "0", "0", "0", "0", "value", "value", "0", "value", "0", "0", "0", "0", "0", "0", "0", "0" }, } } }, }, GlobalParameters = new Dictionary() { } }; const string apiKey = "abc123"; // Replace this with the API key for the web service client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Bearer", apiKey); client.BaseAddress = new Uri("https://ussouthcentral.services.azureml.net/workspaces/***/services/***/execute?api-version=2.0&details=true"); // 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 requert 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); } } } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
import urllib2 # If you are using Python 3+, import urllib instead of urllib2 import json data = { "Inputs": { "input1": { "ColumnNames": ["symboling", "normalized-losses", "make", "fuel-type", "aspiration", "num-of-doors", "body-style", "drive-wheels", "engine-location", "wheel-base", "length", "width", "height", "curb-weight", "engine-type", "num-of-cylinders", "engine-size", "fuel-system", "bore", "stroke", "compression-ratio", "horsepower", "peak-rpm", "city-mpg", "highway-mpg", "price"], "Values": [ [ "0", "0", "value", "value", "value", "value", "value", "value", "value", "0", "0", "0", "0", "0", "value", "value", "0", "value", "0", "0", "0", "0", "0", "0", "0", "0" ], [ "0", "0", "value", "value", "value", "value", "value", "value", "value", "0", "0", "0", "0", "0", "value", "value", "0", "value", "0", "0", "0", "0", "0", "0", "0", "0" ], ] }, }, "GlobalParameters": { } } body = str.encode(json.dumps(data)) url = 'https://ussouthcentral.services.azureml.net/workspaces/***/services/***/execute?api-version=2.0&details=true' api_key = 'abc123' # Replace this with the API key for the web service headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)} req = urllib2.Request(url, body, headers) try: response = urllib2.urlopen(req) # If you are using Python 3+, replace urllib2 with urllib.request in the above code: # req = urllib.request.Request(url, body, headers) # response = urllib.request.urlopen(req) result = response.read() print(result) except urllib2.HTTPError, error: print("The request failed with status code: " + str(error.code)) # Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure print(error.info()) print(json.loads(error.read())) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
library("RCurl") library("rjson") # Accept SSL certificates issued by public Certificate Authorities options(RCurlOptions = list(cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl"))) h = basicTextGatherer() hdr = basicHeaderGatherer() req = list( Inputs = list( "input1" = list( "ColumnNames" = list("symboling", "normalized-losses", "make", "fuel-type", "aspiration", "num-of-doors", "body-style", "drive-wheels", "engine-location", "wheel-base", "length", "width", "height", "curb-weight", "engine-type", "num-of-cylinders", "engine-size", "fuel-system", "bore", "stroke", "compression-ratio", "horsepower", "peak-rpm", "city-mpg", "highway-mpg", "price"), "Values" = list( list( "0", "0", "value", "value", "value", "value", "value", "value", "value", "0", "0", "0", "0", "0", "value", "value", "0", "value", "0", "0", "0", "0", "0", "0", "0", "0" ), list( "0", "0", "value", "value", "value", "value", "value", "value", "value", "0", "0", "0", "0", "0", "value", "value", "0", "value", "0", "0", "0", "0", "0", "0", "0", "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=' ') h$reset() curlPerform(url = "https://ussouthcentral.services.azureml.net/workspaces/***/services/***/execute?api-version=2.0&details=true", httpheader=c('Content-Type' = "application/json", 'Authorization' = authz_hdr), postfields=body, writefunction = h$update, headerfunction = hdr$update, verbose = TRUE ) headers = hdr$value() httpStatus = headers["status"] if (httpStatus >= 400) { print(paste("The request failed with status code:", httpStatus, sep=" ")) # Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure print(headers) } print("Result:") result = h$value() print(fromJSON(result)) |
おわりに
以上、『 Azure Machine Learning Studio 』で構築した機械学習モデルをWebサービスとして公開する方法を紹介致しました。
非常に簡単に機械学習モデルをWebサービス化出来ることがお分かり頂けたかと思います。
最後までご覧頂きありがとうございました。
参考書籍
クラウドではじめる機械学習
http://www.ric.co.jp/book/contents/book_992.html
参考リンク
Azure Machine Learning Studio
https://azure.microsoft.com/ja-jp/services/machine-learning-studio/
Azure Machine Learning Studio のドキュメント
https://docs.microsoft.com/ja-jp/azure/machine-learning/studio/
Azure Machine Learning Studio Web サービスをデプロイする
https://docs.microsoft.com/ja-jp/azure/machine-learning/studio/publish-a-machine-learning-web-service
Microsoft Azure Portal
https://azure.microsoft.com/ja-jp/features/azure-portal/
Microsoft Azure Machine Learning Studio
https://studio.azureml.net/