ML.NET 教學課程 - 10 分鐘入門

使用您的模型

最後一個步驟是在使用者應用程式中使用您的訓練模型。

  1. 使用下列程式碼取代您 myMLApp 專案中的 Program.cs程式碼:

    Program.cs
    using MyMLApp;
    // Add input data
    var sampleData = new SentimentModel.ModelInput()
    {
        Col0 = "This restaurant was wonderful."
    };
    
    // Load model and predict output of sample data
    var result = SentimentModel.Predict(sampleData);
    
    // If Prediction is 1, sentiment is "Positive"; otherwise, sentiment is "Negative"
    var sentiment = result.PredictedLabel == 1 ? "Positive" : "Negative";
    Console.WriteLine($"Text: {sampleData.Col0}\nSentiment: {sentiment}");
  2. 執行 myMLApp (選取 Ctrl+F5[偵錯] > [在不偵錯的情況下啟動])。您應該會看到下列輸出,預測輸入語句是正或負。

    輸出: 文字: 此餐館非常不錯。情感: 正值

ML.NET CLI 已為您產生經過訓練的模型和程式碼,因此您現在可以按照以下步驟在 .NET 應用程式 (例如,SentimentModel 主控台應用程式) 中使用該模型:

  1. 在命令列中,瀏覽至 consumeModelApp 目錄。
    Command prompt
    cd SentimentModel
  2. 在任何程式碼編輯器中開啟 Program.cs,並檢查程式碼。程式碼應如下所示:

    Program.cs
    using System;
    
    namespace SentimentModel.ConsoleApp
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Add input data
                SentimentModel.ModelInput sampleData = new SentimentModel.ModelInput()
                {
                  Col0 = @"Wow... Loved this place."
                };
    
                // Make a single prediction on the sample data and print results
                var predictionResult = SentimentModel.Predict(sampleData);
    
                Console.WriteLine("Using model to make single prediction -- Comparing actual Col1 with predicted Col1 from sample data...\n\n");
    
    
                Console.WriteLine($"Col0: @{"Wow... Loved this place."}");
                Console.WriteLine($"Col1: {1F}");
    
    
                Console.WriteLine($"\n\nPredicted Col1: {predictionResult.PredictedLabel}\n\n");
                Console.WriteLine("=============== End of process, hit any key to finish ===============");
                Console.ReadKey();
            }
        }
    }
  3. 執行您的 SentimentModel.ConsoleApp。您可以在終端機中執行下列命令來執行此操作 (請確保您位於 SentimentModel 目錄中):

    Command prompt
    dotnet run

    輸出看起來應該像這樣:

    Command prompt
    Using model to make single prediction -- Comparing actual Col1 with predicted Col1 from sample data...
    
    
    Col0: Wow... Loved this place.
    Col1: 1
    Class                          Score
    -----                          -----
    1                              0.9651076
    0                              0.034892436
    =============== End of process, hit any key to finish ===============
繼續