夜風のMixedReality

xRと出会って変わった人生と出会った技術を書き残すためのGeekなHoloRangerの居場所

Azure Machine Learningを学ぶ その⑥ テストの実行 リソースの削除

本日はAzure AI学習枠です。

現在Azure MachineLearningをゼロから勉強しています。 チュートリアルとしてAzure MLで提供されている自動車価格のサンプルデータから自動車の価格推論を行うモデルを作成します。

前回まででデータの整理、機械学習のパイプラインの構築を行い実行・デプロイまで行いました。

redhologerbera.hatenablog.com

redhologerbera.hatenablog.com

redhologerbera.hatenablog.com

redhologerbera.hatenablog.com

redhologerbera.hatenablog.com

今回は作成されたモデルの扱いとリソースの削除を行います。

〇テストの実行

デプロイ後のテストタブではJson形式でのサンプルの実行が可能になります。

テストを選択することでそのJsonを投げることで返されるデータを見ることができます。

仕様タブではエンドポイント及び認証キーが発行されます。

またC#のサンプルコードがあるためこれを実行するだけで簡単に使用することができるようになります。

// 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 Newtonsoft.Json

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

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

        static async Task InvokeRequestResponseService()
        {
            var handler = new HttpClientHandler()
            {
                ClientCertificateOptions = ClientCertificateOption.Manual,
                ServerCertificateCustomValidationCallback =
                        (httpRequestMessage, cert, cetChain, policyErrors) => { return true; }
            };
            using (var client = new HttpClient(handler))
            {
                // Request data goes here
                // The example below assumes JSON formatting which may be updated
                // depending on the format your endpoint expects.
                // More information can be found here:
                // https://docs.microsoft.com/azure/machine-learning/how-to-deploy-advanced-entry-script
                var scoreRequest = new
                {
                    Inputs = new Dictionary<string, List<Dictionary<string, string>>>()
                    {
                        
                    },
                    GlobalParameters = new Dictionary<string, string>()
                    {
                    }
                };
                
                const string apiKey = "キー"; // Replace this with the API key for the web service
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Bearer", apiKey);
                client.BaseAddress = new Uri("http:/");

                var requestString = JsonConvert.SerializeObject(scoreRequest);
                var content = new StringContent(requestString);

                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                // 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.PostAsync("", content);

                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);
                }
            }
        }
    }
}

実行後はコンソールに結果が返されるようになっています。

〇リソースの削除

最後にリソースの削除を行います。

Azure MLの課金要素はVMの時間課金とストレージです。そのため必要がなくなったVMを適時削除する必要があります。

①Azure Portalからリソースグループを選択します。

②リソースグループ一覧から削除したい機械学習を含むリソースを選択します。

ここではこのリソースグループに紐づけられているサービスが一覧として並んでいます。

③[リソースグループの削除]を選択します。

④削除されるリソースを確認しリソース名を入力し削除します。

削除には数分の時間がかかります。

以上でAzure MLデザイナーの回帰チュートリアルが終わりました。

筆者は冒頭に述べた通りほぼゼロからの初心者なのでとりあえず一連のワークフローが理解できたような気がしています。

機械学習では回帰以外にもアルゴリズムがあるのでほかのチュートリアルや独自データでのモデル構築も行っていきたいと思います。