C# program to get started with AI programming using ML.NET:
csharpCopy codeusing System;
using Microsoft.ML;
using Microsoft.ML.Data;
class Program
{
// Define the structure for input data
public class IrisData
{
[LoadColumn(0)]
public float SepalLength;
[LoadColumn(1)]
public float SepalWidth;
[LoadColumn(2)]
public float PetalLength;
[LoadColumn(3)]
public float PetalWidth;
[LoadColumn(4)]
public string Label;
}
// Define the structure for making a single prediction
public class IrisPrediction
{
[ColumnName("PredictedLabel")]
public string PredictedLabels;
}
static void Main(string[] args)
{
// Create MLContext
MLContext mlContext = new MLContext();
// Load data
IDataView dataView = mlContext.Data.LoadFromTextFile<IrisData>("iris.csv", hasHeader: true, separatorChar: ',');
// Split data into training (80%) and test (20%) sets
var trainTestData = mlContext.Data.TrainTestSplit(dataView, testFraction: 0.2);
// Build and train the model
var pipeline = mlContext.Transforms.Conversion.MapValueToKey("Label")
.Append(mlContext.Transforms.Concatenate("Features", "SepalLength", "SepalWidth", "PetalLength", "PetalWidth"))
.Append(mlContext.MulticlassClassification.Trainers.SdcaMaximumEntropy())
.Append(mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabel"));
var model = pipeline.Fit(trainTestData.TrainSet);
// Make predictions on test data
var predictions = model.Transform(trainTestData.TestSet);
// Evaluate the model
var metrics = mlContext.MulticlassClassification.Evaluate(predictions);
Console.WriteLine($"Macro Accuracy: {metrics.MacroAccuracy:F2}");
// Use the model for a single prediction
var predictionEngine = mlContext.Model.CreatePredictionEngine<IrisData, IrisPrediction>(model);
var sampleIris = new IrisData()
{
SepalLength = 5.1f,
SepalWidth = 3.5f,
PetalLength = 1.4f,
PetalWidth = 0.2f
};
var prediction = predictionEngine.Predict(sampleIris);
Console.WriteLine($"Predicted flower type is: {prediction.PredictedLabels}");
}
}
To run this program:
- Make sure you have the .NET SDK installed on your system.
- Create a new console application project.
- Install the ML.NET NuGet package by running this command in the terminal:
dotnet add package Microsoft.ML - Replace the contents of your
Program.csfile with the code above. - Download the Iris dataset (iris.csv) and place it in your project directory.
- Build and run the program using:
dotnet run
This program demonstrates:
- Loading and preprocessing data
- Splitting data into training and test sets
- Building and training a machine learning model
- Evaluating the model’s performance
- Using the model to make predictions on new data
As you progress, you can explore more complex algorithms and datasets within the ML.NET framework.
Read more from our Blogs .

Leave a Reply