Machine Learning is becoming very popular, and if you are a .NET developer, the best way to start Machine Learning is by using ML.NET. In this blog, we will create our first Machine Learning project using ML.NET step-by-step in simple language.
This guide is perfect for beginners who know C# / .NET but are new to Machine Learning.
1. What is ML.NET?
ML.NET is a Machine Learning framework created by Microsoft that allows .NET developers to build AI/ML models using C# or F# without learning Python.
With ML.NET you can build:
- Spam detection
- Price prediction
- Recommendation system
- Sentiment analysis
- Image classification
Official site:
https://dotnet.microsoft.com/apps/machinelearning-ai/ml-dotnet
2. System Requirements
Before starting, install:
- Visual Studio 2022
- .NET SDK 6 or later
- NuGet Package Manager
Install ML.NET package:
Install-Package Microsoft.ML
3. Our First Project – Price Prediction Model
We will create a simple ML model that predicts House Price based on size.
Example data:
| Size | Price |
|---|---|
| 1 | 10000 |
| 2 | 20000 |
| 3 | 30000 |
| 4 | 40000 |
We will train ML model using this data.
4. Step 1 – Create Console Project
Create new project:
Console App (.NET)
Install package:
Microsoft.ML
5. Step 2 – Create Data Model
Create class:
using Microsoft.ML.Data;
public class HouseData
{
[LoadColumn(0)]
public float Size;
[LoadColumn(1)]
public float Price;
}
public class HousePrediction
{
[ColumnName("Score")]
public float Price;
}
6. Step 3 – Write ML Code
using Microsoft.ML;
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
var context = new MLContext();
var data = new List<HouseData>()
{
new HouseData{ Size = 1, Price = 10000 },
new HouseData{ Size = 2, Price = 20000 },
new HouseData{ Size = 3, Price = 30000 },
new HouseData{ Size = 4, Price = 40000 }
};
var trainingData = context.Data.LoadFromEnumerable(data);
var pipeline = context.Transforms
.Concatenate("Features", nameof(HouseData.Size))
.Append(context.Regression.Trainers.Sdca(
labelColumnName: "Price",
maximumNumberOfIterations: 100));
var model = pipeline.Fit(trainingData);
var predictor = context.Model.CreatePredictionEngine
<HouseData, HousePrediction>(model);
var prediction = predictor.Predict(
new HouseData { Size = 5 });
Console.WriteLine(
$"Predicted price: {prediction.Price}");
}
}
7. Output
Predicted price: 50000 (approx)
Model learned pattern:
Price = Size × 10000
This is called Regression Model in Machine Learning.
8. What We Learned
In this first ML.NET project we learned:
- What is ML.NET
- How to install ML.NET
- How to create model
- How to train data
- How to predict value
This is the basic workflow of Machine Learning.
Data → Train → Model → Predict
Conclusion
- ML.NET makes Machine Learning easy for .NET developers.
- You do not need Python to start AI.
- With ML.NET you can build real AI applications using C#.