Updated on
ML.NET is Microsoft’s framework for machine learning in C#. With it, we train a model on our own data, measure how well it predicts, save it to a file and call it from any .NET application, without leaving C#.
Let’s build a small credit-risk classifier with ML.NET 6 on .NET 11, from a CSV file to a prediction. Along the way, we’ll see why a model that is right about four times out of five can still do no better than a one-line guess.
Machine learning is one of the most exciting and fastest-moving fields in computer science. Tools such as ChatGPT are built on it, and that alone should make C# developers sit up and take notice.
What Is Machine Learning and How Does ML.NET Enable It?
ML.NET is Microsoft’s machine learning framework for .NET. We use it to train, evaluate and run machine learning models in C#, inside the same application that uses them.
Machine learning is a way of finding patterns in data. We give an algorithm examples with known outcomes, and it learns rules that predict the outcome for new data.
Building that from scratch takes a lot of specialized knowledge, and ML.NET wraps it in an API a C# developer can read. An MLContext object is the entry point. Its catalogs create data loaders, transforms and trainers, and we chain them into a pipeline. Calling Fit() on the pipeline trains a model, which is an ITransformer that turns input rows into predictions.
ML.NET and its add-on packages cover classification, regression, anomaly detection, recommendations and forecasting, and they can run pretrained ONNX and TensorFlow models. A trained model saves to a single .zip file that our application loads at run time.
ML.NET provides a range of algorithms for supervised and unsupervised learning, explained below, as well as tools for data preparation, training, evaluation, and deployment.Â
One of the key advantages of ML.NET is that it integrates seamlessly with the .NET ecosystem. It makes it easy to incorporate machine learning functionalities into our C# applications. This means we can build machine learning models and deploy them alongside our existing code without learning new programming languages or tools.
ML.NET also provides a range of features for optimizing the performance of machine learning models, including hyperparameter tuning, feature (the ML-specific term) selection, and automatic model selection. This makes it easier to build models that are accurate and reliable, even when working with large and complex datasets.
Setting up the Development Environment
Let’s see how to add ML.NET to our project. The first thing we need to do is to install the required ML.NET packages. We can do it from the command line:
dotnet add package Microsoft.ML
Or from Visual Studio’s Package Manager Console:
PM> Install-Package Microsoft.ML
Or by searching for ML.NET in the NuGet package manager. Here is the same search on nuget.org:
Here we can see there are multiple ML.NET packages available to install. Depending on project requirements, we might need to install additional packages, but for our example, we will install only the Microsoft.ML package, version 6.0.0 at the time of writing.
Understanding Supervised Learning
To better understand machine learning, it’s important to know three common categories of machine learning: supervised, unsupervised, and semi-supervised.
Unsupervised learning involves training a model on unlabeled data to find patterns or structures within the data, while semi-supervised learning combines labeled and unlabeled data to train a model.
We will focus on the supervised learning model.
Supervised learning involves training a model on labeled data, where each data point is associated with a known outcome. The goal of supervised learning is to use this labeled data to build a model that can accurately predict outcomes for new, unlabeled data.
Several algorithms are commonly used in supervised learning, including linear regression, logistic regression, decision trees, and more. The details of these algorithms are beyond the scope of this article, but each has its own strengths and weaknesses, and the choice of algorithm will depend on the specific problem being solved and the characteristics of the data.
One of the key benefits of supervised learning is that we can use it to build models for a wide range of applications, from predicting customer behavior to detecting fraud. However, it does require access to labeled data. When we talk about labeled data, we refer to a dataset that has been assigned one or more categories or labels. Data categorization or labeling is usually done manually, and it serves as a basis for the machine learning model to learn from. Considering this, it is not strange that gathering data can be challenging in some cases.
Supervised learning is a powerful tool for building machine learning models to make accurate predictions and automated decisions based on labeled data.
How Do We Build and Train a Model With ML.NET?
Building a model with ML.NET comes down to six steps, in this order.
First, we load the data into an IDataView with LoadFromTextFile() and split it into a training set and a test set with TrainTestSplit().
Second, we prepare the data. Trainers work with numbers, so we turn the text label into a key with MapValueToKey() and gather the input columns into one Features vector with Concatenate().
Third, we append a trainer to that pipeline and call Fit(). This is the training step, and it returns the model.
Fourth, we run the model over the test set and read its metrics from Evaluate().
Fifth, we save the model to a file with Save().
Finally, the application loads the saved model and calls Predict() through a PredictionEngine.
Let’s walk through each step on a real dataset of 1,000 credit applicants and predict whether a new applicant is a good or a bad credit risk.
Here’s the whole pipeline we’re about to build:

The ML.NET pipeline in this article, from the CSV file to a prediction.
It all starts with the data. For our example, we will use Credit Risk Customers dataset available on Kaggle:
This data set contains 21 columns with credit-related customer data. To simplify our example, we will use only columns credit_amount, duration, age, and class.
duration is the loan length in months, credit_amount is the loan amount, and age is the applicant’s age in years.
The class column is the one we want to predict based on other values.Â
Let’s define our ModelInput class:
using Microsoft.ML.Data;
namespace MachineLearningInCsharpEngine.DataModels.MulticlassClassification;
public class ModelInput
{
[ColumnName("duration"), LoadColumn(1)]
public float Duration { get; set; }
[ColumnName("credit_amount"), LoadColumn(4)]
public float CreditAmount { get; set; }
[ColumnName("age"), LoadColumn(12)]
public float Age { get; set; }
[ColumnName("class"), LoadColumn(20)]
public string Class { get; set; } = string.Empty;
}
Here we map our properties with the column names in the dataset.
Next, let’s define ModelOutput class:
using Microsoft.ML.Data;
namespace MachineLearningInCsharpEngine.DataModels.MulticlassClassification;
public class ModelOutput
{
[ColumnName("PredictedLabel")]
public string Prediction { get; set; } = string.Empty;
}
It contains only Prediction property which is enough for the algorithm we use.Â
Now we define ModelBuilder class:
using Microsoft.ML;
namespace MachineLearningInCsharpEngine.DataModels.MulticlassClassification;
public class ModelBuilder
{
private MLContext _mlContext = new MLContext(seed: 0);
private PredictionEngine<ModelInput, ModelOutput> _predictionEngine = null!;
private IDataView _trainingDataView = null!;
private IDataView _testDataView = null!;
private ITransformer _mlModel = null!;
...
}
Here we define private variables:
_mlContext– the common context for allML.NEToperations_predictionEngine– aPredictionEngineinstance used to getModelOutputfromModelInputbased on the trained model_trainingDataView– a data collection (IDataView) used for training the model_testDataView– a data collection (IDataView) used to evaluate the trained model_mlModel– anITransformerinstance used to transform the data
Next, we will define a CreateModel() method :
public void CreateModel(string dataFilePath, string savingPath)
{
LoadAndSplitData(dataFilePath);
var pipeline = PreProcessData();
BuildAndTrainModel(_trainingDataView, pipeline);
EvaluateModel();
SaveModel(savingPath);
CreatePredictionEngine();
}
We can divide machine learning model development into steps. We will examine these steps through our example.
Collecting Data
Although it’s important to note that data collection can often represent a fair amount of time and research, our focus will just be on loading the data. For this, we define a LoadAndSplitData() method:
private void LoadAndSplitData(string dataFilePath)
{
var allDataView = _mlContext.Data.LoadFromTextFile<ModelInput>(
path: dataFilePath,
hasHeader: true,
separatorChar: ',');
var split = _mlContext.Data.TrainTestSplit(allDataView, testFraction: 0.1);
_trainingDataView = split.TrainSet;
_testDataView = split.TestSet;
}
First, we load the data from our data source. We use the LoadFromTextFile() method to do so. By default, it expects tab-delimited content. In our example, we set the separator character to comma (,) and specify that our data has a defined header row.
Next, we need to split our data into train and test data. For this, we use the TrainTestSplit() method, which splits our data by the testFraction parameter. A 0.1 value means we use 90% of the data as a train set while the remaining 10% is a test set.
The split is random, so why do we get the same split every time? Because of the seed we passed to MLContext in the constructor. The Microsoft Learn reference for MLContext says that with a fixed seed, “results are repeatable and will remain the same across multiple runs”. Without a seed, each run trains on a different 90 percent of the data.
With 1,000 rows, a tenth is about 100. Our test set holds 98 applicants on every run.
The seed doesn’t pin down everything, though. By default, our trainer splits its work across several threads, and the ML.NET source code notes that determinism is not guaranteed in that mode. So the metrics we print in a moment can come out a little different on your machine, or on a second run on ours. Setting the trainer’s NumberOfThreads option to 1 switches it to a single-threaded path, which the source code describes as deterministic.
Preparing The Data
Our next step is pre-processing the data. This usually involves cleaning the data, handling missing data, and other actions to make the data as neat as possible for our task. Eventually, this will also lead to better model performance:
public IEstimator<ITransformer> PreProcessData()
{
var pipeline = _mlContext.Transforms.Conversion
.MapValueToKey(inputColumnName: "class", outputColumnName: "Label")
.Append(_mlContext.Transforms.Concatenate("Features", "duration", "credit_amount", "age"));
return pipeline;
}
As a preparatory step in our example, we need to convert the column class, which is a string type, to a numerical value. We do that with the MapValueToKey() method, where we specify input and output columns.Â
In the machine learning context, we refer to a feature as a measurable aspect or property of the data that can be used to make predictions or to identify patterns in the dataset. Machine learning models are based on mathematical operations or statistical models that rely on numerical data to calculate probabilities and make predictions. Thus, we must define our data as numerical objects called features vector. For that, we use the Concatenate() method to convert our input values duration, credit_amount, and age to a Features vector.
Note that we chain Append() onto MapValueToKey(). Append() doesn’t change the estimator we call it on. It returns a new chain, so if we called it on pipeline and ignored the result, the Features column would never reach the trainer.
Training the Model
Finally, we are ready to train our model:
public IEstimator<ITransformer> BuildAndTrainModel(IDataView trainingDataView, IEstimator<ITransformer> pipeline)
{
var trainingPipeline = pipeline
.Append(_mlContext.MulticlassClassification.Trainers.SdcaNonCalibrated("Label", "Features"))
.Append(_mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabel"));
_mlModel = trainingPipeline.Fit(trainingDataView);
return trainingPipeline;
}
In the first place, we need to choose an algorithm. As mentioned, selecting the right algorithm is a topic that is out of the scope of this article, and we may cover it in the future. But for our purposes, we will move forward with the SdcaNonCalibrated algorithm.
We do that by appending a multiclass classification SdcaNonCalibrated trainer to the input pipeline.
The highlighted line shows the step in which we convert the predicted labels from their numeric form to their original string representation using MapKeyToValue() method.
Once the training pipeline is defined, we use it to train (or fit) the model to the training data using the Fit() method. During this process, the model learns to identify the patterns and uses this knowledge to make new predictions.
The trained model is then stored in the _mlModel variable.
Evaluating the Model
The next step in the process is model evaluation. In other words, we want to see how well our model works on a data set with known data. We do that with the Evaluate() method:
public void EvaluateModel()
{
var testMetrics = _mlContext.MulticlassClassification.Evaluate(_mlModel.Transform(_testDataView));
Console.WriteLine($"Evaluation Metrics:");
Console.WriteLine($"- MicroAccuracy:\t{testMetrics.MicroAccuracy:0.###}");
Console.WriteLine($"- MacroAccuracy:\t{testMetrics.MacroAccuracy:0.###}");
Console.WriteLine($"- LogLoss:\t\t{testMetrics.LogLoss:#.###}");
Console.WriteLine($"- LogLossReduction:\t{testMetrics.LogLossReduction:#.###}");
Console.WriteLine(testMetrics.ConfusionMatrix.GetFormattedConfusionTable());
}
And these are our results:
Evaluation Metrics: - MicroAccuracy: 0.765 - MacroAccuracy: 0.495 - LogLoss: 2.743 - LogLossReduction: -4.577
A MicroAccuracy of 0.765 looks decent, but always answering “good” would score 0.806 on this test set. Your numbers may differ a little, for the threading reason above. We come back to them right after we save the model.
We also define a method to save our model to a file:
private void SaveModel(string saveModelPath)
{
_mlContext.Model.Save(_mlModel, _trainingDataView.Schema,
Path.Combine(Environment.CurrentDirectory, saveModelPath));
}
To be able to make predictions on new data, we also need to create a PredictionEngine:
private void CreatePredictionEngine()
{
_predictionEngine = _mlContext.Model.CreatePredictionEngine<ModelInput, ModelOutput>(_mlModel);
}
How Do We Know If Our ML.NET Model Is Any Good?
A model is good when it beats the simplest possible guess, and accuracy alone does not tell us whether it does.
Our test set has 98 applicants, and 79 of them are good credit risks. A program that answers “good” every time is right 79 times out of 98, a MicroAccuracy of 0.806. Our model scored 0.765 above and 0.806 in a second run, so it never beat that one-line program.
MacroAccuracy shows why. It averages the accuracy of each class, so the small “bad” class counts as much as the big “good” one. At 0.495 and 0.54, it says the model hardly ever recognizes a bad applicant.
The confusion matrix confirms it: of the 19 bad applicants, the model flagged one in the first run and two in the second.
Before we trust an accuracy figure, we compare it with the share of the largest class and print the confusion matrix. When the model can’t beat that baseline, we revisit how we prepared the data.
This is what the extra line in EvaluateModel() prints:
Confusion table
||======================
PREDICTED || good | bad | Recall
TRUTH ||======================
good || 74 | 5 | 0.9367
bad || 18 | 1 | 0.0526
||======================
Precision || 0.8043 | 0.1667 |
Each row is the truth and each column is the prediction. In this run, the model labels 92 of the 98 applicants “good”, and only one of the 19 bad applicants lands in the “bad” column.
Where does that come from? Part of the answer is in Microsoft’s documentation for our trainer: its trainer table lists “Is normalization required? Yes”, and our pipeline never normalizes. Our three features live on very different scales: duration runs from 4 to 72, age from 19 to 75, and credit_amount from 250 to 18,424. Adding a normalizer takes one line in PreProcessData():
var pipeline = _mlContext.Transforms.Conversion
.MapValueToKey(inputColumnName: "class", outputColumnName: "Label")
.Append(_mlContext.Transforms.Concatenate("Features", "duration", "credit_amount", "age"))
.Append(_mlContext.Transforms.NormalizeMinMax("Features"));
We trained both versions in our second run. The normalized model caught three of the 19 bad applicants where the plain one caught two, and MacroAccuracy went from 0.54 to 0.566, a small step. Normalization alone won’t make three columns predict credit risk well. The dataset has 21 columns and we use three, so the next section’s techniques still apply.
The two log-loss lines tell us little here. Log-loss measures how far predicted probabilities are from the truth, and Microsoft’s documentation for the SDCA trainers says the scores can be read as class probabilities only when the model is a maximum entropy classifier. SdcaNonCalibrated is not one. Our second run shows what that means: it printed a log-loss that rounds to 0 and a log-loss reduction of 1, the values of a perfect model, for a model that missed 17 of 19 bad applicants. So we read the accuracy figures and the confusion matrix instead. If we need probabilities, SdcaMaximumEntropy produces them.
| Metric | What it measures | Our model, two runs | How to read it |
|---|---|---|---|
| MicroAccuracy | Share of all test rows predicted correctly | 0.765 and 0.806 | Compare it with the share of the largest class, 0.806 here |
| MacroAccuracy | Average of the per-class accuracies, each class weighted equally | 0.495 and 0.54 | With two classes, a value near 0.5 can mean one class is mostly missed |
| Confusion matrix | Count of rows for every true and predicted class pair | 1 and 2 of 19 bad caught | Read the recall of the smaller class first |
| LogLoss | Distance between predicted probabilities and the true label, lower is better | 2.743 and about 0 | Meaningful only for a trainer that outputs probabilities |
| LogLossReduction | Advantage of the classifier over a random prediction, 1 is perfect | -4.577 and 1 | Same caveat as LogLoss |
Any classifier trained on unbalanced data, in any library, can look accurate while it ignores the class we care about. Counting the largest class and printing the confusion matrix takes a few lines, so we do it in every project.
Improving Model Performance
Similar to choosing the right algorithm in the first place, improving model performance requires additional knowledge and experimentation to achieve optimal performance. Let’s explore some of the techniques we can use to improve our model:
- Algorithm Selection – Not surprisingly, our chosen algorithm can significantly impact model performance. It is important we consider the specific characteristics of the data and the problem being addressed because certain algorithms may be better suited to certain types of data or tasks.
-
Feature Engineering – This involves selecting or creating new features from the raw data that are more informative or relevant to the prediction task. This can involve scaling or transforming existing features, creating new features from existing ones, or selecting a subset of the most important features.
-
Hyperparameter Tuning – Many machine learning algorithms have hyperparameters we can fine-tune to optimize the model’s performance. Hyperparameters are settings that are not learned from the data but rather are set manually by the user. Techniques such as grid search or randomized search can be used to find the optimal values for these hyperparameters.
-
Regularization – A technique used to prevent overfitting, where the model is too complex and fits the training data too closely, eventually leading to poor generalization performance on new data. Thus, regularization involves adding a penalty term to the loss function that encourages the model to have simpler weights or coefficients.
-
Ensemble Methods – These involve combining multiple models to improve performance. Examples include bagging, boosting, and stacking. Consequently, these methods can help to reduce overfitting. Furthermore, they can improve model stability and increase predictive accuracy.
-
Data Augmentation – Involves generating additional training data by applying transformations to the existing data. Augmentation can help increase the training set’s size and thus improve the model’s ability to generalize to new data.
We don’t have to do all of this by hand. The AutoML API in ML.NET tries several trainers and hyperparameters for us and reports the best model it finds. Model Builder puts the same search behind a Visual Studio wizard, and the ML.NET CLI runs it from the terminal.
Deploying the Model
This is where all of our hard work and preparation finally pay off. For deploying our model, we define a LoadModel() method in our ModelBuilder class:
public void LoadModel(string path)
{
_mlModel = _mlContext.Model.Load(path, out _);
_predictionEngine = _mlContext.Model.CreatePredictionEngine<ModelInput, ModelOutput>(_mlModel);
}
To make the actual prediction, we define thePredict() method:
public ModelOutput Predict(ModelInput input)
{
return _predictionEngine.Predict(input);
}
And lastly, we can use our trained model in the application:
using MachineLearningInCsharpEngine.DataModels.MulticlassClassification;
var modelBuilder = new ModelBuilder();
modelBuilder.LoadModel(Path.Combine(AppContext.BaseDirectory, "trainedModel.zip"));
var modelInput = new ModelInput()
{
Age = 22,
CreditAmount = 15000,
Duration = 60
};
var prediction = modelBuilder.Predict(modelInput);
Console.WriteLine($"\nExample input class is {prediction.Prediction.ToUpper()}!");
We load the model from the application’s folder, where the sample project copies trainedModel.zip on every build, so the program finds it no matter which directory we start it from. In a project of our own, we create that file first by calling modelBuilder.CreateModel("credit_customers.csv", Path.Combine(AppContext.BaseDirectory, "trainedModel.zip")) before LoadModel(), with the CSV file in the folder we run the app from. For a 22-year-old asking for 15,000 over five years, our model answers:
Example input class is BAD!
Here we can see the usage of the model is pretty straightforward in practice. One caution for web apps: a PredictionEngine is not thread-safe, so in ASP.NET Core we register a PredictionEnginePool from the Microsoft.Extensions.ML package instead of sharing one engine across requests.
What Can We Do With ML.NET?
Now we know how to build, train and use a simple ML model. Let’s quickly mention some examples of what we can do with ML.NET:
-
Image and Video Analysis: Classification of images or videos based on their content, detecting objects or faces in images, or performing other tasks related to image or video analysis.
-
Natural Language Processing: Sentiment analysis, text classification, or sentence similarity.
-
Anomaly Detection: Identification of outliers in data sets, which can be useful for detecting fraud, network intrusions, or other unusual events.
-
Predictive Modeling: Building predictive models that can forecast future trends or identify patterns in data.
-
Recommender Systems: Building personalized recommendation systems that can suggest products, movies, or other items based on a user’s preferences.
-
Imported Models: Running pretrained ONNX or TensorFlow models, which is how speech recognition or translation models get into a .NET application.
And when we need probabilistic models rather than trained classifiers, Microsoft’s Infer.NET library covers that ground.
Conclusion
In this article, we’ve covered the basic concepts of machine learning and explored how to create a simple ML model in C# using ML.NET. We also learned to check a model against a simple baseline, saw techniques to improve its performance and proposed some interesting ML.NET usage scenarios.Â
In the end, we can conclude that ML.NET is a great addition to the Microsoft stack that enables us, as C# developers, to keep pace with this exciting and rapidly evolving technology.
Tested with .NET 11 (SDK 11.0.100, runtime 11.0.0), Microsoft.ML 6.0.0 and MSTest 4.5.3.








