AI時代的網站與手機App建置與開發Part5 - 建立支援貸款授信功能的ASP.NET Core MVC網站

 ·       認識Visual Studio建立的Machine Learning Server程式

使用Visual Studio建立部署機器學習模型的Web API專案, 主要的程式碼在Program.cs, 負責載入訓練妥的機器學習模型, 並指定傾聽Client程式發送的需求的端點與連接埠, List 1:

List 1: Server程式專案Program.cs主要的程式碼

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddPredictionEnginePool<MLModel.ModelInput, MLModel.ModelOutput>()

    .FromFile("MLModel.mlnet");                //載入訓練妥的機器學習模型

builder.Services.AddEndpointsApiExplorer();   //公開API端點資訊

builder.Services.AddSwaggerGen(c =>

{

    c.SwaggerDoc("v1", new OpenApiInfo {

Title = "My API", Description = "Docs for my API", Version = "v1" });

});                 //Model,Controller,Router建立提供OpenAPI資訊的Swagger文件

var app = builder.Build();                    //建立應用程式

app.UseSwagger();                              //產生Swagger JSON文件

app.UseSwaggerUI(c =>

{

    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");

});                                            //JSON文件生成API測試文件

// /predict端點傾聽用戶端的需求

app.MapPost("/predict",

    async (PredictionEnginePool<MLModel.ModelInput, MLModel.ModelOutput> predictionEnginePool, MLModel.ModelInput input) =>

        await Task.FromResult(predictionEnginePool.Predict(input)));

// Run app

app.Run();


List 1的程式碼會用到MLModel.mbconfig這個檔案提供的類別的功能, 包括:

MLModel.consumption.cs : 建立預測引擎, 執行預測, 排序每一種答案的預測分數

MLModel.evaluate.cs : 支援計算訓綶資料中每一個特徵的重要性(PFI: Permutation Feature Importance)

MLModel.mlnet : 訓練妥的機器學習模型

MLModel.training.cs : 支援載入訓綶資料, 訓練機器學習模型, 重新訓綶機器學習模型, 儲存機器學習模型

如圖1所示:

1: 使用ML.NET程式庫的Server程式的機器學習相關功能

·       認識Visual Studio建立的Machine Learning Server程式

使用Visual Studio建立使用機器學習模型的Client主控台應用程式, 主要的程式碼在Program.cs, 負責叫用上述的Web API提供的端點, 傳入預測的資料, 接收預測的結果, List 2:

List 1: Client主控台程式專案Program.cs主要的程式碼

// This file was auto-generated by ML.NET Model Builder.

using MLModel_ConsoleApp;

// Create single instance of sample data from first line of dataset for model input

MLModel.ModelInput sampleData = new MLModel.ModelInput()   //建立欲預測的資料

{

    Checking_status = @"0<=X<200",

    Duration = 48F,

    Credit_history = @"existing paid",

    Purpose = @"radio/tv",

    Credit_amount = 5951F,

    Savings_status = @"<100",

    Employment = @"1<=X<4",

    Installment_commitment = 2F,

    Personal_status = @"female div/dep/mar",

    Other_parties = @"none",

    Residence_since = 2F,

    Property_magnitude = @"real estate",

    Age = 22F,

    Other_payment_plans = @"none",

    Housing = @"own",

    Existing_credits = 1F,

    Job = @"skilled",

    Num_dependents = 1F,

    Own_telephone = @"none",

};

Console.WriteLine("Using model to make single prediction -- Comparing actual Class with predicted Class from sample data...\n\n");      //顯示欲預測的資料

Console.WriteLine($"Checking_status: {@"0<=X<200"}");

Console.WriteLine($"Duration: {48F}");

Console.WriteLine($"Credit_history: {@"existing paid"}");

Console.WriteLine($"Purpose: {@"radio/tv"}");

Console.WriteLine($"Credit_amount: {5951F}");

Console.WriteLine($"Savings_status: {@"<100"}");

Console.WriteLine($"Employment: {@"1<=X<4"}");

Console.WriteLine($"Installment_commitment: {2F}");

Console.WriteLine($"Personal_status: {@"female div/dep/mar"}");

Console.WriteLine($"Other_parties: {@"none"}");

Console.WriteLine($"Residence_since: {2F}");

Console.WriteLine($"Property_magnitude: {@"real estate"}");

Console.WriteLine($"Age: {22F}");

Console.WriteLine($"Other_payment_plans: {@"none"}");

Console.WriteLine($"Housing: {@"own"}");

Console.WriteLine($"Existing_credits: {1F}");

Console.WriteLine($"Job: {@"skilled"}");

Console.WriteLine($"Num_dependents: {1F}");

Console.WriteLine($"Own_telephone: {@"none"}");

Console.WriteLine($"Class: {@"bad"}");

//叫用MLModel類別的PredictAllLabels函式對欲預測的資料進行預測

var sortedScoresWithLabel = MLModel.PredictAllLabels(sampleData);

Console.WriteLine($"{"Class",-40}{"Score",-20}");

Console.WriteLine($"{"-----",-40}{"-----",-20}");

foreach (var score in sortedScoresWithLabel) //依預測的分數由高至低顯示各種預測結果

{

    Console.WriteLine($"{score.Key,-40}{score.Value,-20}");

}

Console.WriteLine("=============== End of process, hit any key to finish ===============");

Console.ReadKey();


List 2的程式碼會用到MLModel.mbconfig這個檔案提供的類別的功能, 包括 : MLModel.consumption.cs, MLModel.evaluate.cs, MLModel.mlnet, MLModel.training.cs, 其功能和加入到Server Web API專案的類別的功能完全相同

如圖2所示:

2: 使用ML.NET程式庫的Client程式的機器學習相關功能


請注意MLModel.consumption.cs, MLModel.evaluate.cs, MLModel.mlnet, MLModel.training.cs這四個檔案定義的是同一個MLModel類別, 這些檔案也同樣加入到原先執行加入[機器學習模型]的專案, 也就是說, 原先執行加入[機器學習模型]的專案只要參考上述List 2所列的程式碼, 就可以使用訓練妥的機器學習模型, 達成欲完成的功能

下一回我們將會討論如何叫用MLModel類別提供的功能, 或叫用部署有機器學習模型的Web API服務, 以完成需要的工作.

 

留言

這個網誌中的熱門文章

AI時代的網站與手機App建置與開發Part27 - ML.NET與物件偵測

AI時代的網站與手機App建置與開發Part28 - 使用YOLO模型進行物件偵測

AI時代的網站與手機App建置與開發Part24 - ML.NET與圖片異常偵測