Skip to main content

What Is ML.NET? Machine Learning in C# for .NET Developers

Verified Apr 2026 Beginner Original .NET 10 Microsoft.ML 4.0.0
By Rajesh Mishra · Mar 12, 2026 · 11 min read
In 30 Seconds

ML.NET is Microsoft's open-source machine learning framework for .NET. It handles predictive ML tasks: classification, regression, forecasting, clustering, anomaly detection. It runs on-device without cloud dependencies. ML.NET complements generative AI (Azure OpenAI/Semantic Kernel) — use ML.NET for structured predictions, generative AI for text/reasoning.

Two Flavors of AI in .NET

The .NET ecosystem has two distinct AI toolkits, and they solve fundamentally different problems:

Generative AI (Azure OpenAI, Semantic Kernel, Agent Framework)

  • Generate text, code, summaries
  • Chat and conversational AI
  • Reasoning and planning
  • Natural language understanding
  • Cost: per API call to cloud service

Predictive ML (ML.NET)

  • Classify data (spam/not-spam, positive/negative)
  • Predict numbers (price estimation, demand forecasting)
  • Detect anomalies (fraud detection, system monitoring)
  • Cluster similar items (customer segmentation)
  • Cost: zero after training — runs on-device

ML.NET is the predictive ML side. It’s Microsoft’s open-source framework for training and deploying traditional machine learning models entirely in C#.

What ML.NET Does

ML.NET provides a pipeline-based system for building ML models:

Data → Load → Transform → Train → Evaluate → Deploy → Predict

Each step is a C# operation. No Python, no Jupyter notebooks, no separate training infrastructure. You build, train, and deploy from the same codebase as your application.

The ML.NET Pipeline Model

using Microsoft.ML;
using Microsoft.ML.Data;

// 1. Create the ML context
var mlContext = new MLContext(seed: 42);

// 2. Load data
var data = mlContext.Data.LoadFromTextFile<SentimentData>(
    "reviews.csv", hasHeader: true, separatorChar: ',');

// 3. Build the pipeline: transform → train
var pipeline = mlContext.Transforms.Text
    .FeaturizeText("Features", nameof(SentimentData.ReviewText))
    .Append(mlContext.BinaryClassification.Trainers
        .SdcaLogisticRegression(
            labelColumnName: nameof(SentimentData.IsPositive),
            featureColumnName: "Features"));

// 4. Train the model
var model = pipeline.Fit(data);

// 5. Evaluate
var predictions = model.Transform(testData);
var metrics = mlContext.BinaryClassification.Evaluate(predictions,
    labelColumnName: nameof(SentimentData.IsPositive));

Console.WriteLine($"Accuracy: {metrics.Accuracy:P2}");
Console.WriteLine($"F1 Score: {metrics.F1Score:P2}");

The data classes:

public class SentimentData
{
    [LoadColumn(0)]
    public string ReviewText { get; set; } = "";

    [LoadColumn(1)]
    public bool IsPositive { get; set; }
}

public class SentimentPrediction
{
    [ColumnName("PredictedLabel")]
    public bool IsPositive { get; set; }

    public float Probability { get; set; }
    public float Score { get; set; }
}

What You Can Build With ML.NET

Binary Classification

Predict one of two outcomes: spam/not-spam, fraudulent/legitimate, positive/negative.

Example: Email spam filter, loan approval predictor, sentiment classifier.

Multi-Class Classification

Predict one of many categories: product category, support ticket routing, language detection.

Example: Customer support ticket auto-routing to the right team.

Regression

Predict a numeric value: house price, delivery time, demand quantity.

Example: Estimated delivery time based on distance, weight, and shipping method.

Time Series Forecasting

Predict future values from historical data: sales forecast, resource demand, traffic prediction.

Example: Predict next month’s server capacity needs based on last 12 months.

Anomaly Detection

Detect unusual patterns: fraud transactions, system failures, data quality issues.

Example: Flag credit card transactions that deviate from a customer’s normal spending pattern.

Clustering

Group similar items without predefined labels: customer segmentation, document grouping.

Example: Segment customers into behavioral groups for targeted marketing.

ML.NET vs Generative AI: When to Use Which

This is the practical question. Here’s the decision framework:

ScenarioUse ML.NETUse Generative AI
Classify 100K records✅ Fast, cheap❌ Slow, expensive
Analyze free-text sentimentPossible but basic✅ Nuanced understanding
Forecast quarterly sales✅ Purpose-built❌ Not designed for this
Generate product descriptions❌ Not designed for this✅ Purpose-built
Detect fraud in transactions✅ Real-time, on-devicePossible but costly per-call
Answer customer questions✅ Natural language
Predict churn probability✅ Structured dataPossible but overkill

The general rule: structured data + prediction → ML.NET. Unstructured text + generation → Generative AI.

Many production systems use both:

  • ML.NET classifies incoming support tickets by category and priority
  • Semantic Kernel generates the initial response based on the classification
  • ML.NET predicts resolution time
  • The customer gets a categorized, AI-drafted response with an estimated resolution time

Getting Started

Install the SDK:

dotnet add package Microsoft.ML

For specific tasks:

dotnet add package Microsoft.ML.TimeSeries      # Forecasting
dotnet add package Microsoft.ML.Vision           # Image classification
dotnet add package Microsoft.ML.Recommender      # Recommendations

Here’s the shortest possible ML.NET program — binary classification in about 30 lines:

using Microsoft.ML;
using Microsoft.ML.Data;

var mlContext = new MLContext();

// Sample training data
var trainingData = new[]
{
    new { Text = "I love this product", IsPositive = true },
    new { Text = "Amazing quality", IsPositive = true },
    new { Text = "Terrible experience", IsPositive = false },
    new { Text = "Would not recommend", IsPositive = false },
    new { Text = "Works great", IsPositive = true },
    new { Text = "Completely broken", IsPositive = false },
};

var data = mlContext.Data.LoadFromEnumerable(trainingData);

var pipeline = mlContext.Transforms.Text
    .FeaturizeText("Features", "Text")
    .Append(mlContext.BinaryClassification.Trainers
        .SdcaLogisticRegression(labelColumnName: "IsPositive"));

var model = pipeline.Fit(data);

// Make a prediction
var predictor = mlContext.Model.CreatePredictionEngine<
    InputData, PredictionResult>(model);

var prediction = predictor.Predict(
    new InputData { Text = "This is excellent" });

Console.WriteLine($"Positive: {prediction.PredictedLabel}, Confidence: {prediction.Probability:P1}");

public class InputData
{
    public string Text { get; set; } = "";
    public bool IsPositive { get; set; }
}

public class PredictionResult
{
    [ColumnName("PredictedLabel")]
    public bool PredictedLabel { get; set; }
    public float Probability { get; set; }
}

Deploying ML.NET Models

Trained models are saved as .zip files and loaded at runtime:

// Save
mlContext.Model.Save(model, data.Schema, "model.zip");

// Load (in your production application)
var loadedModel = mlContext.Model.Load("model.zip", out var schema);

For ASP.NET Core, use the prediction engine pool for thread-safe concurrent predictions:

dotnet add package Microsoft.Extensions.ML
builder.Services.AddPredictionEnginePool<InputData, PredictionResult>()
    .FromFile(modelName: "SentimentModel", filePath: "model.zip");

Inject and use in controllers or services:

public class PredictionService
{
    private readonly PredictionEnginePool<InputData, PredictionResult> _pool;

    public PredictionService(PredictionEnginePool<InputData, PredictionResult> pool)
        => _pool = pool;

    public PredictionResult Predict(string text)
        => _pool.Predict("SentimentModel", new InputData { Text = text });
}

ONNX Integration

ML.NET can run ONNX models — trained in Python (PyTorch, TensorFlow, HuggingFace) and exported to ONNX format. This bridges the Python training ecosystem with .NET production deployment:

dotnet add package Microsoft.ML.OnnxRuntime
dotnet add package Microsoft.ML.OnnxTransformer

See ONNX Models in .NET: Run AI Without Azure for the full walkthrough.

Next Steps

⚠ Production Considerations

  • PredictionEngine is not thread-safe. In ASP.NET Core, use PredictionEnginePool from Microsoft.Extensions.ML for concurrent predictions. Creating a new PredictionEngine per request is expensive.
  • Don't use ML.NET when an LLM is the right tool. Sentiment analysis of free-text customer reviews? LLM is better. Binary classification on 50K structured records? ML.NET is better.

🧠 Architect’s Note

ML.NET's sweet spot is structured data at scale with zero cloud cost per prediction. For every scenario where you're calling an LLM API to classify or predict structured data, evaluate whether ML.NET can do it locally, faster, and cheaper.

AI-Friendly Summary

Summary

ML.NET is Microsoft's open-source machine learning framework for .NET. It handles predictive ML tasks: classification, regression, forecasting, clustering, anomaly detection. It runs on-device without cloud dependencies. ML.NET complements generative AI (Azure OpenAI/Semantic Kernel) — use ML.NET for structured predictions, generative AI for text/reasoning.

Key Takeaways

  • ML.NET = predictive ML in .NET (classification, regression, forecasting)
  • Runs on-device — no cloud API, no cost per prediction
  • Pipeline model: load data → transform → train → evaluate → predict
  • Complements generative AI — different problems, not competing
  • Supports custom models and ONNX model import

Implementation Checklist

  • Install Microsoft.ML NuGet package
  • Define input/output data classes
  • Create an MLContext
  • Build a pipeline: data loading → transforms → trainer
  • Train the model and evaluate metrics
  • Use PredictionEngine for inference

Frequently Asked Questions

What is ML.NET?

ML.NET is Microsoft's open-source machine learning framework for .NET. It lets you train and deploy traditional ML models (classification, regression, forecasting, anomaly detection) entirely in C# without needing Python, R, or external services. It runs on-device — no cloud API calls required.

What is the difference between ML.NET and Azure OpenAI?

ML.NET handles predictive ML: classify data, predict numbers, forecast time series, detect anomalies. Azure OpenAI handles generative AI: generate text, chat, reason, and create content. They solve different problems. Many production systems use both — ML.NET for structured predictions, Azure OpenAI for natural language.

Is ML.NET still relevant in 2026?

Yes, for its domain. LLMs can't efficiently classify 100,000 rows of structured data or forecast sales for the next quarter. ML.NET handles these tasks faster, cheaper, and more reliably. It's not competing with generative AI — it complements it.

Can I use ML.NET without cloud services?

Yes. ML.NET runs entirely on-device. Training, evaluation, and inference all happen in your .NET process. No cloud calls, no API keys, no usage fees. This makes it ideal for edge deployment, sensitive data, and cost-controlled scenarios.

Track your progress through this learning path.

You Might Also Enjoy

#ML.NET #Machine Learning #.NET AI #Classification #Predictive AI

Was this article useful?

Feedback is anonymous and helps us improve content quality.