學習ML.NET(2): 使用模型進行預測
阿新 • • 發佈:2018-09-23
pack 發送post請求 ros 返回 內容 客戶 val net pipe
訓練模型
在上一篇文章中,我們已經通過LearningPipeline訓練好了一個“鳶尾花瓣預測”模型,
var model = pipeline.Train<IrisData, IrisPrediction>();
現在就可以讓模型對一條沒有人工標註結果的數據進行分析,返回一個預測結果。
var prediction = model.Predict(new IrisData() { SepalLength = 3.3f, SepalWidth= 1.6f, PetalLength = 0.2f, PetalWidth = 5.1f, }); Console.WriteLine($"Predicted flower type is: {prediction.PredictedLabels}");
或者一次預測一批數據
var inputs = new[]{ new IrisData() { SepalLength= 3.3f, SepalWidth = 1.6f, PetalLength = 0.2f, PetalWidth = 5.1f, } ,new IrisData() { SepalLength = 5.2f, SepalWidth = 3.5f, PetalLength= 1.5f, PetalWidth = 0.2f, } }; var predictions = model.Predict(inputs);
保存模型
但是大多數時候,已經訓練好的模型以後還需要繼續可以使用,因此需要把它持久化,寫入到zip文件中。
await model.WriteAsync("IrisPredictionModel.zip");
使用模型
一旦建立了機器學習模型,就可以部署它,利用它進行預測。我們可以通過REST API,接受來自客戶端的數據輸入,並返回預測結果。
-
創建API項目
dotnet new webapi -o myApi
-
安裝依賴項
cd myApi
dotnet add package Microsoft.ML
dotnet restore
-
引用模型
要在API中引用我們前面保存的模型,只需將IrisPredictionModel.zip復制到API項目目錄中即可。
-
創建數據結構
我們的模型使用數據結構IrisData和IrisPrediction
來定義特征和預測屬性。因此,當使用我們的模型通過API進行預測時,它也需要引用這些數據結構。因此,我們需要在API項目中定義IrisData和IrisPrediction
。類的內容與上一篇文章中創建模型項目中的內容相同。
using Microsoft.ML.Runtime.Api; namespace myApi { public class IrisData { [Column("0")] public float SepalLength; [Column("1")] public float SepalWidth; [Column("2")] public float PetalLength; [Column("3")] public float PetalWidth; [Column("4")] [ColumnName("Label")] public string Label; } }
using Microsoft.ML.Runtime.Api; namespace myApi { public class IrisPrediction { [ColumnName("PredictedLabel")] public string PredictedLabels; } }
-
創建Controller
現在,在API項目的Controllers目錄中,創建PredictController類,用於處理來自客戶端的預測請求,它包含一個POST方法
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.ML; namespace myApi.Controllers { [Route("api/[controller]")] [ApiController] public class PredictController : ControllerBase { // POST api/predict [HttpPost] public async Task<string> Post([FromBody] IrisData value) { var model = await PredictionModel.ReadAsync<IrisData,IrisPrediction>("IrisPredictionModel.zip"); var prediction = model.Predict(value); return prediction.PredictedLabels; } } }
-
測試API
使用如下命令行運行程序:
dotnet run
然後,使用POSTMAN或其他工具向http://localhost:5000/api/predict
發送POST請求,請求數據類似:
{ "SepalLength": 3.3, "SepalWidth": 1.6, "PetalLength": 0.2, "PetalWidth": 5.1, }
如果成功,將會返回"Iris-virginica"。
學習ML.NET(2): 使用模型進行預測