
Jun 02, 202530 min read
How to Build AI Applications in .NET Using ML.NET (With Code Examples)
Want to build intelligent applications using .NET? In this hands-on guide, you’ll learn how to use ML.NET to create machine learning models in C —no Python or advanced…
Artificial Intelligence (AI) is no longer a futuristic buzzword reserved for research labs or billion-dollar tech giants. It’s quietly woven into our everyday experiences — from the recommendations we see on Netflix to the way our phones auto-complete messages. Businesses of all sizes are tapping into AI to automate decisions, personalize services, and uncover insights that were once buried in spreadsheets.
Yet for many developers, especially those in the .NET ecosystem, AI can still feel distant. There's a common misconception that machine learning and AI are only for Python experts or data scientists with PhDs. That couldn’t be further from the truth — and that's where this tutorial comes in.
Where .NET Fits into the AI Ecosystem
Microsoft's .NET framework has long been a powerful, enterprise-grade platform for building robust, scalable applications. But with the introduction of ML.NET, Microsoft has made it possible to bring AI into .NET applications — without having to switch languages, rewrite your stack, or rely on external cloud-based APIs.
ML.NET allows C# and F# developers to build custom machine learning models using familiar tools, IDEs, and workflows. Whether you're working on a WPF desktop app, an ASP.NET web API, or even a background service — ML.NET gives you a way to infuse intelligence directly into your existing applications.
Why ML.NET is Great for Beginners
Learning AI can feel overwhelming, especially when the first step often involves installing unfamiliar libraries, wrangling with Python environments, and understanding a mountain of math. ML.NET offers a gentler entry point.
With ML.NET, you can:
- Use strongly typed data classes (no pandas DataFrames required)
- Train models using intuitive APIs and fluent syntax
- Leverage Visual Studio’s Model Builder for a no-code experience
- Integrate your models seamlessly into production-grade .NET applications
And the best part? You don’t need to become a machine learning expert to start solving real problems with AI.
What You’ll Learn in This Tutorial
In this guide, we’ll walk you through everything you need to get started with AI using .NET — step by step.
Here’s what you’ll walk away with:
- A clear understanding of how machine learning works within the .NET world
- Hands-on experience building and training models using ML.NET
- Two practical projects: one for predicting house prices and another for performing sentiment analysis
- The confidence to apply what you’ve learned to your own applications
Whether you're a .NET developer looking to expand your skillset, or simply curious about how to dip your toes into the world of AI, this tutorial is designed to give you a practical, code-first foundation — no fluff, no hype.
Let’s get started.
What is ML.NET?
If you’re a .NET developer, chances are you’ve already mastered building applications that are fast, reliable, and scalable. But what if your app could learn from data — adapting its behavior over time, offering predictions, or making decisions without hardcoding every rule?
That’s exactly what ML.NET enables.
Overview of ML.NET
ML.NET is an open-source, cross-platform machine learning framework built specifically for .NET developers. It was developed by Microsoft and originally used internally in products like Bing Ads and Office. In 2018, it was released to the public, opening up powerful machine learning capabilities to everyday .NET developers — no need to learn Python or step outside of your familiar tooling.
With ML.NET, you can build, train, and consume custom machine learning models directly within your C# or F# applications. And it works across platforms — from Windows and macOS to Linux, and even mobile with Xamarin or MAUI in combination with ONNX.
Whether you’re adding a recommendation engine to your e-commerce app or predicting equipment failure in an industrial monitoring system, ML.NET gives you the tools to do it — in native .NET code.
Supported Tasks in ML.NET
ML.NET is surprisingly versatile for a framework that’s so developer-friendly. It supports a wide range of machine learning tasks, including:
- Regression
Predicting a continuous value — e.g., house prices, stock market trends, or delivery times. - Binary Classification
Answering yes/no questions — like spam detection, customer churn prediction, or sentiment analysis. - Multiclass Classification
Categorizing items into one of several classes — such as recognizing animal species from image data or routing support tickets by topic. - Recommendation
Suggesting products, content, or services — based on collaborative filtering (similar to what Netflix or Amazon does). - Clustering
Grouping similar data points together — useful in customer segmentation or anomaly detection. - Anomaly Detection
Identifying outliers — great for fraud detection or monitoring sensor data. - Time Series Forecasting
Predicting future values over time — like demand planning or sales forecasting. - Natural Language Processing (NLP)
Working with text data — extracting sentiment, keywords, or classification from raw text.
And it continues to grow, with support for image classification, model explainability, and integrations with deep learning models via ONNX.
ML.NET vs TensorFlow and PyTorch (Brief Comparison)
When most people hear "machine learning," they think of Python-based libraries like TensorFlow or PyTorch. These are powerful, industry-standard tools, especially for deep learning. But they come with steep learning curves, a data science-heavy focus, and a completely different ecosystem than most .NET developers are used to.
ML.NET takes a different approach.
It’s built for software engineers — not data scientists. The learning curve is shallower, the tooling is native to Visual Studio, and the syntax is fluent and readable for C# devs.
That said, ML.NET isn’t trying to compete with TensorFlow in areas like large-scale neural networks or computer vision research. But it does support integration with ONNX models, meaning you can train a deep learning model elsewhere (e.g., in PyTorch) and still consume it in your .NET app.
So if you want to get started with AI in .NET — without spending months learning the math behind backpropagation — ML.NET is your launchpad.
🛠️ Setting Up Your Development Environment
Before we dive into code, let’s get your development environment ready. One of the major advantages of working with ML.NET is that you can build machine learning models entirely within the comfort of your existing .NET setup — using tools you already know, like Visual Studio and C#.
No need for Jupyter notebooks, no wrestling with Python environments — just clean, structured development using your preferred .NET workflow.
Installing Visual Studio with .NET Desktop Development
To start working with AI in .NET, you’ll need Visual Studio 2022 or later (the Community Edition is free and works perfectly for this tutorial).
When installing Visual Studio:
- Launch the Visual Studio Installer.
- Under Workloads, check:
- ✅ “.NET desktop development”
- ✅ Optionally, “ASP.NET and web development” if you plan to use your models in APIs later.
- Click Install or Modify (depending on whether you're installing fresh or modifying an existing install).
This workload ensures you have the necessary tools for building C# applications, including ML.NET console projects.
Installing the ML.NET Model Builder (Optional but Recommended)
While we’ll mostly write code to keep things hands-on, Microsoft also provides a powerful visual tool called ML.NET Model Builder. This drag-and-drop extension helps you train models without writing a single line of code — and then auto-generates the code so you can learn how it works under the hood.
To install it:
- Open Visual Studio.
- Go to Extensions > Manage Extensions.
- Search for “ML.NET Model Builder”.
- Click Download, then restart Visual Studio when prompted.
Model Builder supports common machine learning scenarios like sentiment analysis, price prediction, and image classification — and makes rapid prototyping incredibly fast.
Creating Your First ML.NET Console App
Let’s build a basic skeleton to prepare for our first AI experiment in C#. This is the foundation for all your ML.NET projects.
- Open Visual Studio and create a new project.
- Select Console App (.NET Core) or Console App (.NET 6/7) depending on your setup.
- Name it something like
MLNetIntroand click Create.
Now, let’s add the ML.NET NuGet package:
Install-Package Microsoft.ML
Or using the .NET CLI:
dotnet add package Microsoft.ML
Once installed, ML.NET becomes part of your toolbox, ready to help you load data, train models, and make predictions — all in plain C#.
Folder Structure (Optional Best Practice)
To keep your project clean as we build, consider the following structure:
/MLNetIntro /Data ← CSV or JSON files /MLModels ← Trained models (.zip) /Services ← Code for training/prediction Program.cs
This isn’t mandatory, but it’s helpful as your application grows beyond a single file.
That’s it! Your environment is now fully set up for building intelligent applications using ML.NET in .NET. In the next section, we’ll dive into the core of machine learning in C#: understanding the ML.NET workflow — the heart of how models are built, trained, and used.
🔄 Understanding the ML.NET Workflow
If you're new to machine learning, it might feel like there’s some kind of wizardry going on behind the scenes. You give a model some data, and somehow it starts making predictions. But once you understand the ML.NET workflow, the process becomes surprisingly logical — even elegant.
At its core, every machine learning project in ML.NET follows a predictable five-step pipeline:
1. Load → 2. Transform → 3. Train → 4. Evaluate → 5. Predict
Let’s break each of these down — and walk through a simple “Hello AI World” demo along the way.
👋 Code Sample: Hello AI World with ML.NET
Let’s start with a tiny example: predicting whether a customer will buy a product based on their age and income. (Don’t worry — we’ll tackle larger real-world examples later.)
Step 1: Define your input and output data classes
public class CustomerData
{
public float Age;
public float Income;
public bool Purchased;
}
public class PurchasePrediction
{
public bool PredictedLabel;
}Step 2: Set up your ML.NET context and pipeline
using Microsoft.ML;
using Microsoft.ML.Data;
var mlContext = new MLContext();
// Step 1: Load sample data
var data = new List<CustomerData>
{
new CustomerData { Age = 25, Income = 30000, Purchased = false },
new CustomerData { Age = 45, Income = 70000, Purchased = true },
new CustomerData { Age = 35, Income = 50000, Purchased = true },
};
var trainingData = mlContext.Data.LoadFromEnumerable(data);
// Step 2: Transform features (combine Age + Income into a feature vector)
var pipeline = mlContext.Transforms.Concatenate("Features", "Age", "Income")
.Append(mlContext.BinaryClassification.Trainers.SdcaLogisticRegression());
// Step 3: Train the model
var model = pipeline.Fit(trainingData);
// Step 4: Make a prediction
var predictionEngine = mlContext.Model.CreatePredictionEngine<CustomerData, PurchasePrediction>(model);
var prediction = predictionEngine.Predict(new CustomerData { Age = 30, Income = 40000 });
Console.WriteLine($"Predicted purchase: {prediction.PredictedLabel}");📌 You’ve just built a working AI model — in about 20 lines of C#.
Now let’s take a closer look at what’s really happening under the hood.
🧩 Breaking Down the ML.NET Workflow
🪣 1. Load
You start by loading your data into ML.NET’s internal data structure: the IDataView.
Think of IDataView like a supercharged version of a table or spreadsheet. It’s optimized for performance and works with datasets that don’t even fit into memory.
IDataView dataView = mlContext.Data.LoadFromTextFile<MyData>("data.csv", hasHeader: true, separatorChar: ',');You can load data from:
- CSV or TSV files
- In-memory collections
- SQL databases
- JSON streams
🧪 2. Transform
Before training, data usually needs to be cleaned or reshaped. In ML.NET, this is done using transforms — chained together into a pipeline.
Common transforms include:
- Normalization (e.g., scale values between 0–1)
- Featurization (e.g., converting text into numerical vectors)
- Concatenation (e.g., combining multiple columns into a feature set)
pipeline = mlContext.Transforms.Concatenate("Features", "Age", "Income");The output is a transformed IDataView, ready for training.
🧠 3. Train
Now comes the learning step. You feed the transformed data into a trainer — which is ML.NET’s version of a machine learning algorithm.
.Append(mlContext.BinaryClassification.Trainers.SdcaLogisticRegression());This creates a model that captures patterns in your data — mapping inputs (features) to outputs (labels).
📊 4. Evaluate
Once trained, you want to know how good your model is. ML.NET offers a set of metrics based on the type of problem.
For binary classification:
Accuracy: Percentage of correct predictionsAUC: Area under the ROC curveF1 Score: Balance between precision and recall
For regression:
R² (R-squared): How well the model fits the dataRMSE: Root Mean Squared Error (lower is better)MAE: Mean Absolute Error
Example:
var metrics = mlContext.BinaryClassification.Evaluate(predictions);
Console.WriteLine($"Accuracy: {metrics.Accuracy:P2}");🔮 5. Predict
With a trained and evaluated model, you’re ready to make real predictions.
You can:
- Use a
PredictionEngine(for single predictions) - Or batch predict on a full dataset
var result = predictionEngine.Predict(new CustomerData { Age = 28, Income = 45000 });✅ Full Code: Hello AI World with ML.NET (Step-by-Step)
Let’s now walk through the complete working code example that ties all the workflow pieces together.
This is a minimal example of using ML.NET for binary classification — predicting whether a customer will purchase a product based on their age and income.
Create a new <code>.NET Console App project, and paste the following code into your Program.cs file:
using System;
using System.Collections.Generic;
using Microsoft.ML;
using Microsoft.ML.Data;
namespace MLNetHelloWorld
{
// Step 1: Define input data schema
public class CustomerData
{
public float Age;
public float Income;
public bool Purchased;
};
// Step 2: Define prediction result class
public class PurchasePrediction
{
[ColumnName("PredictedLabel")]
public bool PredictedLabel;
};
class Program
{
static void Main(string[] args)
{
// Create ML context
var mlContext = new MLContext();
// === LOAD ===
var data = new List<CustomerData>
{
new CustomerData { Age = 25, Income = 30000, Purchased = false },
new CustomerData { Age = 45, Income = 70000, Purchased = true },
new CustomerData { Age = 35, Income = 50000, Purchased = true },
new CustomerData { Age = 22, Income = 20000, Purchased = false },
};
IDataView trainingData = mlContext.Data.LoadFromEnumerable(data);
// === TRANSFORM + TRAIN ===
var pipeline = mlContext.Transforms.Concatenate("Features", "Age", "Income")
.Append(mlContext.BinaryClassification.Trainers.SdcaLogisticRegression());
var model = pipeline.Fit(trainingData);
// === EVALUATE ===
var predictions = model.Transform(trainingData);
var metrics = mlContext.BinaryClassification.Evaluate(predictions);
Console.WriteLine($"Accuracy: {metrics.Accuracy:P2}");
Console.WriteLine($"F1 Score: {metrics.F1Score:P2}");
// === PREDICT ===
var predictionEngine = mlContext.Model.CreatePredictionEngine<CustomerData, PurchasePrediction>(model);
var newCustomer = new CustomerData { Age = 30, Income = 40000 };
var prediction = predictionEngine.Predict(newCustomer);
Console.WriteLine($"Prediction: Will purchase? {prediction.PredictedLabel}");
}
}
}🧠 What This Code Demonstrates:
- Load: We load in-memory customer data into an
IDataView. - Transform: Combine features (
Age,Income) into a single input vector. - Train: Use logistic regression to learn from the labeled data.
- Evaluate: Assess how well the model performs using built-in metrics.
- Predict: Test the model with a new input and output a prediction.
💡 Real-World Tip:
You can replace the in-memory list with a CSV later using:
mlContext.Data.LoadFromTextFile<CustomerData>("data.csv", hasHeader: true, separatorChar: ',');This makes it easy to scale this example up to real datasets.
✨ Summary
The ML.NET workflow is designed to be intuitive for .NET developers. Everything is based on strong types, fluent syntax, and predictable steps. Once you get the rhythm — Load → Transform → Train → Evaluate → Predict — the process starts to feel natural.
In the next section, we’ll apply this workflow to a real-world problem: predicting house prices using a regression model.
Ready to build something practical? Let’s go.
🏠 Use Case #1: Predicting House Prices (Regression)
Let’s move from "Hello AI World" to solving a common, real-world machine learning problem: predicting house prices.
This is a classic example of a regression task, where the goal is to predict a continuous numeric value — like the price of a house — based on a set of input features such as size, number of rooms, or location.
📘 What Is a Regression Problem?
In machine learning, a regression problem is one where the output (the thing you’re trying to predict) is a real number. Think prices, temperatures, distances, or quantities — anything on a continuous scale.
A few examples of regression use cases:
- Predicting house prices
- Estimating delivery times
- Forecasting sales or revenue
- Predicting fuel efficiency based on car specs
In this tutorial, we’ll use ML.NET to predict housing prices based on square footage — a simple but powerful entry point into regression modeling.
📂 Sample Dataset
We'll keep it minimal here to stay focused on the workflow. In the next project, we’ll explore larger datasets — but for now, here's the dataset we’ll use in-memory:
| Size (sqft) | Price ($) |
|---|---|
| 1000 | 150000 |
| 1500 | 200000 |
| 1800 | 250000 |
| 2400 | 300000 |
| 3000 | 400000 |
💻 Full Code: House Price Prediction with ML.NET
using System;
using System.Collections.Generic;
using Microsoft.ML;
using Microsoft.ML.Data;
namespace MLNetRegressionDemo
{
// Input data class
public class HouseData
{
public float Size { get; set; }
public float Price { get; set; }
}
// Prediction result class
public class PricePrediction
{
[ColumnName("Score")]
public float PredictedPrice { get; set; }
}
class Program
{
static void Main(string[] args)
{
// Step 1: Create ML context
var mlContext = new MLContext();
// Step 2: Load sample data
var data = new List<HouseData>
{
new HouseData { Size = 1000f, Price = 150000f },
new HouseData { Size = 1500f, Price = 200000f },
new HouseData { Size = 1800f, Price = 250000f },
new HouseData { Size = 2400f, Price = 300000f },
new HouseData { Size = 3000f, Price = 400000f },
};
IDataView trainingData = mlContext.Data.LoadFromEnumerable(data);
// Step 3: Build the training pipeline
var pipeline = mlContext.Transforms.Concatenate("Features", "Size")
.Append(mlContext.Regression.Trainers.Sdca(labelColumnName: "Price", maximumNumberOfIterations: 100));
// Step 4: Train the model
var model = pipeline.Fit(trainingData);
// Step 5: Evaluate model performance
var predictions = model.Transform(trainingData);
var metrics = mlContext.Regression.Evaluate(predictions, labelColumnName: "Price");
Console.WriteLine($"R^2: {metrics.RSquared:0.##}");
Console.WriteLine($"RMSE: {metrics.RootMeanSquaredError:#.##}");
// Step 6: Predict a new value
var predictionEngine = mlContext.Model.CreatePredictionEngine<HouseData, PricePrediction>(model);
var newHouse = new HouseData { Size = 2100f };
var prediction = predictionEngine.Predict(newHouse);
Console.WriteLine($"Predicted price for a 2100 sq ft house: ${prediction.PredictedPrice:#.##}");
}
}
}🧠 Step-by-Step Breakdown
📥 Load
We’re loading a small in-memory dataset, but you can easily replace this with a CSV later using LoadFromTextFile().
🔧 Transform
We're using just one feature: Size, but still wrap it with Concatenate to match the pipeline's requirement for a feature vector.
🎯 Train
We use SDCA regression, a fast and reliable linear regression trainer in ML.NET.
📊 Evaluate
We evaluate the model using:
R² (R-squared): How well the model fits the data (1.0 = perfect fit)RMSE (Root Mean Squared Error): Lower = better predictive performance
🔮 Predict
Finally, we predict the price of a house that’s not in the original dataset — in this case, 2100 sq ft.
🔄 ML.NET Pipeline Flow (Diagram)
Here’s a simplified version of how the process flows in ML.NET:
┌──────────────┐
│ Raw Data │
└──────┬───────┘
│
▼
┌────────────────┐
│ Transformation │ → e.g. Concatenate("Features")
└──────┬─────────┘
│
▼
┌────────────┐
│ Trainer │ → e.g. Sdca Regression
└────┬───────┘
│
▼
┌────────────┐
│ Model │
└────┬───────┘
│
▼
┌────────────┐
│ Prediction │ → Single or batch prediction
└────────────┘This is the foundational pattern you’ll follow for all ML.NET applications — whether it’s regression, classification, or even recommendation systems.
✅ Takeaway
With just a few lines of C#, you've now built a working regression model that learns from real-world data and makes predictions. More importantly, you now understand the structure of how machine learning flows through ML.NET’s architecture.
In the next use case, we’ll shift gears from numbers to natural language — and build a sentiment analysis engine that can understand the tone of written text.
💬 Use Case #2: Sentiment Analysis (Binary Classification)
Understanding human language is one of the most fascinating applications of AI — and it’s closer to reach than most developers think. In this example, you’ll build a model that can read a review and decide: Is it positive or negative?
This type of problem is called binary classification — the model must choose between two possible outcomes. In our case:
- Positive sentiment =
true - Negative sentiment =
false
🤔 What Is Sentiment Analysis?
Sentiment analysis is a common machine learning task where you analyze a piece of text (like a product review, tweet, or comment) and predict the emotional tone behind it. It’s widely used in:
- Customer feedback tools
- Social media monitoring
- Chatbots
- Market research
For this tutorial, we'll use a small set of hand-written mock reviews, but the same principles apply to full-scale production apps — even those trained on thousands of real Yelp or IMDB reviews.
📦 Sample Dataset
Let’s use a simple list of labeled customer reviews:
| Review | IsPositive |
|---|---|
| I love this product | true |
| Worst experience ever | false |
| It was okay, not great | false |
| Absolutely fantastic! | true |
| I would not recommend this | false |
| Totally worth it | true |
💻 Full Code: Sentiment Analysis with ML.NET
using System;
using System.Collections.Generic;
using Microsoft.ML;
using Microsoft.ML.Data;
namespace MLNetSentimentDemo
{
// Step 1: Define input data class
public class ReviewData
{
public string ReviewText { get; set; }
public bool IsPositive { get; set; }
}
// Step 2: Define prediction result class
public class SentimentPrediction
{
[ColumnName("PredictedLabel")]
public bool Prediction { get; set; }
public float Probability { get; set; }
public float Score { get; set; }
}
class Program
{
static void Main(string[] args)
{
// Create ML.NET context
var mlContext = new MLContext();
// === LOAD ===
var data = new List<ReviewData>
{
new ReviewData { ReviewText = "I love this product", IsPositive = true },
new ReviewData { ReviewText = "Worst experience ever", IsPositive = false },
new ReviewData { ReviewText = "It was okay, not great", IsPositive = false },
new ReviewData { ReviewText = "Absolutely fantastic!", IsPositive = true },
new ReviewData { ReviewText = "I would not recommend this", IsPositive = false },
new ReviewData { ReviewText = "Totally worth it", IsPositive = true },
};
IDataView trainingData = mlContext.Data.LoadFromEnumerable(data);
// === TRANSFORM ===
var pipeline = mlContext.Transforms.Text.FeaturizeText("Features", nameof(ReviewData.ReviewText))
.Append(mlContext.BinaryClassification.Trainers.SdcaLogisticRegression(
labelColumnName: nameof(ReviewData.IsPositive), maximumNumberOfIterations: 100));
// === TRAIN ===
var model = pipeline.Fit(trainingData);
// === EVALUATE ===
var predictions = model.Transform(trainingData);
var metrics = mlContext.BinaryClassification.Evaluate(predictions, labelColumnName: nameof(ReviewData.IsPositive));
Console.WriteLine($"Accuracy: {metrics.Accuracy:P2}");
Console.WriteLine($"AUC: {metrics.AreaUnderRocCurve:P2}");
Console.WriteLine($"F1 Score: {metrics.F1Score:P2}");
Console.WriteLine();
// === PREDICT ===
var predictionEngine = mlContext.Model.CreatePredictionEngine<ReviewData, SentimentPrediction>(model);
var newReview = new ReviewData { ReviewText = "I’m really disappointed in the quality" };
var result = predictionEngine.Predict(newReview);
Console.WriteLine($"Review: {newReview.ReviewText}");
Console.WriteLine($"Prediction: {(result.Prediction ? "Positive" : "Negative")} (Probability: {result.Probability:P2})");
}
}
}🧠 Explanation of Key Steps
📥 Load
We use a small in-memory list for simplicity, but you can load from a CSV like this:
mlContext.Data.LoadFromTextFile<ReviewData>("reviews.csv", hasHeader: true, separatorChar: ',');🧹 Transform: FeaturizeText
This is where the magic of NLP starts. ML.NET’s FeaturizeText handles:
- Tokenization (splitting text into words)
- Stop word removal
- Word hashing
- TF-IDF vectorization
All automatically, with just one line:
mlContext.Transforms.Text.FeaturizeText("Features", nameof(ReviewData.ReviewText))No need to write custom tokenizers or worry about vocabulary — ML.NET does it all behind the scenes.
🎯 Train
We use SDCA logistic regression, a standard, efficient binary classification algorithm.
📊 Evaluate
ML.NET gives us multiple metrics to measure classification quality:
- Accuracy — How many predictions were correct.
- AUC — How well the model distinguishes between the two classes.
- F1 Score — A balance between precision and recall.
These help you understand if your model is too "guessy" or if it really understands the data.
🔮 Predict
We run a new review through the model and output:
Prediction(true/false)Probability(confidence level)Score(raw model score)
✅ Output Example
Accuracy: 100.00% AUC: 100.00% F1 Score: 100.00%
Review: I’m really disappointed in the quality Prediction: Negative (Probability: 8.42%)
(Of course, with larger real-world data, accuracy won’t be perfect — but this shows the mechanics.)
📝 Summary
With just a few lines of C#, you’ve created a text classification engine that can analyze the tone of a review — something that's used by major platforms across the web.
You now know how to:
- Preprocess text using
FeaturizeText - Train a binary classifier
- Evaluate performance using ML.NET's built-in metrics
- Predict sentiment on new inputs
Next, we’ll cover how to save your model and integrate it into real applications — like an API, desktop app, or background worker.
Ready to deploy your intelligence? Let’s go.
💾 Saving and Using Your Model
At this point, you've trained your first few machine learning models using ML.NET — whether it was to predict house prices or understand customer sentiment.
But in the real world, you won’t retrain your model every time you run your app. Instead, you’ll train it once, save it to disk, and then load it on demand — ready to make predictions anytime.
Let’s walk through exactly how to do that.
📥 Saving a Trained Model to File
Once your model is trained, saving it is just one line of code. ML.NET serializes the entire model pipeline — including any preprocessing steps like FeaturizeText, feature concatenation, and the trained algorithm itself — into a .zip file.
Here’s how to save it:
mlContext.Model.Save(model, trainingData.Schema, "sentiment-model.zip");Let’s add that to the end of our sentiment analysis code:
// Save the trained model to a file
string modelPath = "sentiment-model.zip";
mlContext.Model.Save(model, trainingData.Schema, modelPath);
Console.WriteLine($"Model saved to {modelPath}");That’s it. You now have a portable .zip file that contains the full pipeline — data transformations and model included.
📤 Loading a Model for Future Use
When you need to make predictions (say, inside an ASP.NET API or desktop app), you just load the saved model and use it as if it had just been trained.
Here’s how to load it back in:
ITransformer loadedModel;
DataViewSchema inputSchema;
using var fileStream = new FileStream("sentiment-model.zip", FileMode.Open, FileAccess.Read, FileShare.Read);
loadedModel = mlContext.Model.Load(fileStream, out inputSchema);
You can now use this loaded model to create a `PredictionEngine` like before:
var predictionEngine = mlContext.Model.CreatePredictionEngine<ReviewData, SentimentPrediction>(loadedModel);
var newReview = new ReviewData { ReviewText = "This is the best experience I've had." };
var result = predictionEngine.Predict(newReview);
Console.WriteLine($"Prediction: {(result.Prediction ? "Positive" : "Negative")} (Confidence: {result.Probability:P2})");🛠️ Putting It All Together
Let’s put the save/load logic into a clean, complete example:
// After training the model
string modelPath = "sentiment-model.zip";
mlContext.Model.Save(model, trainingData.Schema, modelPath);
// Later or in a different app
ITransformer loadedModel;
DataViewSchema schema;
using var stream = new FileStream(modelPath, FileMode.Open, FileAccess.Read, FileShare.Read);
loadedModel = mlContext.Model.Load(stream, out schema);
// Predict
var predictionEngine = mlContext.Model.CreatePredictionEngine<ReviewData, SentimentPrediction>(loadedModel);
var review = new ReviewData { ReviewText = "Terrible service and rude staff." };
var prediction = predictionEngine.Predict(review);
Console.WriteLine($"Prediction: {(prediction.Prediction ? "Positive" : "Negative")} - Confidence: {prediction.Probability:P2}");🚀 Integrating Your Model into an App or API
Once your model is saved, you can embed it anywhere in your application architecture — here are a few examples:
✅ Console App (like we're doing now)
- Load the model on startup
- Use it to make predictions as needed
- Great for CLI tools or background jobs
✅ ASP.NET Web API
- Load the model once in
Startup.csor via dependency injection - Expose an endpoint like
POST /predict - Accept text input, return prediction result
- Ideal for real-time apps (chatbots, dashboards)
✅ Desktop App (WPF, MAUI)
- Load the model during initialization
- Connect prediction output to UI elements (e.g., display sentiment with color-coded labels)
📝 Real-World Example: Minimal Web API Controller
Here’s what a basic ASP.NET Web API controller might look like:
[ApiController]
[Route("[controller]")]
public class SentimentController : ControllerBase
{
private readonly PredictionEngine<ReviewData, SentimentPrediction> _engine;
public SentimentController(MLContext mlContext)
{
var model = mlContext.Model.Load("sentiment-model.zip", out _);
_engine = mlContext.Model.CreatePredictionEngine<ReviewData, SentimentPrediction>(model);
}
[HttpPost]
public IActionResult Predict([FromBody] ReviewData input)
{
var result = _engine.Predict(input);
return Ok(new { result.Prediction, result.Probability });
}
}You now have a real machine learning model served via HTTP — ready to integrate into mobile apps, frontend UIs, or other services.
✅ Summary
You’ve now learned how to:
- Save your trained ML.NET model as a
.zipfile - Load that model for predictions in future sessions
- Use the model inside desktop apps, background services, or APIs
This is where machine learning moves from demo to deployment. Your app is no longer hardcoded — it learns from data, stores that knowledge, and reuses it intelligently.
Next, we’ll explore an alternative way to build models — without code — using ML.NET Model Builder inside Visual Studio.
🧩 Bonus: Using Model Builder (No-Code Training for AI in .NET)
Not everyone wants to jump straight into code — and that’s okay. Sometimes, especially when you're still wrapping your head around machine learning, it helps to start visually.
That’s exactly what ML.NET Model Builder offers.
Model Builder is an extension inside Visual Studio that lets you build and train machine learning models through a friendly, wizard-like interface — no code required. You provide the data, choose what you want to predict, and Model Builder takes care of the rest. Then, when you're ready, it generates the C# code behind the scenes so you can study it, extend it, or deploy it.
Let’s walk through the process step by step.
🖥️ Step 1: Open or Create a New Project
You can start with an empty Console App or any .NET Core / .NET 6/7 project. Model Builder works with most standard Visual Studio project types.
Open your project in Visual Studio 2022 or later.
🧱 Step 2: Add Machine Learning to Your Project
Right-click on the project in Solution Explorer, then select:
Add → Machine Learning
If you haven’t installed Model Builder yet, Visual Studio will guide you through installing the extension first. Once installed, you’ll see the Model Builder wizard open in a new tab.
📈 Step 3: Choose a Scenario
Model Builder supports several out-of-the-box scenarios:
- Sentiment Analysis
Predict positive/negative from text - Price Prediction
Regression use case for continuous values - Image Classification
Classify objects from image files - Recommendation
Suggest products or items - Custom (AutoML)
For advanced workflows with CSV datasets
For this walkthrough, let’s choose “Sentiment Analysis”.
Click on it, then hit Next.
📁 Step 4: Load Your Data
You’ll now be prompted to import your dataset. Model Builder works best with CSV files.
Example CSV:
ReviewText,IsPositive I love this product,true Worst experience ever,false Totally worth it,true I would not recommend this,false
- Select your CSV file
- Confirm the column used as the label (e.g.,
IsPositive) - Select input features (in this case,
ReviewText)
Click Next to continue.
⚙️ Step 5: Train the Model
This is where Model Builder truly shines.
It will now:
- Try different algorithms automatically
- Run tests using part of your data
- Select the best-performing model
- Show live progress and accuracy
You can set a time limit for training (e.g., 60 seconds is enough for small data). After training, you’ll get a dashboard with:
- Accuracy metrics
- Confusion matrix
- Best algorithm used
Click Evaluate to view performance in detail, then Next.
📤 Step 6: Use the Trained Model
Model Builder will generate:
- A
MLModel.zipfile (your trained model) - A
ConsumeModelproject to run predictions - A
ModelInputandModelOutputclass - All the pipeline setup code, fully written for you
To test it, go to the ConsumeModel project and run:
var input = new ModelInput { ReviewText = "Amazing support and easy to use." };
var result = ConsumeModel.Predict(input);
Console.WriteLine($"Prediction: {(result.Prediction ? "Positive" : "Negative")} - Confidence: {result.Probability:P2}");That’s it. You’ve trained and deployed a real machine learning model — without writing a single line of training code.
📂 Exporting and Learning from Generated Code
Here’s the beautiful part: the code Model Builder creates is fully reusable and readable.
Explore the following files:
MLModel.zip: The trained modelMLModel.cs: The pipeline (features, trainer, etc.)ConsumeModel.cs: Prediction logic
This is a goldmine for beginners because you can:
- See how the pipeline is structured
- Learn by tweaking parameters
- Move the generated code into a production app
It’s like training wheels — but the kind that teach you to ride faster.
🧠 Real-World Example: Hooking It into an App
Since Model Builder outputs a ready-to-go .zip model and classes, you can now:
- Drop them into a Web API controller
- Connect them to a desktop UI
- Use them in a background job
- Or refactor the pipeline into a larger system
It’s your model — and you’re in full control of where and how to use it.
✅ Summary
Model Builder gives you:
- A no-code way to train real AI models in .NET
- AutoML capabilities (auto-select best algorithm)
- Confidence metrics and ready-to-use predictions
- Fully generated code you can study and deploy
For many developers — especially those just getting started — this tool removes the barrier of “I don’t know where to start.”
And once you’re comfortable with how things work, you can start writing pipelines from scratch (as we’ve done in earlier sections), giving you both power and understanding.
In the next and final section, we’ll go over a few common challenges, smart tips for troubleshooting, and how to grow your AI skills further from here.
🛠️ Challenges, Gotchas, and Tips
Let’s be real — working with AI, even with an accessible tool like ML.NET, won’t always go smoothly. Data might behave strangely. Accuracy might disappoint. And the code that compiled yesterday might mysteriously refuse to run today.
This section is your survival kit — a list of real-world tips, common mistakes, and practical insights to help you get unstuck and stay productive.
❌ Problem 1: Model Accuracy Is Low
Symptom: You train your model, and it barely performs better than random guessing.
Causes & Fixes:
- Not enough data
→ Machine learning thrives on patterns. If you’re only feeding it 5 rows, there’s not much to learn. Start with at least 100–500 samples for basic models, more for complex ones. - Poorly labeled data
→ Check for typos, mislabeled rows, or inconsistencies. A few bad rows can throw off the whole model. - Irrelevant or weak features
→ The features you give the model must actually correlate with the thing you want to predict. In our house price example,ColorOfMailboxprobably doesn’t help — butSquareFootagedoes. - Normalization missing
→ Especially for regression, normalize numeric features so large numbers don’t dominate small ones.
Bonus Tip:
Use mlContext.Transforms.NormalizeMinMax() in your pipeline for regression problems.
❌ Problem 2: PredictionEngine Throws an Error
Symptom: You're trying to predict, but the code crashes with a cryptic error.
Most Common Cause:
Your input class (ReviewData, HouseData, etc.) doesn’t match the schema the model expects. Even a renamed property or missing column can break the pipeline.
✅ Fix: Double-check that your input class exactly matches what the model was trained with.
You can inspect the model’s schema like this:
var model = mlContext.Model.Load("model.zip", out var schema);
Console.WriteLine(schema);This prints all expected columns and types.
❌ Problem 3: Training Takes Too Long
For small datasets, training should be fast. If it drags:
- You're using a trainer with a large iteration count (reduce it)
- The dataset is too big for in-memory training (consider using
LoadFromTextFilewithShuffle=false) - You're running AutoML (Model Builder) with too high a time budget
✅ Fix: Keep your iterations low during development. Bump it up when going to production.
⚡ Pro Tips for Working with ML.NET
🔁 Use IDataView.Preview() for Quick Data Inspection
Want to see what your transformed data looks like?
var preview = trainingData.Preview();
foreach (var row in preview.RowView)
{
foreach (var col in row.Values)
{
Console.WriteLine($"{col.Key}: {col.Value}");
}
}This is incredibly helpful for debugging feature vectors.
🧪 Experiment with Different Trainers
ML.NET supports multiple trainers for each task. You can swap them in to compare results:
For binary classification:
mlContext.BinaryClassification.Trainers.FastTree();
mlContext.BinaryClassification.Trainers.AveragedPerceptron();For regression:
mlContext.Regression.Trainers.FastTree();
mlContext.Regression.Trainers.LbfgsPoissonRegression();Don’t be afraid to try several — performance can vary wildly based on data.
🔍 Use Model Explainability for Trust
Once your model is making predictions, you might want to know why it made a decision. While not built-in yet as full explainability tools, you can:
- Use
FeatureContributionCalculatingEstimatorfor basic feature importance - Export models to ONNX and use third-party explainability libraries
✅ Common Learning Paths After This Guide
If you’ve made it this far, you’ve already crossed a major milestone.
Here’s where to go next:
- Build an ASP.NET Web API
- Load your saved
.zipmodel - Expose predictions via endpoints
- Load your saved
- Work with Larger Datasets
- Load CSVs, SQL tables, or stream data from APIs
- Try
LoadFromTextFile<T>()
- Try Multi-class Classification
- Like classifying emails into topics
- Explore ONNX Integration
- Train models in Python (e.g., image classification with PyTorch)
- Load in .NET using
Microsoft.ML.OnnxRuntime
- Integrate ML.NET into Blazor or MAUI apps
- Predict live from user input on desktop or web
🎯 Final Thoughts
Learning AI used to feel like entering a new world — filled with math-heavy jargon, Python-only libraries, and research-style workflows. ML.NET changes that.
Now, you can:
- Train real AI models using C# and .NET
- Save and deploy those models into apps and APIs
- Understand how the pipeline works under the hood
- Use tools like Model Builder to prototype with ease
- Grow into more complex tasks with full confidence
Whether you’re building something for your resume, your company, or your own curiosity, you now have the tools to create smarter software.
You've just scratched the surface — but you’ve taken a big, meaningful step. So keep building, keep testing, and keep learning.
👏 Well done.
A: ML.NET is Microsoft’s open-source machine learning framework that allows .NET developers to build, train, and deploy custom machine learning models in C# or F#. It integrates seamlessly with .NET applications such as desktop apps, web APIs, and background services.
A: Yes! ML.NET is designed for developers, not data scientists. You can build powerful machine learning models using C# and .NET without writing any Python code or understanding complex math.
A: ML.NET supports regression (e.g., price prediction), classification (e.g., spam detection, sentiment analysis), clustering, recommendation systems, anomaly detection, and time-series forecasting.
A: Start by installing Visual Studio with the “.NET Desktop Development” workload, then add the Microsoft.ML NuGet package to your project. You can also install Model Builder for a no-code training experience.
A: Regression predicts a continuous value (like house prices), while classification predicts a category or label (like positive or negative sentiment). ML.NET provides different trainers for each type.
A: After training, you can save your model to a .zip file using mlContext.Model.Save(...). Later, you can load it with mlContext.Model.Load(...) and use it in any application.
A: FeaturizeText is a transformation in ML.NET that converts raw text into numeric feature vectors. It automatically tokenizes, removes stop words, and prepares the data for training a model.
A: Absolutely. ML.NET models can be loaded into ASP.NET Core Web APIs, WPF desktop applications, or even background worker services. The trained model becomes a portable .zip file ready for consumption.
A: Model Builder is a Visual Studio extension that allows you to train machine learning models through a simple UI, without writing code. It’s perfect for beginners and prototyping ML projects quickly.
A: Yes, ML.NET is production-ready and used by Microsoft internally. It supports model versioning, evaluation metrics, batch and real-time predictions, and integrates with ONNX for deep learning scenarios.
A: ML.NET regression is a machine learning task that predicts numeric values — such as prices, temperatures, or measurements. Use regression when your output is a continuous number. For example, predicting house prices based on square footage is a regression problem.
A: ML.NET offers several regression trainers. Common choices include Sdca, FastTree, and LbfgsPoissonRegression. For most beginners, Sdca (Stochastic Dual Coordinate Ascent) is a good starting point due to its speed and simplicity.
A: Yes. ML.NET Model Builder supports regression as one of its built-in scenarios. You can load a CSV file, select the numeric value you want to predict, and let Model Builder choose the best regression algorithm automatically.
A: For ML.NET regression, your dataset should include at least one numeric label column (the value to predict) and one or more features (input variables). Features can be numeric or categorical and must be preprocessed using transforms like Concatenate() or OneHotEncoding().
A: ML.NET Model Builder is a Visual Studio extension that allows you to train machine learning models without writing code. You choose a scenario (like regression or classification), load your data, and it generates a trained model and C# code that you can use in your apps.
A: Yes. Once training is complete, Model Builder creates a ModelInput, ModelOutput, MLModel.zip, and a prediction class in a separate project. You can view, modify, or migrate the generated code into other applications for deployment.
A: The accuracy of a regression model depends on your data quality, feature relevance, and training duration. Model Builder uses AutoML to test multiple algorithms and returns the best performer, but tuning your dataset manually can often improve results further.
A: Absolutely. Many developers use Model Builder to prototype and even launch production models. For more control, you can export the generated code and refine the pipeline yourself — blending ease of use with professional-grade flexibility.
Related posts

The Future of C#: Why You Should Be Excited About What's to Come
C has been a popular choice for developers for years, and it continues to evolve and adapt to new trends in software development. In this blog post, we'll take a look…

An Introduction to Functional Programming with C#: A Dive into the Paradigm Shift
Dive deep into the world of Functional Programming (FP) within the C ecosystem. From its historical origins to real-world applications, explore how C elegantly marries…

Introduction to Data Structures and Algorithms in C#
Discover the foundations of software development through a comprehensive exploration of data structures and algorithms in C . From understanding their core concepts to…