ML.Net – A Machine Learning Framework for .Net Developers
ML.NET is a free, open-source machine learning framework created by Microsoft, designed specifically for .NET developers to build, train, and deploy custom ML models using C# or F# — without needing to leave the .NET ecosystem.
Why ML.NET Exists
Most ML tooling is built around Python. ML.NET fills the gap for teams already invested in the .NET stack, letting them integrate machine learning directly into existing C#/.NET applications without switching languages or runtimes.
Key Features
- Cross-Platform: Runs on Windows, Linux, and macOS.
- AutoML: Automatically tries multiple algorithms and hyperparameters to find the best model.
- Model Builder: A visual, low-code interface within Visual Studio.
- ONNX Support: Ability to import and run models trained in other frameworks like TensorFlow or PyTorch.
Supported ML Tasks
| Task | Example Use Case |
|---|---|
| Classification | Sentiment analysis, spam detection |
| Regression | Price prediction, demand forecasting |
| Clustering | Customer segmentation |
| Anomaly Detection | Fraud or fault detection |
| Recommendation | Product recommendations |
Typical ML.NET Workflow
- Load data using ML.NET's IDataView abstraction.
- Build a training pipeline with data transforms and an algorithm.
- Train and evaluate the model using built-in metrics.
- Save the trained model as a .zip file and integrate it into a .NET application.
A Complete Sentiment Model in C#
The fastest way to understand ML.NET is to follow one small project from data file to prediction. This example trains a model that labels short product reviews as positive or negative. After adding the Microsoft.ML NuGet package with dotnet add package Microsoft.ML, the whole program fits in one file:
using Microsoft.ML;
using Microsoft.ML.Data;
var ml = new MLContext(seed: 1);
// 1. Load a tab-separated file: Text, Label (true = positive)
IDataView data = ml.Data.LoadFromTextFile<Review>("reviews.tsv", hasHeader: true);
var split = ml.Data.TrainTestSplit(data, testFraction: 0.2);
// 2. Turn text into numeric features, then add a trainer
var pipeline = ml.Transforms.Text.FeaturizeText("Features", nameof(Review.Text))
.Append(ml.BinaryClassification.Trainers.SdcaLogisticRegression());
// 3. Train and evaluate on data the model has not seen
var model = pipeline.Fit(split.TrainSet);
var metrics = ml.BinaryClassification.Evaluate(model.Transform(split.TestSet));
Console.WriteLine($"Accuracy: {metrics.Accuracy:P2}, F1: {metrics.F1Score:F2}");
// 4. Save, then predict a single review
ml.Model.Save(model, data.Schema, "sentiment.zip");
var engine = ml.Model.CreatePredictionEngine<Review, ReviewPrediction>(model);
var result = engine.Predict(new Review { Text = "Fast delivery and great quality" });
Console.WriteLine($"{result.PredictedLabel} ({result.Probability:P0})");
public class Review
{
[LoadColumn(0)] public string Text { get; set; } = "";
[LoadColumn(1)] public bool Label { get; set; }
}
public class ReviewPrediction
{
[ColumnName("PredictedLabel")] public bool PredictedLabel { get; set; }
public float Probability { get; set; }
}
What each part is doing
- MLContext is the starting point for every ML.NET operation. Setting a seed makes results repeatable between runs.
- FeaturizeText handles tokenising, normalising and building n-gram features, so you do not write that code yourself.
- The trainer looks for columns named
LabelandFeaturesby default, which is why the class property and the transform output use those names. - The saved .zip contains both the data transforms and the trained model, so new text is processed exactly as the training text was.
Serving Predictions in a Web Application
A PredictionEngine is quick but not thread-safe. In an ASP.NET Core API, many requests arrive at once, so sharing one engine causes errors or wrong results. The Microsoft.Extensions.ML package provides a PredictionEnginePool that you register in dependency injection and then inject into controllers or minimal API handlers. It can also reload the model file when you replace it with a retrained version.
For batch scoring of many rows, skip the prediction engine entirely and call model.Transform() on an IDataView, which is more efficient.
When ML.NET Fits and When It Does Not
| Choose ML.NET when | Consider Python tools when |
|---|---|
| The product is already a .NET application | Data scientists on the team work mainly in Python notebooks |
| You need classic tasks on tabular or text data | You need cutting-edge deep learning research models |
| Predictions must run inside the app, without a separate service | You rely on a large ecosystem of specialised libraries |
The ONNX support gives a middle path: a model can be trained in Python, exported to ONNX and then scored inside a .NET service.
Mistakes to avoid
- Reporting metrics on the training set instead of a held-out test set.
- Defining input classes whose column types do not match the file, such as reading a "yes"/"no" column straight into a
bool. - Retraining without versioning the model files, which makes it hard to roll back a worse model.
Ready to master Machine Learning?
Build real-world machine learning skills with hands-on projects, mentor-led sessions, and industry-relevant tools.