本文是《使用ML.NET和Azure Function進行機器學習 - 第1部分》的續篇。html
回顧第1部分,您將使用Visual Studio建立一個新的Azure Function項目。json
注意:確保安裝了Azure Workload以查看此模板。api
從Visual Studio的第1部分打開演示解決方案,並使用名爲serverless_ai的Azure Functions項目模板建立新項目。app
出現提示時,選擇Http觸發器選項並將其鏈接到項目的Azure存儲賬戶(此帖子的mlnetdemostorage1)。less
而後完成如下步驟:機器學習
將Http觸發器類Function1的名稱更改爲預測並複製如下代碼:ide
using Newtonsoft.Json; using Microsoft.ML; namespace serverless_ai { public static class Predict { [FunctionName("Predict")] public static IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequest req, [Blob("models/model.zip", FileAccess.Read, Connection = "AzureWebJobsStorage")] Stream serializedModel, TraceWriter log) { if (typeof(Microsoft.ML.Runtime.Data.LoadTransform) == null || typeof(Microsoft.ML.Runtime.Learners.LinearClassificationTrainer) == null || typeof(Microsoft.ML.Runtime.Internal.CpuMath.SseUtils) == null || typeof(Microsoft.ML.Runtime.FastTree.FastTree) == null) { log.Error("Error loading ML.NET"); return new StatusCodeResult(500); } //Read incoming request body string requestBody = new StreamReader(req.Body).ReadToEnd(); log.Info(requestBody); //Bind request body to IrisData object IrisData data = JsonConvert.DeserializeObject<IrisData>(requestBody); //Load prediction model var model = PredictionModel.ReadAsync<IrisData, IrisPrediction>(serializedModel).Result; //Make prediction IrisPrediction prediction = model.Predict(data); //Return prediction return (IActionResult)new OkObjectResult(prediction.PredictedLabels); } } }
這些行使用您的模型來評估新的鳶尾花虹據以進行預測。您的應用已準備好進行測試。工具
要測試本地計算機上的Azure Function應用程序,請檢查local.settings.json文件以確保AzureWebJobsStorage具備與之關聯的值。這是您的本地應用程序將在Azure存儲賬戶上找到您上載的模型的方式。若是有一個值(它應該會在您綁定的項目到您的賬戶建立時),你能夠F5的serverless_ai爲了項目來運行它。如今打開Postman (或相似的REST API工具)並使用如下正文發送POST調用到http://localhost:7071/api/Predict:post
{ "SepalLength": 3.3, "SepalWidth": 1.6, "PetalLength": 0.2, "PetalWidth": 5.1 }
若是一切順利,分類程序將返回「Iris-verginica」。學習
...或者您從Visual Studio部署的任何AI,轉到工具欄中的構建設置。
選擇「發佈serverless_ai」以部署Azure Function應用程序。
要在Azure門戶中測試應用程序部署,請選擇mlnetdemo下的Azure Function應用程序(或者您將其命名),而後選擇其下的Predict功能。使用屏幕右側的「 測試」面板查看已部署的應用程序。
這會將您的鳶尾花分類程序放在Azure上供其餘人嘗試吧。恭喜!您如今將人工智能應用成功部署到雲端了。