How to write a sample program to get started with AI program in C#

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:

  1. Make sure you have the .NET SDK installed on your system.
  2. Create a new console application project.
  3. Install the ML.NET NuGet package by running this command in the terminal:dotnet add package Microsoft.ML
  4. Replace the contents of your Program.cs file with the code above.
  5. Download the Iris dataset (iris.csv) and place it in your project directory.
  6. Build and run the program using:dotnet run

This program demonstrates:

  1. Loading and preprocessing data
  2. Splitting data into training and test sets
  3. Building and training a machine learning model
  4. Evaluating the model’s performance
  5. 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

error: Content is protected !!