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:
| Scenario | Use ML.NET | Use Generative AI |
|---|---|---|
| Classify 100K records | ✅ Fast, cheap | ❌ Slow, expensive |
| Analyze free-text sentiment | Possible 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-device | Possible but costly per-call |
| Answer customer questions | ❌ | ✅ Natural language |
| Predict churn probability | ✅ Structured data | Possible 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
- ML.NET Sentiment Analysis: Complete Tutorial — Full hands-on classification tutorial
- ONNX Models in .NET — Import Python-trained models into .NET
- What is Generative AI for .NET Developers? — The other side of .NET AI