How to implement machine learning in .NET applications using ML.NET?

Machine learning is a part of artificial intelligence that allows machines to learn through data. It is a science that helps solve various problems and/or predict various business aspects based on previous data. Machine learning uses multiple patterns to make predictions based on the available data with the application instead of making any decisions programmatically. It is a powerful tool for industries like the stock market, health care and many more to identify and analyze sales and plan for business growth.

Now, to implement machine learning in .NET applications, a framework is provided by Microsoft named ML.NET. Using ML.NET, we can make automatic predictions for different scenarios using the data available with the application. It works in both online & offline modes. For online mode, it supports Web API, and for offline mode, it supports Console App. ML.NET works with Windows, Linux & macOS using .NET Core and Windows 64 bit all platforms using .NET Framework.

Some of the critical features of ML.NET are:

  • Open Source
  • Cross Platform
  • Code First Approach
  • Support to On-Premise Architecture

ML.NET provides various scenarios to create models for automated ML predictions. However, few methods support local environments, i.e., on-premise, and few support cloud or both. Below are the different scenarios available in ML.NET to create predictions.

  • Data Classification: Classifies text data, e.g., predicts if the statement is positive or negative. This scenario is only available in the local environment.
  • Value Prediction: Predicts the numeric value from the available data, e.g., predicts the land value based on the available information according to the size, location, etc. This scenario is only available in the local environment.
  • Image Classification: Classifies the images, e.g., predicting the image if it is of a dog or a cat. This scenario supports both local and cloud (Azure) environments.
  • Recommendation: Produces the list of suggested items for a particular user, e.g., based on previous purchases. This scenario is only available in the local environment.
  • Object Detection: Detect objects in any image, e.g., identifying cars in a snap and highlighting cars with boundaries. This scenario supports only the cloud (Azure) environment.

Except for the five scenarios mentioned above, there are three more scenarios that ML.NET does not yet support. But, in the future, they will also be available to use.

  • Anomaly Detection: Detects abnormalities in the data, e.g., fraudulent banking transactions.
  • Forecasting: Predicts future values based on the previously observed values, e.g., a hike in fuel rates.
  • Clustering: Identify groups of related items without any pre-existing labels or categories.

Check out the below steps to implement machine learning in .NET applications using ML.NET

Now, let's try to create a machine-learning project and see how it works for the data provided for prediction. We will use the "Data Classification" scenario in this example to build our machine learning project. But first, open Microsoft VS and create a console application project.

Step 1:

Select "C#" as a programming language in the drop-down as shown above. It would be chosen if C# were selected as a default programming language while installing Visual Studio.

Step 2:

Select the project type "Console" in the third drop-down to filter the list of project types below.

Step 3:

Select "Console App (.NET Framework)" from the filtered project type list and click "Next."

Step 4:

Name your project and make sure that the checkbox to place the solution and project in the same directory is unchecked and click on "Create." It will create the project and will load the Program.cs file by default.

Step 5:

Start working with the "Machine Learning Model." Right-click on your project, click on Add, and select Machine Learning Model.

Step 6:

It will open a new window to add a new item. Make sure that Machine Learning Model (ML.NET) is selected in the list and name the model as a statement.mbconfig, and click on Add.

Step 7:

After clicking Add, you can see that a new file named statement.mbconfig is added to the solution, and the Model Builder UI is opened in a new docked window, as displayed in the following screenshot. The mbconfig file is a JSON file that keeps track of the UI state. This model builder will guide us toward creating the machine-learning model for our project. First, explore the various stages of developing a machine-learning model.

Step 8:

As discussed earlier, we will be creating the model for the Data Classification scenario. So let's select our procedure and proceed to the next step.

Step 9:

After selecting the scenario, the next step will be to choose the environment where we will train our model. As I mentioned while describing the scenarios, the Data Classification scenario only supports local or on-premise environments to train the model so that we will see only one option on the environment screen. Select Local (CPU) and click on Next Step.

Step 10:

Clicking Next Step will move us to the Data screen, where we will have to provide the data on whose basis the model will perform the predictions. There are two options to provide data to the model: using some file (.csv, .tsv, .txt) or through SQL Server. In this example, we will use a .txt file to provide data to the model, which we will place in the same project folder. For this example, I have downloaded the sample file from Microsoft's site, but we can create our own also as per our data prediction. The file data will look somewhat like the below screenshot.

Step 11:

Once we browse and select our data source file, the file data will be displayed in the Data Preview section.

The above screenshot shows that in the data preview section, the column headers are col0 & col1. The reason is that our source file does not have any header for the data, so the system auto-generated the titles. The most crucial point here is that the columns that help to predict the output are by default called Features, and the column to predict is the column that you expect, i.e., in our case, col0 will be called Feature, and col1 will be called Label, i.e., column to predict.

Step 12:

As mentioned, col1 will be the Label, so we need to select col1 in the column to predict (Label) drop-down and click on the Next step button.

Step 13:

We will now train our model with the help of the dataset we provided. Model builder appraises many models by varying the algorithms and settings depending on the time duration to find the best-performing model. For our dataset, we will keep the time to train at 60 seconds so that the model builder can evaluate more models. Important to note that the time to prepare will be higher for larger datasets, and sometimes the model builder himself adjusts the time as per the dataset size. Let's set the time to train to 60 seconds and click on Start training.

Once the training is completed, the model builder displays the training results also. The model builder majorly displays four parameters.

  • Best Accuracy: It displays the accuracy of the best model found by the model builder. The more accuracy means that the model prediction was correct towards the test data.
  • Best Model: It displays the algorithm's name whose performance was best during the exploration.
  • Training Time: This is the total time for training or exploring models.
  • Models Explored (total): This is the number of models explored by the model builder during the training time provided.

In the above screenshot, we can see that after the successful training, the model builder automatically created the code for the scenario in these two files, which we will see later in this article. So, let's move to the next step by clicking the Next step button.

Step 14:

We will evaluate our model using this screen. As we can see that it has already chosen the best algorithm or model to predict the data. As mentioned earlier, in our dataset, col0 is the Feature on which we will perform the prediction, and by default, the first row from our dataset is displayed in the textbox to predict. So let's click on the Predict button and see the results.

Here one stands for Positive statement, and 0 stands for Negative statement, and the results show that the model predicted that the information is 75% Positive. Also, we can see in the dataset (screenshot attached above) that the prediction value against this statement is 1 in the dataset.

So now let's try one Negative statement also.

Here we see that the model prediction is more accurate for the provided statement, and it is saying that the statement is 79% Negative. Now it's time to consume this model; this step will give a sample code snippet to predict some input. It also allows you to add another project where you want to finish this prediction model. Finally, it provides two project templates to be added to the solution: a console app and a web API.

Let's get an overview of the two classes created by the model builder.

Please note that these two classes are, by default, created by the model builder while setting up the model.

Statement. training.cs: The purpose of this class is to retrain the model in case of any changes. It contains two methods: one (BuildPipeline) to build the pipeline used by the model builder and the other (RetrainPipeline) to retrain the builder.

Statement.consumption.cs: The main purpose of this class is to create the prediction engine, predict on model input and return the prediction result via model output.

Step 15: 

Now, let's write some code to predict inside our console application created and see the output. We will write some code inside Program. cs to use the prediction method developed by the model builder.

Please find the output below:


ML.NET is an excellent framework for implementing machine learning in current industry scenarios, as it can analyze large data sets to provide industry patterns and trends. Moreover, it is delivered with various use scenarios to help us identify our business needs and improve our business pattern. For example, massive competition in the current market could be an excellent tool to predict and improve the business by getting relevant results based on previous industry data. In this document, we implemented the ML for text data analysis using a console application, but there is one more way to implement it: Web API. Also, we have gone through only one scenario, but many more can help analyze the data for our business. For more Hire Dedicated .Net Developers to implement the ML.NET framework in the ML industry. 

About Author

Manektech Team

ManekTech Team

ManekTech is a well-known software development and IT consulting company, providing custom software, website, and mobile app development services. ManekTech has own content writing and development team who writes content on various and trending technology that it serves currently.

Need a consultation?

Drop us a line! We are here to answer your questions 24/7

Areas we serve


4100 NW Loop 410, Suite 200, San Antonio, Texas, USA 78229


7 Artisan Place Harrow, HA3 5DS


4th Floor, Timber Point, Prahaladnagar Road, Ahmedabad, Gujarat - 380015