How to execute ML.NET Model in .NET Framework

How to execute ML.NET Model in .NET Framework

Execute ML.NET Model in .NET Framework demo application

How to execute ML.NET Model in .NET Framework

This article should help you solve the issue ML.NET has with .NET Framework. Once, you have the model built you need to reference the ML.NET libraries in your .NET Framework project. This works fine for .NET Core but there are quite a lot of issue in .NET Framework.

If you are like me, you still have active projects under the .NET Framework. And if you want to use your machine learning model in your project, you may have encountered multiple different errors. Anything from trouble referencing the libraries to the app being unable to load TensorFlow library.

If this sounds familiar, then you are at the right place. ML.NET is still under development. There are kinks and bugs being solved at this moment. Some of them pertain to the .NET Framework. This article will explain how you can use your model by creating a simple but effective workaround.

So, let’s get started.

Windows Forms .NET Framework Application

Execute ML.NET Model in .NET Framework Demo Application
Execute ML.NET Model in .NET Framework Demo Application

Some time ago, we tried out the ML.NET Model Builder by creating a Cat vs Dog Classifier. We ended the post there. Now we want to consume our model inside a Windows Forms .NET Framework application.

How to use ML.NET Model Builder for Image Classification

As you expected referencing the classifier was quite difficult. Especially if you use an older framework version like 4.5. But there is a way to do that. Before we dive into the solution, we will discuss the application.

To demonstrate how to use the ML.NET Model inside a .NET Framework project I built a very simple demo app. It allows the user to pick an image from the File -> Open Image menu. Then by clicking File -> Classify the app will make a call to the model and present the result inside an information message box.

The Solution

To achieve the desired result, we must set up the following pipeline. A command from the .NET Framework application is sent to a .NET Core app hosting the model. The .NET Core app executes the model with the sent parameters and returns the results to the caller.

Solution Explorer
Solution Explorer

In this case, our working .NET Framework application is the MLNETConnection. On the other side we have CatVsDogClassifierML.ConsoleApp that has a reference to the ML.NET trained model. This .NET Core application can take an image file path as an input, pass it to the ML.NET model and classify it, then print the result out. At the very end of this pipeline is the CatVsDogClassifierML.Model. Just like the name suggest this a Class Library that loads and utilizes the trained model.

ML.NET Model Class Library

This library created by the ML.NET Model Builder is responsible for loading up the model and creating the prediction engine.

Cat Vs Dog Classifier Project Structure
CatVsDogClassifierML.Model project

Inside there is a file called MLModel.zip. This is the model produced by ML.NET. The ConsumeModel class will load it up and create the prediction engine like so:

public static PredictionEngine<ModelInput, ModelOutput> CreatePredictionEngine()
{
    MLContext = new MLContext();
    string modelPath = @"MLModel.zip";
    ITransformer mlModel = mlContext.Model.Load(modelPath, out var modelInputSchema);
    var predEngine = mlContext.Model.CreatePredictionEngine<ModelInput, ModelOutput>(mlModel);

    return predEngine;
}

This class hosts one more function called Predict which accepts a ModelInput parameter.

public static ModelOutput Predict(ModelInput input)
{
     ModelOutput result = PredictionEngine.Value.Predict(input);
     return result;
}

The ModelInput class has two properties. ImageSource and Label. The Image Source property holds the physical path to the image we want to classify. And because Neural Nets are a Supervised type of Machine Learning we are passing the Label as an input as well. The ModelOutput has two properties. Prediction and Score.

However, this demo we will populate only the Image Source for the input, and we will display the Prediction field from the output. We don’t need the Label since we are not going to be training the model, and we don’t need the Score since we want to print out the class label stored in Prediction.

.NET Core Console Application

The .NET Core console application references and consumes the ML.NET Model created by the Model Builder.

Cat Vs Dog Classifier the .NET Core Console App
CatVsDogClassifierML.ConsoleApp

The goal is to launch this console application from our .NET Framework Windows Forms app. Then all we want to do is pass the image file path to classify it, and present the output.

C#: execute ML.NET Model in .NET Framework:

static void Main(string[] args)
{
     new InputController((line) => line.Trim().ToLower().Equals("q"))
       .ReadLine((line) => new ImageInput(line).IsValidInput((imageFilePath) =>
                      Output.PrintResult(Console.WriteLine,    ConsumeModel.Predict(new ModelInput() { ImageSource = imageFilePath }).Prediction,args)));
}

The Input Controller class will read a string line indefinitely from the console until the character “q” is detected. Next, that line is passed to the Image Input class to check if the line is an actual path that points to an image file. If it does, the Consume Model static class will read in the image and make a prediction. That prediction is then printed on the console.

.NET Core Console Application Demo
.NET Core Console Application

Here you can see I am manually entering an image path. Then the ML.NET model is initialized and finally a prediction is made. Then I am doing the same for two more images, until I press the letter “q” to exit the application.

We will do the same process from the .NET Framework application.

.NET Framework Application

So, we need a way to pass a file path to an image, and get the result back. We already have the solution described in more detail here:

Execute Command Prompt commands from C#

Because we already have the CMD Service code, we can only focus on what matters in this solution. And that is calling the application and retrieve the output.

Let us check the code:

public class Classifier
{
   private CmdService _cmdService;
   private const string RESULT_LINE = "Result:";
   public Classifier(string classifierAppPath)
   {
      _cmdService = new CmdService(classifierAppPath, RESULT_LINE, (data) => data.StartsWith(RESULT_LINE));
   }
   public void Classify(string imageFilePath,Action<string>classify)=>
            classify(_cmdService.ExecuteCommand(imageFilePath));
}

As you can see the Classifier class hosts the Command Line Service. To create an instance from it you must pass three parameters. The first one is the path to the application you would like to launch. The second one is used as a key word that is going to be appended to the result. This way we know at which line the ML.NET Model prints out the result. Finally, we pass in a predicate that will return true when the result is returned.

For example:

We can pass the following path: C:\Images\Test\animal.png

Then the application will return: Result: Cat

We need this because there might be some warnings returned, or other information that we do not need. By prefixing the classifier result with the string “Result: “ we know exactly where to look for it.

C# Code Walkthrough

Execute ML.NET Model in .NET Framework

If we look at the code, we can see two properties in our MainView.

private readonly InputImage _inputImage = new InputImage();
private readonly Classifier _classifier = new Classifier(@"""…CatVsDogClassifierML.ConsoleApp\bin\Debug\netcoreapp3.1\CatVsDogClassifierML.ConsoleApp.exe""");

The input image class is responsible for loading an image, and verifying that the path is in the correct form.

To open an image, we can simply use the following statement:

new OpenImageFileDialog().OpenImage(
 (imageFilePath) => _inputImage.LoadImageFromFilePath(imageFilePath,                             (bmp) => pictureBox.Image = bmp));

To classify the image, we call the Classify method from our Classifier instance. It takes two parameters. One is the image file path and the second is an Action Delegate which allows us to process the returned result. All we want to do is show an informational message box and display the resulting string.

private void classifyToolStripMenuItem_Click(object sender, EventArgs e) =>

_inputImage.HasImageLoaded((imageFilePath)=>
    _classifier.Classify(imageFilePath, 
          (result) => MessageBox.Show(result,AppGlobals.AppName,MessageBoxButtons.OK,MessageBoxIcon.Information)));

The important thing to note here is to check the constructor of the Classifier class. As a parameter it takes a path to the .NET Core application that has the model referenced and ready to use. The Classify method on the other hand, writes the image file path to the console of that application. Then the image is loaded, classified and the result is returned. On the main app, the delegate is executed when the ML.NET Model result is returned. Finally, it is displayed in a message box.

Conclusion

I expect that Microsoft will resolve all problems related to this very soon. But, until such time comes, this would be my go-to solution when I want to embed ML.NET into an already existent .NET Framework application

More ML.NET Tutorials

44 thoughts on “How to execute ML.NET Model in .NET Framework

  1. Reply
    dieBachs
    March 31, 2021 at 8:43 am

    Thank you for the explanations, especially as I wondered after your image classification post on bringing this into a nice GUI. As I am not a professional programmer, I failed to finalize the program as there seem to be some changes to the previous version, and I somehow struggle with MLNETConnection. Could you please explain in more detail or provide the project data?

    1. Reply
      vanco
      March 31, 2021 at 9:34 am

      Hi, the complete solution is around 1GB so I can temporary upload it at some location.
      So, if you have the classifier projects ready (generated by the model builder) then you are ready to build the GUI.
      To build the Windows Forms project (GUI), you need the following tutorial: https://code-ai.mk/execute-command-prompt-commands-from-c/
      Inside your GUI project you should have a CMD Service that will call and execute the .NET Core console application. Also make sure to copy the MLModel.zip inside your GUI bin project. If you have more details about the error you are getting, please let me know.

  2. Reply
    Dona
    April 18, 2021 at 9:19 pm

    Please can you share us the codes from MLNETCONNECTION files? ( AppGlobals.cs, InputImage.cs, Program.cs)

    I don’t know how to write the Appglobals and InputImages, and I have 1 error with Classifier calling the CmdService.
    (and yeah I followed your CMDSERVICE tutorial)

    1. Reply
      vanco
      April 19, 2021 at 6:58 am

      Hi, I did check but I don’t currently have the project with me. When I get it I will upload the complete solution on the post.

      1. Reply
        Dona
        May 12, 2021 at 4:04 am

        Thank you Vanco, I hope you can share the project with us

  3. Reply
    ubaTaeCJ
    March 12, 2024 at 10:10 pm

    1

  4. Reply
    vpn code 2024
    April 1, 2024 at 7:32 am

    You have made some decent points there. I looked on the web
    for more info about the issue and found most people will go along with your views on this site.

    my website … vpn code 2024

  5. Reply
    vpn special code
    April 11, 2024 at 3:51 pm

    Hi there this is kinda of off topic but I was wondering if blogs use WYSIWYG
    editors or if you have to manually vpn special code with HTML.
    I’m starting a blog soon but have no coding know-how so
    I wanted to get advice from someone with experience.
    Any help would be greatly appreciated!

  6. Reply
    Bryanmyday
    May 6, 2024 at 1:02 am

    Our premium databases recompense XRumer and GSA Search Machine Ranker are just what you have occasion for!
    What do our databases include?
    • Nimble links: Earn access to constantly updated lists of sprightly links from profiles, posts, forums, guestbooks, blogs, and more. No more wasting things on dead links!
    • Verified and identified links: Our premium databases for GSA Search Engine Ranker encompass verified and identified links, categorized sooner than search engines. This means you pull down the highest grandeur links that will escape you row higher.
    • Monthly updates: All of our databases are updated monthly to ensure you have in the offing the most unconventional and crap links.

    Pick out the perfect way out for you:
    • XRumer premium database:
    o Premium database with free updates: $119
    o Premium database without updates: $38

    • Fresh XRumer Database:
    o Fresh database with unused updates: $94
    o Newfangled database without updates: $25

    • GSA Search Apparatus Ranker Verified Links:
    o GSA Search Locomotive Ranker activation critical: $65 (includes database)
    o Immature database with free updates: $119
    o Untried database without updates: $38

    Don’t enervate epoch on outdated or tranquil links. Sink in our premium databases and start seeing results today!
    Order now!
    P.S. During purchasing GSA Search Machine Ranker from us, you get a high-quality product at a competitive price. Come to someone’s rescue your resources and start improving your SEO rankings today!
    To connection us, write to telegram https://t.me/DropDeadStudio promocode “DD50%”

  7. Reply
    PatrickBug
    May 7, 2024 at 6:06 pm

    Покорите вершины рейтингов вместе с нами https://bazydlyaxrumerkupitt.ru/!

  8. Reply
    PatrickBug
    May 7, 2024 at 7:51 pm

    Наши базы – это не просто данные, это ключ к доминированию в поисковых системах. Доверьте свой рост нам https://bazydlyaxrumerkupitt.ru/!

  9. Reply
    Matthewtig
    May 7, 2024 at 8:22 pm

    Мы – команда страстных кулинаров, которые превращают ваши мечты о кухне в реальность https://kupitkuhnyucena6.ru/.

  10. Reply
    Matthewtig
    May 7, 2024 at 9:33 pm

    Доверьте нам создание кухни вашей мечты и погрузитесь в мир вкуса и уюта https://kupitkuhnyucena6.ru/!

  11. Reply
    Matthewtig
    May 7, 2024 at 10:34 pm

    Откройте для себя новые вкусы и ароматы нашего мирового меню в уютной атмосфере https://kupitkuhnyucena6.ru/!

  12. Reply
    Bobbyrem
    May 7, 2024 at 11:18 pm

    Мечтаете о кухне вашей мечты? Мы воплотим ваши желания https://kupitkuhnyumagazin.ru/!

  13. Reply
    Bobbyrem
    May 8, 2024 at 12:13 am

    Лучший выбор для тех, кто ценит качество и стиль. Рекомендую всем https://kupitkuhnyumagazin.ru/!

  14. Reply
    Anthonywrord
    May 8, 2024 at 1:53 am

    Мы – команда профессионалов, которая превращает ваши мечты в реальность. Каждая кухня у нас – это произведение искусства и функциональности https://kupitkuhnyunedorogo.ru/.

  15. Reply
    Anthonywrord
    May 8, 2024 at 2:56 am

    Мы не просто продаём кухни, мы создаём шедевры, которые будут восхищать вас каждый день https://kupitkuhnyunedorogo.ru/.

  16. Reply
    RichardGuize
    May 8, 2024 at 4:31 am

    Наша страсть к дизайну и индивидуальному подходу позволяет нам создавать кухни, которые отражают ваш стиль и вкус https://kupitkuhnyu-ot-proizvoditelya.ru/.

  17. Reply
    RichardGuize
    May 8, 2024 at 5:37 am

    Каждая кухня уникальна и создана специально для вас, отражая вашу индивидуальность и стиль https://kupitkuhnyu-ot-proizvoditelya.ru/.

  18. Reply
    PatrickBug
    May 8, 2024 at 7:15 am

    Невероятное качество баз! Рекомендую всем, кто хочет быть на пике https://bazydlyaxrumerkupitt.ru/!

  19. Reply
    PatrickBug
    May 8, 2024 at 8:26 am

    С нами ваш сайт станет непобедимым в борьбе за первые места в поисковой выдаче https://bazydlyaxrumerkupitt.ru/.

  20. Reply
    Matthewtig
    May 8, 2024 at 9:57 am

    Погрузитесь в мир волшебства и вкуса вместе с нашими талантливыми поварами и артистами https://kupitkuhnyucena6.ru/!

  21. Reply
    Matthewtig
    May 8, 2024 at 11:04 am

    Присоединяйтесь к нам и узнайте секреты итальянской кухни от наших шеф-поваров https://kupitkuhnyucena6.ru/!

  22. Reply
    Bobbyrem
    May 8, 2024 at 1:31 pm

    Забудьте о скучных кухнях! Наши дизайнеры помогут воплотить ваши самые дерзкие фантазии в реальность. Выберите стиль, цвет и форму – и ваша кухня станет настоящим произведением искусства https://kupitkuhnyumagazin.ru/!

  23. Reply
    Bobbyrem
    May 8, 2024 at 1:40 pm

    Наша миссия – сделать кухню не просто местом приготовления пищи, а настоящим источником радости и вдохновения https://kupitkuhnyumagazin.ru/.

  24. Reply
    RichardGuize
    May 8, 2024 at 5:45 pm

    Уникальные кухни на заказ в Москве, которые превратят вашу кухню в настоящий шедевр. Доверьте свои кулинарные фантазии нам https://kupitkuhnyu-ot-proizvoditelya.ru/!

  25. Reply
    RichardGuize
    May 8, 2024 at 6:50 pm

    Мы используем только лучшие материалы и технологии для создания кухонь, которые прослужат вам долгие годы https://kupitkuhnyu-ot-proizvoditelya.ru/.

  26. Reply
    PatrickBug
    May 8, 2024 at 8:24 pm

    Мы – команда профессионалов, готовых ускорить ваш путь к онлайн-успеху с помощью уникальных баз для XRumer и GSA Search Engine Ranker https://bazydlyaxrumerkupitt.ru/.

  27. Reply
    Bobbyrem
    May 9, 2024 at 1:29 am

    Кухни от КухниМаркет – это просто сказка! Каждый день – праздник https://kupitkuhnyumagazin.ru/!

  28. Reply
    Anthonywrord
    May 9, 2024 at 3:57 am

    Кухни просто супер! Не могу нарадоваться своей новой кухне, спасибо фабрике https://kupitkuhnyunedorogo.ru/!

  29. Reply
    PatrickBug
    May 9, 2024 at 10:09 am

    Мы работаем над увеличением скорости и совместимости с новыми платформами для вашего удобства https://bazydlyaxrumerkupitt.ru/.

  30. Reply
    RichardGuize
    May 9, 2024 at 8:41 pm

    Наша команда опытных специалистов обеспечит качественный и профессиональный монтаж вашей кухни https://kupitkuhnyu-ot-proizvoditelya.ru/.

  31. Reply
    RichardGuize
    May 9, 2024 at 8:42 pm

    Индивидуальные дизайны кухонь, которые вдохнут жизнь в ваш дом https://kupitkuhnyu-ot-proizvoditelya.ru/.

  32. Reply
    Anthonywrord
    May 10, 2024 at 5:33 am

    Лучшее решение для кухни! Качество на высоте, заказал здесь и не пожалел https://kupitkuhnyunedorogo.ru/.

  33. Reply
    Bobbyrem
    May 10, 2024 at 2:55 pm

    Мы – команда мастеров, создающих кухни мечты для каждого клиента. Вдохновляйтесь идеями и воплощайте их в жизнь с нами https://kupitkuhnyumagazin.ru/!

  34. Reply
    Short Hairstyles
    May 12, 2024 at 8:29 am

    I have noticed that online diploma is getting favorite because attaining your degree online has become a popular alternative for many people. Quite a few people have not really had a possibility to attend a normal college or university nonetheless seek the raised earning potential and career advancement that a Bachelor Degree provides. Still others might have a college degree in one training but would want to pursue anything they now have an interest in.

  35. Reply
    Matthewtig
    May 14, 2024 at 8:18 pm

    Участвуйте в увлекательных мастер-классах и соревнованиях, чтобы стать настоящим шеф-поваром https://kupitkuhnyucena6.ru/!

  36. Reply
    facebook vs eharmony to find love online
    May 16, 2024 at 1:42 am

    What i don’t realize is actually how you’re not actually much more well-liked than you may be now.

    You’re so intelligent. You understand therefore considerably in terms of this matter, produced me
    personally consider it from numerous various angles.
    Its like women and men don’t seem facebook vs eharmony to find love online be interested
    unless it is one thing to accomplish with Woman gaga! Your own stuffs nice.

    Always deal with it up!

  37. Reply
    Bryanmyday
    May 17, 2024 at 2:29 pm

    Want to improve your SEO rankings and save time? Our premium databases for XRumer and GSA Search Engine Ranker are just what you need!
    What do our databases include?
    • Active links: Get access to constantly updated lists of active links from profiles, posts, forums, guestbooks, blogs, and more. No more wasting time on dead links!
    • Verified and identified links: Our premium databases for GSA Search Engine Ranker include verified and identified links, categorized by search engines. This means you get the highest quality links that will help you rank higher.
    • Monthly updates: All of our databases are updated monthly to ensure you have the most fresh and effective links.

    Choose the right option for you:
    • XRumer premium database:
    o Premium database with free updates: $119
    o Premium database without updates: $38

    • Fresh XRumer Database:
    o Fresh database with free updates: $94
    o Fresh database without updates: $25

    • GSA Search Engine Ranker Verified Links:
    o GSA Search Engine Ranker activation key: $65 (includes database)
    o Fresh database with free updates: $119
    o Fresh database without updates: $38

    Don’t waste time on outdated or inactive links. Invest in our premium databases and start seeing results today!
    Order now!
    P.S. By purchasing GSA Search Engine Ranker from us, you get a high-quality product at a competitive price. Save your resources and start improving your SEO rankings today!
    To contact us, write to telegram https://t.me/DropDeadStudio

  38. Reply
    Zane Parrotte
    May 19, 2024 at 10:27 am

    Would you be interested in exchanging links?

  39. Reply
    Lottery defeater
    May 20, 2024 at 9:07 am

    I’ve recently started a website, the info you provide on this site has helped me tremendously. Thank you for all of your time & work.

  40. Reply
    Zen cortex reviews
    May 20, 2024 at 10:58 am

    Wow, superb weblog layout! How lengthy have you been running a blog for? you make blogging look easy. The total glance of your website is excellent, let alone the content material!

  41. Reply
    Sumatra slim belly tonic review
    May 20, 2024 at 5:37 pm

    Howdy are using WordPress for your blog platform? I’m new to the blog world but I’m trying to get started and create my own. Do you need any html coding knowledge to make your own blog? Any help would be really appreciated!

Leave a Reply

Your email address will not be published. Required fields are marked *