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 ===============
続行