ML.NET Tutorial - Get started in 10 minutes

Consume your model

Model Builder generates the trained model and code for you, including the next steps for model consumption, so you can easily use the model in your end-user .NET application.

  1. Replace the Program.cs code in your myMLApp with the following code:

  2. Program.cs
    using System;
    using MyMLAppML.Model;
    
    namespace myMLApp
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Add input data
                var input = new ModelInput();
                input.SentimentText = "That is rude.";
    
                // Load model and predict output of sample data
                ModelOutput result = ConsumeModel.Predict(input);
                Console.WriteLine($"Text: {input.SentimentText}\nIs Toxic: {result.Prediction}");
            }
        }
    }
  3. Run myMLApp (select Ctrl+F5 or Debug > Start Without Debugging). You should see the following output, predicting whether the input statement is toxic (true or 1) or non-toxic (false or 0).

  4. The output 'Text: This is rude. Is Toxic: True'

The ML.NET CLI has generated the trained model and code for you, so you can now use the model in your other .NET applications (for example, your consumeModelApp console app) by following these steps:

  1. Add a reference to the generated class library that contains the trained model and consumption code (SampleClassification.Model) in your consumeModelApp project. You can do this by navigating to the consumeModelApp directory in the terminal and running the following command:

    Command prompt
    dotnet add reference "../SampleClassification/SampleClassification.Model/SampleClassification.Model.csproj
  2. Open the consumeModelApp Program.cs in any code editor and replace the code with the following:

  3. Program.cs
    using System;
    using SampleClassification.Model;
    
    namespace consumeModelApp
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Add input data
                var input = new ModelInput();
                input.SentimentText = "That is rude.";
    
                // Load model and predict output of sample data
                ModelOutput result = ConsumeModel.Predict(input);
                Console.WriteLine($"Text: {input.SentimentText}\nIs Toxic: {result.Prediction}");
            }
        }
    }
  4. Run your consumeModelApp. You can do this by running the following command in the terminal (make sure you are in the consumeModelApp directory):

  5. Command prompt
    dotnet run
Continue