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 ===============
继续