Azure Machine Learning Studioの機械学習モデルにアクセスする( Python / Postman / Azure Functions )

まずは、『 Python 3 』でアクセスする方法を紹介致します。

『Request Response API Documentation』で『Python 2』のサンプルコードが得られるので、

それを元に『 Python 3 』のコードに書き換えます。

ここでは、環境として Jupyter Notebook を使用しています。

import urllib

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": [ [ "2","164","audi","gas","std","four","sedan","fwd","front","99.80","176.60","66.20","54.30","2337","ohc","four","109","mpfi","3.19","3.40","10.00","102","5500","24","30","13950" ] ]
},
},
"GlobalParameters": {}
}

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

url = 'https://ussouthcentral.services.azureml.net/workspaces/*/services/*/execute?api-version=2.0&details=true'
api_key = '***' # Replace this with the API key for the web service
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}

req = urllib.request.Request(url, body, headers)

try:
response = urllib.request.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(json.dumps(json.loads(result), indent=4))
except (urllib.error.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()))

実行すると、次のような結果が返ってきます。

{
"Results": {
"output1": {
"type": "table",
"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": [
"Int32",
"Int32",
"String",
"String",
"String",
"String",
"String",
"String",
"String",
"Double",
"Double",
"Double",
"Double",
"Int32",
"String",
"String",
"Int32",
"String",
"Nullable`1",
"Nullable`1",
"Double",
"Nullable`1",
"Nullable`1",
"Int32",
"Int32",
"Nullable`1",
"Double"
],
"Values": [
[
"2",
"164",
"audi",
"gas",
"std",
"four",
"sedan",
"fwd",
"front",
"99.8",
"176.6",
"66.2",
"54.3",
"2337",
"ohc",
"four",
"109",
"mpfi",
"3.19",
"3.4",
"10",
"102",
"5500",
"24",
"30",
"13950",
"13271.3472331043"
]
]
}
}
}
}

Postman

次に、REST APIテストツール『 Postman 』でアクセスする方法を紹介致します。

次の項目を入力して、『 Send 』ボダンを押下するとレスポンスが返ってきます。

  • HTTPメソッド
  • リクエストURI
  • リクエストヘッダ( Authorization / Content-Type )
  • リクエストボディ

リクエストボディとレスポンスボディはそれぞれ次のような形式です。

{
"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": [
[
"2",
"164",
"audi",
"gas",
"std",
"four",
"sedan",
"fwd",
"front",
"99.80",
"176.60",
"66.20",
"54.30",
"2337",
"ohc",
"four",
"109",
"mpfi",
"3.19",
"3.40",
"10.00",
"102",
"5500",
"24",
"30",
"13950"
]
]
}
},
"GlobalParameters": {}
}

{
"Results": {
"output1": {
"type": "table",
"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": [
"Int32",
"Int32",
"String",
"String",
"String",
"String",
"String",
"String",
"String",
"Double",
"Double",
"Double",
"Double",
"Int32",
"String",
"String",
"Int32",
"String",
"Nullable`1",
"Nullable`1",
"Double",
"Nullable`1",
"Nullable`1",
"Int32",
"Int32",
"Nullable`1",
"Double"
],
"Values": [
[
"2",
"164",
"audi",
"gas",
"std",
"four",
"sedan",
"fwd",
"front",
"99.8",
"176.6",
"66.2",
"54.3",
"2337",
"ohc",
"four",
"109",
"mpfi",
"3.19",
"3.4",
"10",
"102",
"5500",
"24",
"30",
"13950",
"13271.3472331043"
]
]
}
}
}
}

Azure Functions ( JavaScript )

最後に、Azure Functions ( JavaScript ) でアクセスする方法を紹介致します。

まずは、 npm request をインストールします。

D:\home\site\wwwroot\HttpTrigger1> npm initD:\home\site\wwwroot\HttpTrigger1> npm install request

npm WARN saveError ENOENT: no such file or directory, open 'D:\home\site\wwwroot\HttpTrigger1\package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open 'D:\home\site\wwwroot\HttpTrigger1\package.json'
npm WARN HttpTrigger1 No description
npm WARN HttpTrigger1 No repository field.
npm WARN HttpTrigger1 No README data
npm WARN HttpTrigger1 No license field.

一例として、次のようなプログラムを作成し、 Azureポータル上から実行します。

const request = require("request");

module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');

if ((req.body && req.body.Inputs)) {
let result = await reqML(context, req.body)
context.res = {
// status: 200, /* Defaults to 200 */
body: result
};
}
else {
context.res = {
status: 400,
body: "Please pass data in the request body"
};
}
};

function reqML(context, data) {

const uri = "https://ussouthcentral.services.azureml.net/workspaces/*/services/*/execute?api-version=2.0&details=true";
const apikey = "***";
const options = {
"uri": uri,
"method": "POST",
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer " + apikey,
},
"body": JSON.stringify(data)
};
return doRequest(context, options);
};

function doRequest(context, options) {
return new Promise(function (resolve, reject) {
request(options, function (error, res, body) {
context.log(res.statusCode);
context.log(res)
if (!error && res.statusCode == 200) {
resolve(body);
} else {
reject(error);
}
});
});
};

実行すると、次のような結果が返ってきます。

{"Results":{"output1":{"type":"table","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":["Int32","Int32","String","String","String","String","String","String","String","Double","Double","Double","Double","Int32","String","String","Int32","String","Nullable1","Nullable1","Double","Nullable1","Nullable1","Int32","Int32","Nullable`1","Double"],"Values":[["2","164","audi","gas","std","four","sedan","fwd","front","99.8","176.6","66.2","54.3","2337","ohc","four","109","mpfi","3.19","3.4","10","102","5500","24","30","13950","13271.3472331043"]]}}}}

おわりに

以上、『 Azure Machine Learning Studio 』でWebサービスとして公開した機械学習モデルへアクセスする方法を紹介致しました。

REST API ですので、他にもアクセス方法はあります。ご自身の要件に合わせた方法をご選択下さい。

最後までご覧頂きありがとうございました。

参考リンク

Azure Machine Learning Studioで機械学習モデルをWebサービス化する | ナレコムAzureレシピ

/2019/01/azure-machine-learning-studio-web-service/

Postman | API Development Environment

Azure Functions—サーバーレス アーキテクチャ | Microsoft Azure

この記事を書いた人

azure-recipe-user